summaryrefslogtreecommitdiff
path: root/src/mscorlib/src
diff options
context:
space:
mode:
Diffstat (limited to 'src/mscorlib/src')
-rw-r--r--src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.cs72
-rw-r--r--src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.cs131
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs60
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Win32Native.cs24
-rw-r--r--src/mscorlib/src/System/AccessViolationException.cs6
-rw-r--r--src/mscorlib/src/System/Activator.cs258
-rw-r--r--src/mscorlib/src/System/AppDomain.cs178
-rw-r--r--src/mscorlib/src/System/AppDomainAttributes.cs1
-rw-r--r--src/mscorlib/src/System/AppDomainSetup.cs14
-rw-r--r--src/mscorlib/src/System/AppDomainUnloadedException.cs2
-rw-r--r--src/mscorlib/src/System/ArgumentOutOfRangeException.cs118
-rw-r--r--src/mscorlib/src/System/Array.cs3
-rw-r--r--src/mscorlib/src/System/ArraySegment.cs1
-rw-r--r--src/mscorlib/src/System/BCLDebug.cs2
-rw-r--r--src/mscorlib/src/System/BadImageFormatException.CoreCLR.cs19
-rw-r--r--src/mscorlib/src/System/BadImageFormatException.cs162
-rw-r--r--src/mscorlib/src/System/Boolean.cs6
-rw-r--r--src/mscorlib/src/System/Byte.cs2
-rw-r--r--src/mscorlib/src/System/Collections/ArrayList.cs626
-rw-r--r--src/mscorlib/src/System/Collections/Comparer.cs27
-rw-r--r--src/mscorlib/src/System/Collections/CompatibleComparer.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs1
-rw-r--r--src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Comparer.cs3
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Dictionary.cs44
-rw-r--r--src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs34
-rw-r--r--src/mscorlib/src/System/Collections/Generic/List.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Hashtable.cs72
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs4
-rw-r--r--src/mscorlib/src/System/Currency.cs1
-rw-r--r--src/mscorlib/src/System/Delegate.cs4
-rw-r--r--src/mscorlib/src/System/DelegateSerializationHolder.cs287
-rw-r--r--src/mscorlib/src/System/Diagnostics/AssertFilter.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/AssertFilters.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs13
-rw-r--r--src/mscorlib/src/System/Diagnostics/Debug.Unix.cs95
-rw-r--r--src/mscorlib/src/System/Diagnostics/Debugger.cs114
-rw-r--r--src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs3
-rw-r--r--src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs175
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs116
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs20
-rw-r--r--src/mscorlib/src/System/Diagnostics/LogSwitch.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/LoggingLevels.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/Stackframe.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/Stacktrace.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/log.cs2
-rw-r--r--src/mscorlib/src/System/DllNotFoundException.cs45
-rw-r--r--src/mscorlib/src/System/Double.cs2
-rw-r--r--src/mscorlib/src/System/Empty.cs9
-rw-r--r--src/mscorlib/src/System/Environment.cs3
-rw-r--r--src/mscorlib/src/System/Exception.cs102
-rw-r--r--src/mscorlib/src/System/GC.cs3
-rw-r--r--src/mscorlib/src/System/Globalization/BidiCategory.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/Calendar.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarData.Unix.cs339
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarData.Windows.cs49
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.cs34
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.Unix.cs431
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.Windows.cs98
-rw-r--r--src/mscorlib/src/System/Globalization/CultureInfo.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingDataItem.cs2
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendar.cs3
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs2
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.Unix.cs15
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs96
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.WinRT.cs16
-rw-r--r--src/mscorlib/src/System/Globalization/IdnMapping.Unix.cs142
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs96
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs209
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.cs62
-rw-r--r--src/mscorlib/src/System/Globalization/NumberFormatInfo.cs900
-rw-r--r--src/mscorlib/src/System/Globalization/RegionInfo.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/SortKey.cs203
-rw-r--r--src/mscorlib/src/System/Globalization/StringInfo.cs374
-rw-r--r--src/mscorlib/src/System/Globalization/TextElementEnumerator.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.cs32
-rw-r--r--src/mscorlib/src/System/IO/BinaryWriter.cs1
-rw-r--r--src/mscorlib/src/System/IO/DriveNotFoundException.cs2
-rw-r--r--src/mscorlib/src/System/IO/EncodingCache.cs13
-rw-r--r--src/mscorlib/src/System/IO/File.cs27
-rw-r--r--src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs5
-rw-r--r--src/mscorlib/src/System/IO/FileSystemEnumerable.cs19
-rw-r--r--src/mscorlib/src/System/IO/IOException.cs2
-rw-r--r--src/mscorlib/src/System/IO/MemoryStream.cs1
-rw-r--r--src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs76
-rw-r--r--src/mscorlib/src/System/IO/SearchOption.cs1
-rw-r--r--src/mscorlib/src/System/IO/Stream.cs3
-rw-r--r--src/mscorlib/src/System/IO/StreamReader.cs1
-rw-r--r--src/mscorlib/src/System/IO/TextReader.cs3
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs731
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs220
-rw-r--r--src/mscorlib/src/System/IO/__Error.cs6
-rw-r--r--src/mscorlib/src/System/InsufficientMemoryException.cs5
-rw-r--r--src/mscorlib/src/System/Int16.cs2
-rw-r--r--src/mscorlib/src/System/Int32.cs2
-rw-r--r--src/mscorlib/src/System/Int64.cs2
-rw-r--r--src/mscorlib/src/System/IntPtr.cs60
-rw-r--r--src/mscorlib/src/System/MissingFieldException.cs3
-rw-r--r--src/mscorlib/src/System/MissingMemberException.cs14
-rw-r--r--src/mscorlib/src/System/MulticastDelegate.cs45
-rw-r--r--src/mscorlib/src/System/Object.cs1
-rw-r--r--src/mscorlib/src/System/OleAutBinder.cs1
-rw-r--r--src/mscorlib/src/System/OperatingSystem.cs154
-rw-r--r--src/mscorlib/src/System/OperationCanceledException.cs73
-rw-r--r--src/mscorlib/src/System/OutOfMemoryException.cs2
-rw-r--r--src/mscorlib/src/System/PlatformID.cs27
-rw-r--r--src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs80
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyName.cs67
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttribute.cs31
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EventToken.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FieldToken.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FlowControl.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/Label.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodToken.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OperandType.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/StringToken.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SymbolType.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeToken.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/MdFieldInfo.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/MdImport.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs39
-rw-r--r--src/mscorlib/src/System/Reflection/RtFieldInfo.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeAssembly.cs31
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs6
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs10
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeModule.cs8
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs31
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs7
-rw-r--r--src/mscorlib/src/System/Resources/ResourceFallbackManager.cs96
-rw-r--r--src/mscorlib/src/System/Resources/ResourceManager.cs1
-rw-r--r--src/mscorlib/src/System/Resources/ResourceSet.cs84
-rw-r--r--src/mscorlib/src/System/Resources/RuntimeResourceSet.cs462
-rw-r--r--src/mscorlib/src/System/RtType.cs22
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs38
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs14
-rw-r--r--src/mscorlib/src/System/Runtime/GcSettings.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/COMException.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs128
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs5
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/PInvokeMarshal.cs24
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs40
-rw-r--r--src/mscorlib/src/System/Runtime/RuntimeImports.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs1
-rw-r--r--src/mscorlib/src/System/RuntimeHandles.cs98
-rw-r--r--src/mscorlib/src/System/SByte.cs2
-rw-r--r--src/mscorlib/src/System/SharedStatics.cs1
-rw-r--r--src/mscorlib/src/System/Single.cs2
-rw-r--r--src/mscorlib/src/System/StubHelpers.cs31
-rw-r--r--src/mscorlib/src/System/Text/DecoderBestFitFallback.cs1
-rw-r--r--src/mscorlib/src/System/Text/DecoderExceptionFallback.cs3
-rw-r--r--src/mscorlib/src/System/Text/DecoderFallback.cs1
-rw-r--r--src/mscorlib/src/System/Text/DecoderNLS.cs16
-rw-r--r--src/mscorlib/src/System/Text/DecoderReplacementFallback.cs1
-rw-r--r--src/mscorlib/src/System/Text/EncoderBestFitFallback.cs1
-rw-r--r--src/mscorlib/src/System/Text/EncoderExceptionFallback.cs6
-rw-r--r--src/mscorlib/src/System/Text/EncoderFallback.cs1
-rw-r--r--src/mscorlib/src/System/Text/EncoderNLS.cs17
-rw-r--r--src/mscorlib/src/System/Text/EncoderReplacementFallback.cs1
-rw-r--r--src/mscorlib/src/System/Text/Encoding.cs100
-rw-r--r--src/mscorlib/src/System/Text/Latin1Encoding.cs25
-rw-r--r--src/mscorlib/src/System/Text/UTF7Encoding.cs52
-rw-r--r--src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Unix.cs21
-rw-r--r--src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs42
-rw-r--r--src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs23
-rw-r--r--src/mscorlib/src/System/Threading/Monitor.cs1
-rw-r--r--src/mscorlib/src/System/Threading/PinnableBufferCache.cs544
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/Task.cs3
-rw-r--r--src/mscorlib/src/System/Threading/Thread.cs1
-rw-r--r--src/mscorlib/src/System/Threading/ThreadInterruptedException.cs2
-rw-r--r--src/mscorlib/src/System/Threading/Timer.cs14
-rw-r--r--src/mscorlib/src/System/Threading/WaitHandle.cs1
-rw-r--r--src/mscorlib/src/System/TypeLoadException.cs21
-rw-r--r--src/mscorlib/src/System/UInt16.cs2
-rw-r--r--src/mscorlib/src/System/UInt32.cs2
-rw-r--r--src/mscorlib/src/System/UInt64.cs2
-rw-r--r--src/mscorlib/src/System/UIntPtr.cs46
-rw-r--r--src/mscorlib/src/System/Variant.cs1
-rw-r--r--src/mscorlib/src/System/__HResults.cs1
229 files changed, 1556 insertions, 8376 deletions
diff --git a/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.cs b/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.cs
deleted file mode 100644
index fe14560a3a..0000000000
--- a/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.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;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.InteropServices;
-using System.Security;
-
-internal static partial class Interop
-{
- internal static partial class GlobalizationInterop
- {
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortHandle")]
- internal unsafe static extern ResultCode GetSortHandle(byte[] localeName, out SafeSortHandle sortHandle);
-
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CloseSortHandle")]
- internal unsafe static extern void CloseSortHandle(IntPtr handle);
-
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareString")]
- internal unsafe static extern int CompareString(SafeSortHandle sortHandle, char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len, CompareOptions options);
-
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOf")]
- internal unsafe static extern int IndexOf(SafeSortHandle sortHandle, string target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr);
-
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_LastIndexOf")]
- internal unsafe static extern int LastIndexOf(SafeSortHandle sortHandle, string target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options);
-
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOfOrdinalIgnoreCase")]
- internal unsafe static extern int IndexOfOrdinalIgnoreCase(string target, int cwTargetLength, char* pSource, int cwSourceLength, bool findLast);
-
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_StartsWith")]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal unsafe static extern bool StartsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options);
-
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EndsWith")]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal unsafe static extern bool EndsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options);
-
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortKey")]
- internal unsafe static extern int GetSortKey(SafeSortHandle sortHandle, string str, int strLength, byte* sortKey, int sortKeyLength, CompareOptions options);
-
- [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareStringOrdinalIgnoreCase")]
- internal unsafe static extern int CompareStringOrdinalIgnoreCase(char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len);
-
- [DllImport(Libraries.GlobalizationInterop, EntryPoint = "GlobalizationNative_GetSortVersion")]
- internal static extern int GetSortVersion();
-
- internal class SafeSortHandle : SafeHandle
- {
- private SafeSortHandle() :
- base(IntPtr.Zero, true)
- {
- }
-
- public override bool IsInvalid
- {
- get { return handle == IntPtr.Zero; }
- }
-
- protected override bool ReleaseHandle()
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- CloseSortHandle(handle);
- SetHandle(IntPtr.Zero);
- return true;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.cs b/src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.cs
deleted file mode 100644
index 2bb349d670..0000000000
--- a/src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.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 System;
-using System.Runtime.InteropServices;
-
-internal static partial class Interop
-{
- internal static unsafe partial class Kernel32
- {
- internal const int LOCALE_NAME_MAX_LENGTH = 85;
- internal const uint LOCALE_ALLOW_NEUTRAL_NAMES = 0x08000000; // Flag to allow returning neutral names/lcids for name conversion
- internal const uint LOCALE_SUPPLEMENTAL = 0x00000002;
- internal const uint LOCALE_REPLACEMENT = 0x00000008;
- internal const uint LOCALE_NEUTRALDATA = 0x00000010;
- internal const uint LOCALE_SPECIFICDATA = 0x00000020;
- internal const int COMPARE_STRING = 0x0001;
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static unsafe int LCIDToLocaleName(int locale, char *pLocaleName, int cchName, uint dwFlags);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static int LocaleNameToLCID(string lpName, uint dwFlags);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static unsafe int LCMapStringEx(
- string lpLocaleName,
- uint dwMapFlags,
- char* lpSrcStr,
- int cchSrc,
- void* lpDestStr,
- int cchDest,
- void* lpVersionInformation,
- void* lpReserved,
- IntPtr sortHandle);
-
- [DllImport("kernel32.dll", EntryPoint = "FindNLSStringEx")]
- internal extern static unsafe int FindNLSStringEx(
- char* lpLocaleName,
- uint dwFindNLSStringFlags,
- char* lpStringSource,
- int cchSource,
- char* lpStringValue,
- int cchValue,
- int* pcchFound,
- void* lpVersionInformation,
- void* lpReserved,
- IntPtr sortHandle);
-
- [DllImport("kernel32.dll", EntryPoint = "CompareStringEx")]
- internal extern static unsafe int CompareStringEx(
- char* lpLocaleName,
- uint dwCmpFlags,
- char* lpString1,
- int cchCount1,
- char* lpString2,
- int cchCount2,
- void* lpVersionInformation,
- void* lpReserved,
- IntPtr lParam);
-
- [DllImport("kernel32.dll", EntryPoint = "CompareStringOrdinal")]
- internal extern static unsafe int CompareStringOrdinal(
- char* lpString1,
- int cchCount1,
- char* lpString2,
- int cchCount2,
- bool bIgnoreCase);
-
- [DllImport("kernel32.dll", EntryPoint = "FindStringOrdinal")]
- internal extern static unsafe int FindStringOrdinal(
- uint dwFindStringOrdinalFlags,
- char* lpStringSource,
- int cchSource,
- char* lpStringValue,
- int cchValue,
- int bIgnoreCase);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static unsafe bool IsNLSDefinedString(
- int Function,
- uint dwFlags,
- IntPtr lpVersionInformation,
- char* lpString,
- int cchStr);
-
- [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
- internal static extern bool GetUserPreferredUILanguages(uint dwFlags, out uint pulNumLanguages, char [] pwszLanguagesBuffer, ref uint pcchLanguagesBuffer);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, IntPtr lpLCData, int cchData);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved);
-
- internal delegate BOOL EnumLocalesProcEx(IntPtr lpLocaleString, uint dwFlags, IntPtr lParam);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static int ResolveLocaleName(string lpNameToResolve, char* lpLocaleName, int cchLocaleName);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam);
-
- internal delegate BOOL EnumTimeFormatsProcEx(IntPtr lpTimeFormatString, IntPtr lParam);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam);
-
- internal delegate BOOL EnumCalendarInfoProcExEx(IntPtr lpCalendarInfoString, uint Calendar, IntPtr lpReserved, IntPtr lParam);
-
- [StructLayout(LayoutKind.Sequential)]
- internal struct NlsVersionInfoEx
- {
- internal int dwNLSVersionInfoSize;
- internal int dwNLSVersion;
- internal int dwDefinedVersion;
- internal int dwEffectiveId;
- internal Guid guidCustomVersion;
- }
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- internal extern static unsafe bool GetNLSVersionEx(int function, string localeName, NlsVersionInfoEx* lpVersionInformation);
- }
-}
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
deleted file mode 100644
index 8a7f591dfc..0000000000
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
+++ /dev/null
@@ -1,60 +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.
-
-//
-// Abstract derivations of SafeHandle designed to provide the common
-// functionality supporting Win32 handles. More specifically, they describe how
-// an invalid handle looks (for instance, some handles use -1 as an invalid
-// handle value, others use 0).
-//
-// Further derivations of these classes can specialise this even further (e.g.
-// file or registry handles).
-//
-//
-
-using System;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
-
-namespace Microsoft.Win32.SafeHandles
-{
- // Class of safe handle which uses 0 or -1 as an invalid handle.
- public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle
- {
- protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
- {
- }
-
- // A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime
- protected SafeHandleZeroOrMinusOneIsInvalid()
- {
- throw new NotImplementedException();
- }
-
- public override bool IsInvalid
- {
- get { return handle.IsNull() || handle == new IntPtr(-1); }
- }
- }
-
- // Class of safe handle which uses only -1 as an invalid handle.
- public abstract class SafeHandleMinusOneIsInvalid : SafeHandle
- {
- protected SafeHandleMinusOneIsInvalid(bool ownsHandle) : base(new IntPtr(-1), ownsHandle)
- {
- }
-
- // A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime
- protected SafeHandleMinusOneIsInvalid()
- {
- throw new NotImplementedException();
- }
-
- public override bool IsInvalid
- {
- get { return handle == new IntPtr(-1); }
- }
- }
-}
diff --git a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
index 8543bc8a99..b05445961d 100644
--- a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
+++ b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
@@ -93,7 +93,6 @@ namespace Microsoft.Win32
using System.Security;
using System.Text;
using System.Configuration.Assemblies;
- using System.Runtime.Remoting;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
@@ -400,7 +399,6 @@ namespace Microsoft.Win32
internal int bInheritHandle = 0;
}
- [Serializable]
[StructLayout(LayoutKind.Sequential)]
internal struct WIN32_FILE_ATTRIBUTE_DATA
{
@@ -461,13 +459,11 @@ namespace Microsoft.Win32
internal const String USER32 = "user32.dll";
internal const String OLE32 = "ole32.dll";
internal const String OLEAUT32 = "oleaut32.dll";
- internal const String NTDLL = "ntdll.dll";
#else //FEATURE_PAL
internal const String KERNEL32 = "libcoreclr";
internal const String USER32 = "libcoreclr";
internal const String OLE32 = "libcoreclr";
internal const String OLEAUT32 = "libcoreclr";
- internal const String NTDLL = "libcoreclr";
#endif //FEATURE_PAL
internal const String ADVAPI32 = "advapi32.dll";
internal const String SHELL32 = "shell32.dll";
@@ -476,9 +472,6 @@ namespace Microsoft.Win32
internal const String SECUR32 = "secur32.dll";
internal const String MSCORWKS = "coreclr.dll";
- // From WinBase.h
- internal const int SEM_FAILCRITICALERRORS = 1;
-
[DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = true)]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer,
@@ -509,10 +502,6 @@ namespace Microsoft.Win32
[DllImport(KERNEL32, SetLastError = true)]
internal static extern IntPtr LocalFree(IntPtr handle);
- // MSDN says the length is a SIZE_T.
- [DllImport(NTDLL, EntryPoint = "RtlZeroMemory")]
- internal static extern void ZeroMemory(IntPtr address, UIntPtr length);
-
internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer)
{
buffer.length = Marshal.SizeOf(typeof(MEMORYSTATUSEX));
@@ -733,7 +722,6 @@ namespace Microsoft.Win32
}
// Win32 Structs in N/Direct style
- [Serializable]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
[BestFitMapping(false)]
internal class WIN32_FIND_DATA
@@ -783,18 +771,6 @@ namespace Microsoft.Win32
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool SetCurrentDirectory(String path);
- [DllImport(KERNEL32, SetLastError = false, EntryPoint = "SetErrorMode", ExactSpelling = true)]
- private static extern int SetErrorMode_VistaAndOlder(int newMode);
-
- // RTM versions of Win7 and Windows Server 2008 R2
- private static readonly Version ThreadErrorModeMinOsVersion = new Version(6, 1, 7600);
-
- // this method uses the thread-safe version of SetErrorMode on Windows 7 / Windows Server 2008 R2 operating systems.
- internal static int SetErrorMode(int newMode)
- {
- return SetErrorMode_VistaAndOlder(newMode);
- }
-
internal const int LCID_SUPPORTED = 0x00000002; // supported locale ids
[DllImport(KERNEL32)]
diff --git a/src/mscorlib/src/System/AccessViolationException.cs b/src/mscorlib/src/System/AccessViolationException.cs
index 12911c1b17..23d086fb42 100644
--- a/src/mscorlib/src/System/AccessViolationException.cs
+++ b/src/mscorlib/src/System/AccessViolationException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class AccessViolationException : SystemException
{
public AccessViolationException()
@@ -37,7 +36,10 @@ namespace System
HResult = __HResults.E_POINTER;
}
- protected AccessViolationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected AccessViolationException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
#pragma warning disable 169 // Field is not used from managed.
private IntPtr _ip; // Address of faulting instruction.
diff --git a/src/mscorlib/src/System/Activator.cs b/src/mscorlib/src/System/Activator.cs
index 34c6ea5874..d11739b826 100644
--- a/src/mscorlib/src/System/Activator.cs
+++ b/src/mscorlib/src/System/Activator.cs
@@ -16,7 +16,6 @@ namespace System
{
using System;
using System.Reflection;
- using System.Runtime.Remoting;
using System.Security;
using CultureInfo = System.Globalization.CultureInfo;
using Evidence = System.Security.Policy.Evidence;
@@ -113,47 +112,6 @@ namespace System
return Activator.CreateInstance(type, false);
}
- /*
- * Create an instance using the name of type and the assembly where it exists. This allows
- * types to be created remotely without having to load the type locally.
- */
-
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- static public ObjectHandle CreateInstance(String assemblyName,
- String typeName)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return CreateInstance(assemblyName,
- typeName,
- false,
- Activator.ConstructorDefault,
- null,
- null,
- null,
- null,
- null,
- ref stackMark);
- }
-
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- static public ObjectHandle CreateInstance(String assemblyName,
- String typeName,
- Object[] activationAttributes)
-
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return CreateInstance(assemblyName,
- typeName,
- false,
- Activator.ConstructorDefault,
- null,
- null,
- null,
- activationAttributes,
- null,
- ref stackMark);
- }
-
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public Object CreateInstance(Type type, bool nonPublic)
{
@@ -185,221 +143,5 @@ namespace System
// Skip the CreateInstanceCheckThis call to avoid perf cost and to maintain compatibility with V2 (throwing the same exceptions).
return (T)rt.CreateInstanceDefaultCtor(true /*publicOnly*/, true /*skipCheckThis*/, true /*fillCache*/, ref stackMark);
}
-
- static public ObjectHandle CreateInstanceFrom(String assemblyFile,
- String typeName)
-
- {
- return CreateInstanceFrom(assemblyFile, typeName, null);
- }
-
- static public ObjectHandle CreateInstanceFrom(String assemblyFile,
- String typeName,
- Object[] activationAttributes)
-
- {
- return CreateInstanceFrom(assemblyFile,
- typeName,
- false,
- Activator.ConstructorDefault,
- null,
- null,
- null,
- activationAttributes);
- }
-
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public static ObjectHandle CreateInstance(string assemblyName,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- object[] args,
- CultureInfo culture,
- object[] activationAttributes)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return CreateInstance(assemblyName,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes,
- null,
- ref stackMark);
- }
-
- static internal ObjectHandle CreateInstance(String assemblyString,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityInfo,
- ref StackCrawlMark stackMark)
- {
- Type type = null;
- Assembly assembly = null;
- if (assemblyString == null)
- {
- assembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- }
- else
- {
- RuntimeAssembly assemblyFromResolveEvent;
- AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, false /*forIntrospection*/, out assemblyFromResolveEvent);
- if (assemblyFromResolveEvent != null)
- {
- // Assembly was resolved via AssemblyResolve event
- assembly = assemblyFromResolveEvent;
- }
- else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime)
- {
- // WinRT type - we have to use Type.GetType
- type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase);
- }
- else
- {
- // Classic managed type
- assembly = RuntimeAssembly.InternalLoadAssemblyName(
- assemblyName, securityInfo, null, ref stackMark,
- true /*thrownOnFileNotFound*/, false /*forIntrospection*/);
- }
- }
-
- if (type == null)
- {
- // It's classic managed type (not WinRT type)
- Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyString);
- if (assembly == null) return null;
-
- type = assembly.GetType(typeName, true /*throwOnError*/, ignoreCase);
- }
-
- Object o = Activator.CreateInstance(type,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes);
-
- Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
- if (o == null)
- return null;
- else
- {
- ObjectHandle Handle = new ObjectHandle(o);
- return Handle;
- }
- }
-
- public static ObjectHandle CreateInstanceFrom(string assemblyFile,
- string typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- object[] args,
- CultureInfo culture,
- object[] activationAttributes)
- {
- return CreateInstanceFromInternal(assemblyFile,
- typeName,
- ignoreCase,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes,
- null);
- }
-
- private static ObjectHandle CreateInstanceFromInternal(String assemblyFile,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityInfo)
- {
-#pragma warning disable 618
- Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo);
-#pragma warning restore 618
- Type t = assembly.GetType(typeName, true, ignoreCase);
-
- Object o = Activator.CreateInstance(t,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes);
-
- Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
- if (o == null)
- return null;
- else
- {
- ObjectHandle Handle = new ObjectHandle(o);
- return Handle;
- }
- }
-
- public static ObjectHandle CreateComInstanceFrom(String assemblyName,
- String typeName)
- {
- return CreateComInstanceFrom(assemblyName,
- typeName,
- null,
- AssemblyHashAlgorithm.None);
- }
-
- public static ObjectHandle CreateComInstanceFrom(String assemblyName,
- String typeName,
- byte[] hashValue,
- AssemblyHashAlgorithm hashAlgorithm)
- {
- Assembly assembly = Assembly.LoadFrom(assemblyName, hashValue, hashAlgorithm);
-
- Type t = assembly.GetType(typeName, true, false);
-
- Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute), false);
- if (Attr.Length > 0)
- {
- if (((ComVisibleAttribute)Attr[0]).Value == false)
- throw new TypeLoadException(SR.Argument_TypeMustBeVisibleFromCom);
- }
-
- Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName);
-
- if (assembly == null) return null;
-
-
- Object o = Activator.CreateInstance(t,
- Activator.ConstructorDefault,
- null,
- null,
- null,
- null);
-
- Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
- if (o == null)
- return null;
- else
- {
- ObjectHandle Handle = new ObjectHandle(o);
- return Handle;
- }
- }
-
- [System.Diagnostics.Conditional("_DEBUG")]
- private static void Log(bool test, string title, string success, string failure)
- {
- }
}
}
-
diff --git a/src/mscorlib/src/System/AppDomain.cs b/src/mscorlib/src/System/AppDomain.cs
index 7d2f2ceaf8..24c6765026 100644
--- a/src/mscorlib/src/System/AppDomain.cs
+++ b/src/mscorlib/src/System/AppDomain.cs
@@ -25,7 +25,6 @@ namespace System
using System.Collections.Generic;
using System.Threading;
using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
using System.Reflection.Emit;
using CultureInfo = System.Globalization.CultureInfo;
using System.IO;
@@ -37,7 +36,6 @@ namespace System
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
- [Serializable]
internal delegate void AppDomainInitializer(string[] args);
internal class AppDomainInitializerInfo
@@ -258,18 +256,6 @@ namespace System
private static extern APPX_FLAGS nGetAppXFlags();
#endif
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void GetAppDomainManagerType(AppDomainHandle domain,
- StringHandleOnStack retAssembly,
- StringHandleOnStack retType);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void SetAppDomainManagerType(AppDomainHandle domain,
- string assembly,
- string type);
-
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetSecurityHomogeneousFlag(AppDomainHandle domain,
@@ -328,54 +314,6 @@ namespace System
SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths, appLocalWinMD);
}
- string domainManagerAssembly;
- string domainManagerType;
- GetAppDomainManagerType(out domainManagerAssembly, out domainManagerType);
-
- if (domainManagerAssembly != null && domainManagerType != null)
- {
- try
- {
- _domainManager = CreateInstanceAndUnwrap(domainManagerAssembly, domainManagerType) as AppDomainManager;
- }
- catch (FileNotFoundException e)
- {
- throw new TypeLoadException(SR.Argument_NoDomainManager, e);
- }
- catch (SecurityException e)
- {
- throw new TypeLoadException(SR.Argument_NoDomainManager, e);
- }
- catch (TypeLoadException e)
- {
- throw new TypeLoadException(SR.Argument_NoDomainManager, e);
- }
-
- if (_domainManager == null)
- {
- throw new TypeLoadException(SR.Argument_NoDomainManager);
- }
-
- // If this domain was not created by a managed call to CreateDomain, then the AppDomainSetup
- // will not have the correct values for the AppDomainManager set.
- FusionStore.AppDomainManagerAssembly = domainManagerAssembly;
- FusionStore.AppDomainManagerType = domainManagerType;
-
- bool notifyFusion = _domainManager.GetType() != typeof(System.AppDomainManager) && !DisableFusionUpdatesFromADManager();
-
-
-
- AppDomainSetup FusionStoreOld = null;
- if (notifyFusion)
- FusionStoreOld = new AppDomainSetup(FusionStore, true);
-
- // Initialize the AppDomainMAnager and register the instance with the native host if requested
- _domainManager.InitializeNewDomain(FusionStore);
-
- if (notifyFusion)
- SetupFusionStore(_FusionStore, FusionStoreOld); // Notify Fusion about the changes the user implementation of InitializeNewDomain may have made to the FusionStore object.
- }
-
InitializeCompatibilityFlags();
}
@@ -485,34 +423,6 @@ namespace System
}
/// <summary>
- /// Get the name of the assembly and type that act as the AppDomainManager for this domain
- /// </summary>
- internal void GetAppDomainManagerType(out string assembly, out string type)
- {
- // We can't just use our parameters because we need to ensure that the strings used for hte QCall
- // are on the stack.
- string localAssembly = null;
- string localType = null;
-
- GetAppDomainManagerType(GetNativeHandle(),
- JitHelpers.GetStringHandleOnStack(ref localAssembly),
- JitHelpers.GetStringHandleOnStack(ref localType));
-
- assembly = localAssembly;
- type = localType;
- }
-
- /// <summary>
- /// Set the assembly and type which act as the AppDomainManager for this domain
- /// </summary>
- private void SetAppDomainManagerType(string assembly, string type)
- {
- Debug.Assert(assembly != null, "assembly != null");
- Debug.Assert(type != null, "type != null");
- SetAppDomainManagerType(GetNativeHandle(), assembly, type);
- }
-
- /// <summary>
/// Called for every AppDomain (including the default domain) to initialize the security of the AppDomain)
/// </summary>
private void InitializeDomainSecurity(Evidence providedSecurityInfo,
@@ -584,23 +494,6 @@ namespace System
}
}
-
- public ObjectHandle CreateInstance(String assemblyName,
- String typeName)
-
- {
- // jit does not check for that, so we should do it ...
- if (this == null)
- throw new NullReferenceException();
-
- if (assemblyName == null)
- throw new ArgumentNullException(nameof(assemblyName));
- Contract.EndContractBlock();
-
- return Activator.CreateInstance(assemblyName,
- typeName);
- }
-
public static AppDomain CurrentDomain
{
get
@@ -646,6 +539,14 @@ namespace System
return StringBuilderCache.GetStringAndRelease(sb);
}
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private extern Assembly[] nGetAssemblies(bool forIntrospection);
+
+ internal Assembly[] GetAssemblies(bool forIntrospection)
+ {
+ return nGetAssemblies(forIntrospection);
+ }
+
// this is true when we've removed the handles etc so really can't do anything
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsUnloadingForcedFinalize();
@@ -664,17 +565,6 @@ namespace System
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
- // SetData should only be used to set values that don't already exist.
- object currentVal;
- lock (((ICollection)LocalStore).SyncRoot)
- {
- LocalStore.TryGetValue(name, out currentVal);
- }
- if (currentVal != null)
- {
- throw new InvalidOperationException(SR.InvalidOperation_SetData_OnlyOnce);
- }
-
lock (((ICollection)LocalStore).SyncRoot)
{
LocalStore[name] = data;
@@ -688,38 +578,14 @@ namespace System
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
- int key = AppDomainSetup.Locate(name);
- if (key == -1)
+ object data;
+ lock (((ICollection)LocalStore).SyncRoot)
{
- if (name.Equals(AppDomainSetup.LoaderOptimizationKey))
- return FusionStore.LoaderOptimization;
- else
- {
- object data;
- lock (((ICollection)LocalStore).SyncRoot)
- {
- LocalStore.TryGetValue(name, out data);
- }
- if (data == null)
- return null;
- return data;
- }
- }
- else
- {
- // Be sure to call these properties, not Value, so
- // that the appropriate permission demand will be done
- switch (key)
- {
- case (int)AppDomainSetup.LoaderInformation.ApplicationBaseValue:
- return FusionStore.ApplicationBase;
- case (int)AppDomainSetup.LoaderInformation.ApplicationNameValue:
- return FusionStore.ApplicationName;
- default:
- Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
- return null;
- }
+ LocalStore.TryGetValue(name, out data);
}
+ if (data == null)
+ return null;
+ return data;
}
[Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)]
@@ -1150,12 +1016,6 @@ namespace System
}
#endif // FEATURE_COMINTEROP
- // set up the AppDomainManager for this domain and initialize security.
- if (adSetup.AppDomainManagerAssembly != null && adSetup.AppDomainManagerType != null)
- {
- ad.SetAppDomainManagerType(adSetup.AppDomainManagerAssembly, adSetup.AppDomainManagerType);
- }
-
ad.CreateAppDomainManager(); // could modify FusionStore's object
ad.InitializeDomainSecurity(providedSecurityInfo,
creatorsSecurityInfo,
@@ -1293,16 +1153,6 @@ namespace System
}
}
- public Object CreateInstanceAndUnwrap(String assemblyName,
- String typeName)
- {
- ObjectHandle oh = CreateInstance(assemblyName, typeName);
- if (oh == null)
- return null;
-
- return oh.Unwrap();
- } // CreateInstanceAndUnwrap
-
public Int32 Id
{
get
diff --git a/src/mscorlib/src/System/AppDomainAttributes.cs b/src/mscorlib/src/System/AppDomainAttributes.cs
index deb43eadf9..92d6d8bbb2 100644
--- a/src/mscorlib/src/System/AppDomainAttributes.cs
+++ b/src/mscorlib/src/System/AppDomainAttributes.cs
@@ -13,7 +13,6 @@
namespace System
{
- [Serializable]
internal enum LoaderOptimization
{
NotSpecified = 0,
diff --git a/src/mscorlib/src/System/AppDomainSetup.cs b/src/mscorlib/src/System/AppDomainSetup.cs
index 142b8a05f7..7714da12ab 100644
--- a/src/mscorlib/src/System/AppDomainSetup.cs
+++ b/src/mscorlib/src/System/AppDomainSetup.cs
@@ -22,10 +22,8 @@ namespace System
using System.Diagnostics.Contracts;
using System.Collections.Generic;
- [Serializable]
internal sealed class AppDomainSetup
{
- [Serializable]
internal enum LoaderInformation
{
// If you add a new value, add the corresponding property
@@ -338,18 +336,6 @@ namespace System
}
}
- static internal int Locate(String s)
- {
- if (String.IsNullOrEmpty(s))
- return -1;
-
- Debug.Assert('A' == ACTAG_APP_BASE_URL[0], "Assumption violated");
- if (s[0] == 'A' && s == ACTAG_APP_BASE_URL)
- return (int)LoaderInformation.ApplicationBaseValue;
-
- return -1;
- }
-
#if FEATURE_COMINTEROP
public bool SandboxInterop
{
diff --git a/src/mscorlib/src/System/AppDomainUnloadedException.cs b/src/mscorlib/src/System/AppDomainUnloadedException.cs
index 52cbb980af..a5e74e2b23 100644
--- a/src/mscorlib/src/System/AppDomainUnloadedException.cs
+++ b/src/mscorlib/src/System/AppDomainUnloadedException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
internal class AppDomainUnloadedException : SystemException
{
public AppDomainUnloadedException()
@@ -30,6 +29,7 @@ namespace System
//
protected AppDomainUnloadedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
deleted file mode 100644
index 90837810d1..0000000000
--- a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
+++ /dev/null
@@ -1,118 +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.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: Exception class for method arguments outside of the legal range.
-**
-**
-=============================================================================*/
-
-
-using System;
-using System.Runtime.Remoting;
-using System.Runtime.Serialization;
-using System.Globalization;
-using System.Diagnostics.Contracts;
-
-namespace System
-{
- // The ArgumentOutOfRangeException is thrown when an argument
- // is outside the legal range for that argument.
- [Serializable]
- public class ArgumentOutOfRangeException : ArgumentException, ISerializable
- {
- private static volatile String _rangeMessage;
- private Object m_actualValue;
-
- private static String RangeMessage
- {
- get
- {
- if (_rangeMessage == null)
- _rangeMessage = SR.Arg_ArgumentOutOfRangeException;
- return _rangeMessage;
- }
- }
-
- // Creates a new ArgumentOutOfRangeException with its message
- // string set to a default message explaining an argument was out of range.
- public ArgumentOutOfRangeException()
- : base(RangeMessage)
- {
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
- }
-
- public ArgumentOutOfRangeException(String paramName)
- : base(RangeMessage, paramName)
- {
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
- }
-
- public ArgumentOutOfRangeException(String paramName, String message)
- : base(message, paramName)
- {
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
- }
-
- public ArgumentOutOfRangeException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
- }
-
- // We will not use this in the classlibs, but we'll provide it for
- // anyone that's really interested so they don't have to stick a bunch
- // of printf's in their code.
- public ArgumentOutOfRangeException(String paramName, Object actualValue, String message)
- : base(message, paramName)
- {
- m_actualValue = actualValue;
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
- }
-
- public override String Message
- {
- get
- {
- String s = base.Message;
- if (m_actualValue != null)
- {
- String valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, m_actualValue.ToString());
- if (s == null)
- return valueMessage;
- return s + Environment.NewLine + valueMessage;
- }
- return s;
- }
- }
-
- // Gets the value of the argument that caused the exception.
- // Note - we don't set this anywhere in the class libraries in
- // version 1, but it might come in handy for other developers who
- // want to avoid sticking printf's in their code.
- public virtual Object ActualValue
- {
- get { return m_actualValue; }
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- base.GetObjectData(info, context);
- info.AddValue("ActualValue", m_actualValue, typeof(Object));
- }
-
- protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- m_actualValue = info.GetValue("ActualValue", typeof(Object));
- }
- }
-}
diff --git a/src/mscorlib/src/System/Array.cs b/src/mscorlib/src/System/Array.cs
index 05c4804cc5..fcfeb94675 100644
--- a/src/mscorlib/src/System/Array.cs
+++ b/src/mscorlib/src/System/Array.cs
@@ -2415,7 +2415,6 @@ namespace System
}
}
- [Serializable]
private sealed class SZArrayEnumerator : IEnumerator, ICloneable
{
private Array _array;
@@ -2461,7 +2460,6 @@ namespace System
}
}
- [Serializable]
private sealed class ArrayEnumerator : IEnumerator, ICloneable
{
private Array array;
@@ -2723,7 +2721,6 @@ namespace System
// This is a normal generic Enumerator for SZ arrays. It doesn't have any of the "this" stuff
// that SZArrayHelper does.
//
- [Serializable]
private sealed class SZGenericArrayEnumerator<T> : IEnumerator<T>
{
private T[] _array;
diff --git a/src/mscorlib/src/System/ArraySegment.cs b/src/mscorlib/src/System/ArraySegment.cs
index a18590d5d8..664352708d 100644
--- a/src/mscorlib/src/System/ArraySegment.cs
+++ b/src/mscorlib/src/System/ArraySegment.cs
@@ -316,7 +316,6 @@ namespace System
}
}
- [Serializable]
public struct Enumerator : IEnumerator<T>
{
private readonly T[] _array;
diff --git a/src/mscorlib/src/System/BCLDebug.cs b/src/mscorlib/src/System/BCLDebug.cs
index 67f7c9a0f7..4a5f6d1891 100644
--- a/src/mscorlib/src/System/BCLDebug.cs
+++ b/src/mscorlib/src/System/BCLDebug.cs
@@ -15,7 +15,6 @@ namespace System
{
using System.IO;
using System.Text;
- using System.Runtime.Remoting;
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
@@ -23,7 +22,6 @@ namespace System
using System.Security;
using System.Diagnostics.Contracts;
- [Serializable]
internal enum LogLevel
{
Trace = 0,
diff --git a/src/mscorlib/src/System/BadImageFormatException.CoreCLR.cs b/src/mscorlib/src/System/BadImageFormatException.CoreCLR.cs
new file mode 100644
index 0000000000..094668bde0
--- /dev/null
+++ b/src/mscorlib/src/System/BadImageFormatException.CoreCLR.cs
@@ -0,0 +1,19 @@
+// 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 partial class BadImageFormatException
+ {
+ // Do not delete: this is invoked from native code.
+ private BadImageFormatException(string fileName, string fusionLog, int hResult)
+ : base(null)
+ {
+ HResult = hResult;
+ _fileName = fileName;
+ _fusionLog = fusionLog;
+ SetMessageField();
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/BadImageFormatException.cs b/src/mscorlib/src/System/BadImageFormatException.cs
deleted file mode 100644
index 42005cccce..0000000000
--- a/src/mscorlib/src/System/BadImageFormatException.cs
+++ /dev/null
@@ -1,162 +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.
-
-/*============================================================
-**
-**
-**
-** Purpose: Exception to an invalid dll or executable format.
-**
-**
-===========================================================*/
-
-namespace System
-{
- using System;
- using System.Runtime.Serialization;
- using FileLoadException = System.IO.FileLoadException;
- using SecurityException = System.Security.SecurityException;
- using System.Globalization;
-
- [Serializable]
- public class BadImageFormatException : SystemException
- {
- private String _fileName; // The name of the corrupt PE file.
- private String _fusionLog; // fusion log (when applicable)
-
- public BadImageFormatException()
- : base(SR.Arg_BadImageFormatException)
- {
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
- }
-
- public BadImageFormatException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
- }
-
- public BadImageFormatException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
- }
-
- public BadImageFormatException(String message, String fileName) : base(message)
- {
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
- _fileName = fileName;
- }
-
- public BadImageFormatException(String message, String fileName, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
- _fileName = fileName;
- }
-
- public override String Message
- {
- get
- {
- SetMessageField();
- return _message;
- }
- }
-
- private void SetMessageField()
- {
- if (_message == null)
- {
- if ((_fileName == null) &&
- (HResult == System.__HResults.COR_E_EXCEPTION))
- _message = SR.Arg_BadImageFormatException;
-
- else
- _message = FileLoadException.FormatFileLoadExceptionMessage(_fileName, HResult);
- }
- }
-
- public String FileName
- {
- get { return _fileName; }
- }
-
- public override String ToString()
- {
- String s = GetType().FullName + ": " + Message;
-
- if (_fileName != null && _fileName.Length != 0)
- s += Environment.NewLine + SR.Format(SR.IO_FileName_Name, _fileName);
-
- if (InnerException != null)
- s = s + " ---> " + InnerException.ToString();
-
- if (StackTrace != null)
- s += Environment.NewLine + StackTrace;
- try
- {
- if (FusionLog != null)
- {
- if (s == null)
- s = " ";
- s += Environment.NewLine;
- s += Environment.NewLine;
- s += FusionLog;
- }
- }
- catch (SecurityException)
- {
- }
- return s;
- }
-
- protected BadImageFormatException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- // Base class constructor will check info != null.
-
- _fileName = info.GetString("BadImageFormat_FileName");
- try
- {
- _fusionLog = info.GetString("BadImageFormat_FusionLog");
- }
- catch
- {
- _fusionLog = null;
- }
- }
-
- private BadImageFormatException(String fileName, String fusionLog, int hResult)
- : base(null)
- {
- HResult = hResult;
- _fileName = fileName;
- _fusionLog = fusionLog;
- SetMessageField();
- }
-
- public String FusionLog
- {
-#pragma warning disable CS0618 // Type or member is obsolete
-#pragma warning restore CS0618 // Type or member is obsolete
- get { return _fusionLog; }
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // Serialize data for our base classes. base will verify info != null.
- base.GetObjectData(info, context);
-
- // Serialize data for this class
- info.AddValue("BadImageFormat_FileName", _fileName, typeof(String));
- try
- {
- info.AddValue("BadImageFormat_FusionLog", FusionLog, typeof(String));
- }
- catch (SecurityException)
- {
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Boolean.cs b/src/mscorlib/src/System/Boolean.cs
index fe25e22920..59cab74456 100644
--- a/src/mscorlib/src/System/Boolean.cs
+++ b/src/mscorlib/src/System/Boolean.cs
@@ -26,10 +26,10 @@ namespace System
//
// Member Variables
//
- private bool m_value;
+ private bool m_value; // Do not rename (binary serialization)
- // The true value.
- //
+ // The true value.
+ //
internal const int True = 1;
// The false value.
diff --git a/src/mscorlib/src/System/Byte.cs b/src/mscorlib/src/System/Byte.cs
index 27fdcd7a64..da3b790ac6 100644
--- a/src/mscorlib/src/System/Byte.cs
+++ b/src/mscorlib/src/System/Byte.cs
@@ -28,7 +28,7 @@ namespace System
public struct Byte : IComparable, IFormattable, IConvertible
, IComparable<Byte>, IEquatable<Byte>
{
- private byte m_value;
+ private byte m_value; // Do not rename (binary serialization)
// The maximum value that a Byte may represent: 255.
public const byte MaxValue = (byte)0xFF;
diff --git a/src/mscorlib/src/System/Collections/ArrayList.cs b/src/mscorlib/src/System/Collections/ArrayList.cs
deleted file mode 100644
index cee7be726a..0000000000
--- a/src/mscorlib/src/System/Collections/ArrayList.cs
+++ /dev/null
@@ -1,626 +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.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Implements a dynamically sized List as an array,
-** and provides many convenience methods for treating
-** an array as an IList.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime;
-using System.Security;
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
-using System.Runtime.Serialization;
-using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
-
-namespace System.Collections
-{
- // Implements a variable-size List that uses an array of objects to store the
- // elements. A ArrayList has a capacity, which is the allocated length
- // of the internal array. As elements are added to a ArrayList, the capacity
- // of the ArrayList is automatically increased as required by reallocating the
- // internal array.
- //
- [FriendAccessAllowed]
- [DebuggerTypeProxy(typeof(System.Collections.ArrayList.ArrayListDebugView))]
- [DebuggerDisplay("Count = {Count}")]
- [Serializable]
- internal class ArrayList : IList, ICloneable
- {
- private Object[] _items;
- [ContractPublicPropertyName("Count")]
- private int _size;
- private int _version;
- [NonSerialized]
- private Object _syncRoot;
-
- private const int _defaultCapacity = 4;
- private static readonly Object[] emptyArray = Array.Empty<Object>();
-
- // Constructs a ArrayList. The list is initially empty and has a capacity
- // of zero. Upon adding the first element to the list the capacity is
- // increased to _defaultCapacity, and then increased in multiples of two as required.
- public ArrayList()
- {
- _items = emptyArray;
- }
-
- // Constructs a ArrayList with a given initial capacity. The list is
- // initially empty, but will have room for the given number of elements
- // before any reallocations are required.
- //
- public ArrayList(int capacity)
- {
- if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(capacity)));
- Contract.EndContractBlock();
-
- if (capacity == 0)
- _items = emptyArray;
- else
- _items = new Object[capacity];
- }
-
- // Constructs a ArrayList, copying the contents of the given collection. The
- // size and capacity of the new list will both be equal to the size of the
- // given collection.
- //
- public ArrayList(ICollection c)
- {
- if (c == null)
- throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection);
- Contract.EndContractBlock();
-
- int count = c.Count;
- if (count == 0)
- {
- _items = emptyArray;
- }
- else
- {
- _items = new Object[count];
- AddRange(c);
- }
- }
-
- // Gets and sets the capacity of this list. The capacity is the size of
- // the internal array used to hold items. When set, the internal
- // array of the list is reallocated to the given capacity.
- //
- public virtual int Capacity
- {
- get
- {
- Contract.Ensures(Contract.Result<int>() >= Count);
- return _items.Length;
- }
- set
- {
- if (value < _size)
- {
- throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
- }
- Contract.Ensures(Capacity >= 0);
- Contract.EndContractBlock();
- // We don't want to update the version number when we change the capacity.
- // Some existing applications have dependency on this.
- if (value != _items.Length)
- {
- if (value > 0)
- {
- Object[] newItems = new Object[value];
- if (_size > 0)
- {
- Array.Copy(_items, 0, newItems, 0, _size);
- }
- _items = newItems;
- }
- else
- {
- _items = new Object[_defaultCapacity];
- }
- }
- }
- }
-
- // Read-only property describing how many elements are in the List.
- public virtual int Count
- {
- get
- {
- Contract.Ensures(Contract.Result<int>() >= 0);
- return _size;
- }
- }
-
- public virtual bool IsFixedSize
- {
- get { return false; }
- }
-
-
- // Is this ArrayList read-only?
- public virtual bool IsReadOnly
- {
- get { return false; }
- }
-
- // Is this ArrayList synchronized (thread-safe)?
- public virtual bool IsSynchronized
- {
- get { return false; }
- }
-
- // Synchronization root for this object.
- public virtual Object SyncRoot
- {
- get
- {
- if (_syncRoot == null)
- {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
- }
- return _syncRoot;
- }
- }
-
- // Sets or Gets the element at the given index.
- //
- public virtual Object this[int index]
- {
- get
- {
- if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
- return _items[index];
- }
- set
- {
- if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
- _items[index] = value;
- _version++;
- }
- }
-
- // Adds the given object to the end of this list. The size of the list is
- // increased by one. If required, the capacity of the list is doubled
- // before adding the new element.
- //
- public virtual int Add(Object value)
- {
- Contract.Ensures(Contract.Result<int>() >= 0);
- if (_size == _items.Length) EnsureCapacity(_size + 1);
- _items[_size] = value;
- _version++;
- return _size++;
- }
-
- // Adds the elements of the given collection to the end of this list. If
- // required, the capacity of the list is increased to twice the previous
- // capacity or the new size, whichever is larger.
- //
- public virtual void AddRange(ICollection c)
- {
- InsertRange(_size, c);
- }
-
-
- // Clears the contents of ArrayList.
- public virtual void Clear()
- {
- if (_size > 0)
- {
- Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
- _size = 0;
- }
- _version++;
- }
-
- // Clones this ArrayList, doing a shallow copy. (A copy is made of all
- // Object references in the ArrayList, but the Objects pointed to
- // are not cloned).
- public virtual Object Clone()
- {
- Contract.Ensures(Contract.Result<Object>() != null);
- ArrayList la = new ArrayList(_size);
- la._size = _size;
- la._version = _version;
- Array.Copy(_items, 0, la._items, 0, _size);
- return la;
- }
-
-
- // Contains returns true if the specified element is in the ArrayList.
- // It does a linear, O(n) search. Equality is determined by calling
- // item.Equals().
- //
- public virtual bool Contains(Object item)
- {
- if (item == null)
- {
- for (int i = 0; i < _size; i++)
- if (_items[i] == null)
- return true;
- return false;
- }
- else
- {
- for (int i = 0; i < _size; i++)
- if ((_items[i] != null) && (_items[i].Equals(item)))
- return true;
- return false;
- }
- }
-
- // Copies this ArrayList into array, which must be of a
- // compatible array type.
- //
- public virtual void CopyTo(Array array, int arrayIndex)
- {
- if ((array != null) && (array.Rank != 1))
- throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
- Contract.EndContractBlock();
- // Delegate rest of error checking to Array.Copy.
- Array.Copy(_items, 0, array, arrayIndex, _size);
- }
-
- // Ensures that the capacity of this list is at least the given minimum
- // value. If the currect capacity of the list is less than min, the
- // capacity is increased to twice the current capacity or to min,
- // whichever is larger.
- private void EnsureCapacity(int min)
- {
- if (_items.Length < min)
- {
- int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;
- // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
- // Note that this check works even when _items.Length overflowed thanks to the (uint) cast
- if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
- if (newCapacity < min) newCapacity = min;
- Capacity = newCapacity;
- }
- }
-
- // Returns an enumerator for this list with the given
- // permission for removal of elements. If modifications made to the list
- // while an enumeration is in progress, the MoveNext and
- // GetObject methods of the enumerator will throw an exception.
- //
- public virtual IEnumerator GetEnumerator()
- {
- Contract.Ensures(Contract.Result<IEnumerator>() != null);
- return new ArrayListEnumeratorSimple(this);
- }
-
- // Returns the index of the first occurrence of a given value in a range of
- // this list. The list is searched forwards from beginning to end.
- // The elements of the list are compared to the given value using the
- // Object.Equals method.
- //
- // This method uses the Array.IndexOf method to perform the
- // search.
- //
- public virtual int IndexOf(Object value)
- {
- Contract.Ensures(Contract.Result<int>() < Count);
- return Array.IndexOf((Array)_items, value, 0, _size);
- }
-
- // Inserts an element into this list at a given index. The size of the list
- // is increased by one. If required, the capacity of the list is doubled
- // before inserting the new element.
- //
- public virtual void Insert(int index, Object value)
- {
- // Note that insertions at the end are legal.
- if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_ArrayListInsert);
- //Contract.Ensures(Count == Contract.OldValue(Count) + 1);
- Contract.EndContractBlock();
-
- if (_size == _items.Length) EnsureCapacity(_size + 1);
- if (index < _size)
- {
- Array.Copy(_items, index, _items, index + 1, _size - index);
- }
- _items[index] = value;
- _size++;
- _version++;
- }
-
- // Inserts the elements of the given collection at a given index. If
- // required, the capacity of the list is increased to twice the previous
- // capacity or the new size, whichever is larger. Ranges may be added
- // to the end of the list by setting index to the ArrayList's size.
- //
- public virtual void InsertRange(int index, ICollection c)
- {
- if (c == null)
- throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection);
- if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
- //Contract.Ensures(Count == Contract.OldValue(Count) + c.Count);
- Contract.EndContractBlock();
-
- int count = c.Count;
- if (count > 0)
- {
- EnsureCapacity(_size + count);
- // shift existing items
- if (index < _size)
- {
- Array.Copy(_items, index, _items, index + count, _size - index);
- }
-
- Object[] itemsToInsert = new Object[count];
- c.CopyTo(itemsToInsert, 0);
- itemsToInsert.CopyTo(_items, index);
- _size += count;
- _version++;
- }
- }
-
- // Returns a read-only IList wrapper for the given IList.
- //
- [FriendAccessAllowed]
- public static IList ReadOnly(IList list)
- {
- if (list == null)
- throw new ArgumentNullException(nameof(list));
- Contract.Ensures(Contract.Result<IList>() != null);
- Contract.EndContractBlock();
- return new ReadOnlyList(list);
- }
-
- // Removes the element at the given index. The size of the list is
- // decreased by one.
- //
- public virtual void Remove(Object obj)
- {
- Contract.Ensures(Count >= 0);
-
- int index = IndexOf(obj);
- BCLDebug.Correctness(index >= 0 || !(obj is Int32), "You passed an Int32 to Remove that wasn't in the ArrayList." + Environment.NewLine + "Did you mean RemoveAt? int: " + obj + " Count: " + Count);
- if (index >= 0)
- RemoveAt(index);
- }
-
- // Removes the element at the given index. The size of the list is
- // decreased by one.
- //
- public virtual void RemoveAt(int index)
- {
- if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
- Contract.Ensures(Count >= 0);
- //Contract.Ensures(Count == Contract.OldValue(Count) - 1);
- Contract.EndContractBlock();
-
- _size--;
- if (index < _size)
- {
- Array.Copy(_items, index + 1, _items, index, _size - index);
- }
- _items[_size] = null;
- _version++;
- }
-
- // ToArray returns a new array of a particular type containing the contents
- // of the ArrayList. This requires copying the ArrayList and potentially
- // downcasting all elements. This copy may fail and is an O(n) operation.
- // Internally, this implementation calls Array.Copy.
- //
- public virtual Array ToArray(Type type)
- {
- if (type == null)
- throw new ArgumentNullException(nameof(type));
- Contract.Ensures(Contract.Result<Array>() != null);
- Contract.EndContractBlock();
- Array array = Array.UnsafeCreateInstance(type, _size);
- Array.Copy(_items, 0, array, 0, _size);
- return array;
- }
-
- [Serializable]
- private class ReadOnlyList : IList
- {
- private IList _list;
-
- internal ReadOnlyList(IList l)
- {
- _list = l;
- }
-
- public virtual int Count
- {
- get { return _list.Count; }
- }
-
- public virtual bool IsReadOnly
- {
- get { return true; }
- }
-
- public virtual bool IsFixedSize
- {
- get { return true; }
- }
-
- public virtual bool IsSynchronized
- {
- get { return _list.IsSynchronized; }
- }
-
- public virtual Object this[int index]
- {
- get
- {
- return _list[index];
- }
- set
- {
- throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
- }
- }
-
- public virtual Object SyncRoot
- {
- get { return _list.SyncRoot; }
- }
-
- public virtual int Add(Object obj)
- {
- throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
- }
-
- public virtual void Clear()
- {
- throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
- }
-
- public virtual bool Contains(Object obj)
- {
- return _list.Contains(obj);
- }
-
- public virtual void CopyTo(Array array, int index)
- {
- _list.CopyTo(array, index);
- }
-
- public virtual IEnumerator GetEnumerator()
- {
- return _list.GetEnumerator();
- }
-
- public virtual int IndexOf(Object value)
- {
- return _list.IndexOf(value);
- }
-
- public virtual void Insert(int index, Object obj)
- {
- throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
- }
-
- public virtual void Remove(Object value)
- {
- throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
- }
-
- public virtual void RemoveAt(int index)
- {
- throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
- }
- }
-
- [Serializable]
- private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable
- {
- private ArrayList list;
- private int index;
- private int version;
- private Object currentElement;
- [NonSerialized]
- private bool isArrayList;
- // this object is used to indicate enumeration has not started or has terminated
- private static Object dummyObject = new Object();
-
- internal ArrayListEnumeratorSimple(ArrayList list)
- {
- this.list = list;
- index = -1;
- version = list._version;
- isArrayList = (list.GetType() == typeof(ArrayList));
- currentElement = dummyObject;
- }
-
- public Object Clone()
- {
- return MemberwiseClone();
- }
-
- public bool MoveNext()
- {
- if (version != list._version)
- {
- throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- }
-
- if (isArrayList)
- { // avoid calling virtual methods if we are operating on ArrayList to improve performance
- if (index < list._size - 1)
- {
- currentElement = list._items[++index];
- return true;
- }
- else
- {
- currentElement = dummyObject;
- index = list._size;
- return false;
- }
- }
- else
- {
- if (index < list.Count - 1)
- {
- currentElement = list[++index];
- return true;
- }
- else
- {
- index = list.Count;
- currentElement = dummyObject;
- return false;
- }
- }
- }
-
- public Object Current
- {
- get
- {
- object temp = currentElement;
- if (dummyObject == temp)
- { // check if enumeration has not started or has terminated
- if (index == -1)
- {
- throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- }
- else
- {
- throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumEnded));
- }
- }
-
- return temp;
- }
- }
-
- public void Reset()
- {
- if (version != list._version)
- {
- throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- }
-
- currentElement = dummyObject;
- index = -1;
- }
- }
-
- internal class ArrayListDebugView
- {
- private ArrayList arrayList;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Comparer.cs b/src/mscorlib/src/System/Collections/Comparer.cs
index 7f4f9f0a07..76e19e77f1 100644
--- a/src/mscorlib/src/System/Collections/Comparer.cs
+++ b/src/mscorlib/src/System/Collections/Comparer.cs
@@ -20,7 +20,6 @@ using System.Diagnostics.Contracts;
namespace System.Collections
{
- [Serializable]
internal sealed class Comparer : IComparer, ISerializable
{
private CompareInfo m_compareInfo;
@@ -44,21 +43,6 @@ namespace System.Collections
m_compareInfo = culture.CompareInfo;
}
- private Comparer(SerializationInfo info, StreamingContext context)
- {
- m_compareInfo = null;
- SerializationInfoEnumerator enumerator = info.GetEnumerator();
- while (enumerator.MoveNext())
- {
- switch (enumerator.Name)
- {
- case CompareInfoName:
- m_compareInfo = (CompareInfo)info.GetValue(CompareInfoName, typeof(CompareInfo));
- break;
- }
- }
- }
-
// Compares two Objects by calling CompareTo. If a ==
// b,0 is returned. If a implements
// IComparable, a.CompareTo(b) is returned. If a
@@ -92,16 +76,7 @@ namespace System.Collections
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
-
- if (m_compareInfo != null)
- {
- info.AddValue(CompareInfoName, m_compareInfo);
- }
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/Collections/CompatibleComparer.cs b/src/mscorlib/src/System/Collections/CompatibleComparer.cs
index 1c90707184..7dcaa4e103 100644
--- a/src/mscorlib/src/System/Collections/CompatibleComparer.cs
+++ b/src/mscorlib/src/System/Collections/CompatibleComparer.cs
@@ -8,7 +8,6 @@ using System.Diagnostics.Contracts;
namespace System.Collections
{
- [Serializable]
internal class CompatibleComparer : IEqualityComparer
{
private IComparer _comparer;
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
index c6211dadd3..3540cca8cf 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
@@ -20,7 +20,6 @@ namespace System.Collections.Concurrent
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
- [Serializable]
internal class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
// This implementation provides an unbounded, multi-producer multi-consumer queue
diff --git a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
index 63e0d47c75..9841bdb4bb 100644
--- a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
+++ b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
@@ -18,7 +18,6 @@ using System.Diagnostics.Contracts;
namespace System.Collections
{
/// This is a simple implementation of IDictionary that is empty and readonly.
- [Serializable]
internal sealed class EmptyReadOnlyDictionaryInternal : IDictionary
{
// Note that this class must be agile with respect to AppDomains. See its usage in
diff --git a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
index e313cda0fb..e4a4acf74e 100644
--- a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
+++ b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
@@ -368,7 +368,6 @@ namespace System.Collections.Generic
}
}
- [Serializable()]
internal class GenericArraySortHelper<T>
: IArraySortHelper<T>
where T : IComparable<T>
diff --git a/src/mscorlib/src/System/Collections/Generic/Comparer.cs b/src/mscorlib/src/System/Collections/Generic/Comparer.cs
index a9b4b3f0dd..e163faa80f 100644
--- a/src/mscorlib/src/System/Collections/Generic/Comparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Comparer.cs
@@ -51,7 +51,6 @@ namespace System.Collections.Generic
// reasons. Adding another base class (even one with no fields)
// means another generic instantiation, which can be costly esp.
// for value types.
-
[Serializable]
internal sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T>
{
@@ -112,7 +111,6 @@ namespace System.Collections.Generic
GetType().GetHashCode();
}
- [Serializable]
internal sealed class ComparisonComparer<T> : Comparer<T>
{
private readonly Comparison<T> _comparison;
@@ -133,7 +131,6 @@ namespace System.Collections.Generic
// and have a SerializationInfo/StreamingContext ctor,
// since we want to serialize as ObjectComparer for
// back-compat reasons (see below).
-
[Serializable]
internal sealed class Int32EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
diff --git a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
index e360eef897..cd33428ca1 100644
--- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
@@ -17,29 +17,6 @@
** thread safety. If a reader writer lock is available, then that may be used
** with a Dictionary to get the same thread safety guarantee.
**
-** Reader writer locks don't exist in silverlight, so we do the following as a
-** result of removing non-generic collections from silverlight:
-** 1. If the Hashtable was fully synchronized, then we replace it with a
-** Dictionary with full locks around reads/writes (same thread safety
-** guarantee).
-** 2. Otherwise, the Hashtable has the default MR/SW thread safety behavior,
-** so we do one of the following on a case-by-case basis:
-** a. If the race condition can be addressed by rearranging the code and using a temp
-** variable (for example, it's only populated immediately after created)
-** then we address the race condition this way and use Dictionary.
-** b. If there's concern about degrading performance with the increased
-** locking, we ifdef with FEATURE_NONGENERIC_COLLECTIONS so we can at
-** least use Hashtable in the desktop build, but Dictionary with full
-** locks in silverlight builds. Note that this is heavier locking than
-** MR/SW, but this is the only option without rewriting (or adding back)
-** the reader writer lock.
-** c. If there's no performance concern (e.g. debug-only code) we
-** consistently replace Hashtable with Dictionary plus full locks to
-** reduce complexity.
-** d. Most of serialization is dead code in silverlight. Instead of updating
-** those Hashtable occurences in serialization, we carved out references
-** to serialization such that this code doesn't need to build in
-** silverlight.
===========================================================*/
namespace System.Collections.Generic
@@ -706,22 +683,6 @@ namespace System.Collections.Generic
value = default(TValue);
return false;
}
-
- // Method similar to TryGetValue that returns the value instead of putting it in an out param.
- public TValue GetValueOrDefault(TKey key) => GetValueOrDefault(key, default(TValue));
-
- // Method similar to TryGetValue that returns the value instead of putting it in an out param. If the entry
- // doesn't exist, returns the defaultValue instead.
- public TValue GetValueOrDefault(TKey key, TValue defaultValue)
- {
- int i = FindEntry(key);
- if (i >= 0)
- {
- return entries[i].value;
- }
- return defaultValue;
- }
-
public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None);
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
@@ -947,7 +908,6 @@ namespace System.Collections.Generic
}
}
- [Serializable]
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>,
IDictionaryEnumerator
{
@@ -1076,7 +1036,6 @@ namespace System.Collections.Generic
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
- [Serializable]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private Dictionary<TKey, TValue> dictionary;
@@ -1227,7 +1186,6 @@ namespace System.Collections.Generic
get { return ((ICollection)dictionary).SyncRoot; }
}
- [Serializable]
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
@@ -1306,7 +1264,6 @@ namespace System.Collections.Generic
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
- [Serializable]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private Dictionary<TKey, TValue> dictionary;
@@ -1455,7 +1412,6 @@ namespace System.Collections.Generic
get { return ((ICollection)dictionary).SyncRoot; }
}
- [Serializable]
public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
diff --git a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
index 0cd1bc1c12..d6b213c9d7 100644
--- a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
@@ -10,6 +10,7 @@ using System.Security;
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
namespace System.Collections.Generic
@@ -352,7 +353,7 @@ namespace System.Collections.Generic
}
[Serializable]
- internal class EnumEqualityComparer<T> : EqualityComparer<T> where T : struct
+ internal class EnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
{
[Pure]
public override bool Equals(T x, T y)
@@ -371,6 +372,9 @@ namespace System.Collections.Generic
public EnumEqualityComparer() { }
+ // This is used by the serialization engine.
+ protected EnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
+
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
@@ -401,6 +405,14 @@ namespace System.Collections.Generic
}
return -1;
}
+
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ // For back-compat we need to serialize the comparers for enums with underlying types other than int as ObjectEqualityComparer
+ if (Type.GetTypeCode(Enum.GetUnderlyingType(typeof(T))) != TypeCode.Int32) {
+ info.SetType(typeof(ObjectEqualityComparer<T>));
+ }
+ }
}
[Serializable]
@@ -408,6 +420,9 @@ namespace System.Collections.Generic
{
public SByteEnumEqualityComparer() { }
+ // This is used by the serialization engine.
+ public SByteEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
+
[Pure]
public override int GetHashCode(T obj)
{
@@ -417,10 +432,13 @@ namespace System.Collections.Generic
}
[Serializable]
- internal sealed class ShortEnumEqualityComparer<T> : EnumEqualityComparer<T> where T : struct
+ internal sealed class ShortEnumEqualityComparer<T> : EnumEqualityComparer<T>, ISerializable where T : struct
{
public ShortEnumEqualityComparer() { }
+ // This is used by the serialization engine.
+ public ShortEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
+
[Pure]
public override int GetHashCode(T obj)
{
@@ -430,7 +448,7 @@ namespace System.Collections.Generic
}
[Serializable]
- internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T> where T : struct
+ internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
{
[Pure]
public override bool Equals(T x, T y)
@@ -479,5 +497,15 @@ namespace System.Collections.Generic
}
return -1;
}
+
+ // This is used by the serialization engine.
+ public LongEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
+
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ // The LongEnumEqualityComparer does not exist on 4.0 so we need to serialize this comparer as ObjectEqualityComparer
+ // to allow for roundtrip between 4.0 and 4.5.
+ info.SetType(typeof(ObjectEqualityComparer<T>));
+ }
}
}
diff --git a/src/mscorlib/src/System/Collections/Generic/List.cs b/src/mscorlib/src/System/Collections/Generic/List.cs
index 4e480885ef..94e794cfd2 100644
--- a/src/mscorlib/src/System/Collections/Generic/List.cs
+++ b/src/mscorlib/src/System/Collections/Generic/List.cs
@@ -1254,7 +1254,6 @@ namespace System.Collections.Generic
}
}
- [Serializable]
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private List<T> list;
diff --git a/src/mscorlib/src/System/Collections/Hashtable.cs b/src/mscorlib/src/System/Collections/Hashtable.cs
index e2fd57ea4d..0c89632828 100644
--- a/src/mscorlib/src/System/Collections/Hashtable.cs
+++ b/src/mscorlib/src/System/Collections/Hashtable.cs
@@ -66,7 +66,6 @@ namespace System.Collections
//
[DebuggerTypeProxy(typeof(System.Collections.Hashtable.HashtableDebugView))]
[DebuggerDisplay("Count = {Count}")]
- [Serializable]
internal class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable
{
/*
@@ -919,58 +918,7 @@ namespace System.Collections
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- // This is imperfect - it only works well if all other writes are
- // also using our synchronized wrapper. But it's still a good idea.
- lock (SyncRoot)
- {
- // This method hasn't been fully tweaked to be safe for a concurrent writer.
- int oldVersion = version;
- info.AddValue(LoadFactorName, loadFactor);
- info.AddValue(VersionName, version);
-
- //
- // We need to maintain serialization compatibility with Everett and RTM.
- // If the comparer is null or a compatible comparer, serialize Hashtable
- // in a format that can be deserialized on Everett and RTM.
- //
-#pragma warning disable 618
- IEqualityComparer keyComparerForSerilization = _keycomparer;
-
- if (keyComparerForSerilization == null)
- {
- info.AddValue(ComparerName, null, typeof(IComparer));
- info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider));
- }
- else if (keyComparerForSerilization is CompatibleComparer)
- {
- CompatibleComparer c = keyComparerForSerilization as CompatibleComparer;
- info.AddValue(ComparerName, c.Comparer, typeof(IComparer));
- info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider));
- }
- else
- {
- info.AddValue(KeyComparerName, keyComparerForSerilization, typeof(IEqualityComparer));
- }
-#pragma warning restore 618
-
- info.AddValue(HashSizeName, buckets.Length); //This is the length of the bucket array.
- Object[] serKeys = new Object[count];
- Object[] serValues = new Object[count];
- CopyKeys(serKeys, 0);
- CopyValues(serValues, 0);
- info.AddValue(KeysName, serKeys, typeof(Object[]));
- info.AddValue(ValuesName, serValues, typeof(Object[]));
-
- // Explicitly check to see if anyone changed the Hashtable while we
- // were serializing it. That's a race condition in their code.
- if (version != oldVersion)
- throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- }
+ throw new PlatformNotSupportedException();
}
//
@@ -1073,7 +1021,6 @@ namespace System.Collections
// Implements a Collection for the keys of a hashtable. An instance of this
// class is created by the GetKeys method of a hashtable.
- [Serializable]
private class KeyCollection : ICollection
{
private Hashtable _hashtable;
@@ -1120,7 +1067,6 @@ namespace System.Collections
// Implements a Collection for the values of a hashtable. An instance of
// this class is created by the GetValues method of a hashtable.
- [Serializable]
private class ValueCollection : ICollection
{
private Hashtable _hashtable;
@@ -1166,7 +1112,6 @@ namespace System.Collections
}
// Synchronized wrapper for hashtable
- [Serializable]
private class SyncHashtable : Hashtable, IEnumerable
{
protected Hashtable _table;
@@ -1189,17 +1134,7 @@ namespace System.Collections
==============================================================================*/
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- // Our serialization code hasn't been fully tweaked to be safe
- // for a concurrent writer.
- lock (_table.SyncRoot)
- {
- info.AddValue("ParentTable", _table, typeof(Hashtable));
- }
+ throw new PlatformNotSupportedException();
}
public override int Count
@@ -1339,7 +1274,7 @@ namespace System.Collections
==============================================================================*/
public override void OnDeserialization(Object sender)
{
- return;
+ throw new PlatformNotSupportedException();
}
}
@@ -1347,7 +1282,6 @@ namespace System.Collections
// Implements an enumerator for a hashtable. The enumerator uses the
// internal version number of the hashtabke to ensure that no modifications
// are made to the hashtable while an enumeration is in progress.
- [Serializable]
private class HashtableEnumerator : IDictionaryEnumerator, ICloneable
{
private Hashtable hashtable;
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
index ebf86cdc58..3fd0cf8c6c 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
@@ -19,7 +19,6 @@ using System.Diagnostics.Contracts;
namespace System.Collections.ObjectModel
{
- [Serializable]
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
internal class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
@@ -365,7 +364,6 @@ namespace System.Collections.ObjectModel
}
}
- [Serializable]
private struct DictionaryEnumerator : IDictionaryEnumerator
{
private readonly IDictionary<TKey, TValue> m_dictionary;
@@ -432,7 +430,6 @@ namespace System.Collections.ObjectModel
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
- [Serializable]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private readonly ICollection<TKey> m_collection;
@@ -543,7 +540,6 @@ namespace System.Collections.ObjectModel
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
- [Serializable]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private readonly ICollection<TValue> m_collection;
diff --git a/src/mscorlib/src/System/Currency.cs b/src/mscorlib/src/System/Currency.cs
index 13ec1b0c4e..4b735bbfe3 100644
--- a/src/mscorlib/src/System/Currency.cs
+++ b/src/mscorlib/src/System/Currency.cs
@@ -10,7 +10,6 @@ using System.Runtime.Versioning;
namespace System
{
- [Serializable]
internal struct Currency
{
internal long m_value;
diff --git a/src/mscorlib/src/System/Delegate.cs b/src/mscorlib/src/System/Delegate.cs
index 75ec57a003..8a9763694b 100644
--- a/src/mscorlib/src/System/Delegate.cs
+++ b/src/mscorlib/src/System/Delegate.cs
@@ -15,7 +15,6 @@ namespace System
using System.Diagnostics;
using System.Diagnostics.Contracts;
- [Serializable]
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Delegate : ICloneable, ISerializable
@@ -545,8 +544,9 @@ namespace System
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
- throw new NotSupportedException();
+ throw new PlatformNotSupportedException();
}
+
//
// internal implementation details (FCALLS and utilities)
//
diff --git a/src/mscorlib/src/System/DelegateSerializationHolder.cs b/src/mscorlib/src/System/DelegateSerializationHolder.cs
deleted file mode 100644
index d7ad827673..0000000000
--- a/src/mscorlib/src/System/DelegateSerializationHolder.cs
+++ /dev/null
@@ -1,287 +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.Reflection;
-using System.Runtime.Remoting;
-using System.Runtime.Serialization;
-using System.Globalization;
-using System.Diagnostics.Contracts;
-
-namespace System
-{
- [Serializable]
- internal sealed class DelegateSerializationHolder : IObjectReference, ISerializable
- {
- #region Static Members
- internal static DelegateEntry GetDelegateSerializationInfo(
- SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
- {
- // Used for MulticastDelegate
-
- if (method == null)
- throw new ArgumentNullException(nameof(method));
- Contract.EndContractBlock();
-
- Type c = delegateType.BaseType;
-
- if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
- throw new ArgumentException(SR.Arg_MustBeDelegate, "type");
-
- if (method.DeclaringType == null)
- throw new NotSupportedException(SR.NotSupported_GlobalMethodSerialization);
-
- DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target,
- method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);
-
- if (info.MemberCount == 0)
- {
- info.SetType(typeof(DelegateSerializationHolder));
- info.AddValue("Delegate", de, typeof(DelegateEntry));
- }
-
- // target can be an object so it needs to be added to the info, or else a fixup is needed
- // when deserializing, and the fixup will occur too late. If it is added directly to the
- // info then the rules of deserialization will guarantee that it will be available when
- // needed
-
- if (target != null)
- {
- String targetName = "target" + targetIndex;
- info.AddValue(targetName, de.target);
- de.target = targetName;
- }
-
- // Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the
- // first parameter and delegates over generic methods) we need to send a deal more information than previously. We can
- // get this by serializing the target MethodInfo. We still need to send the same information as before though (the
- // DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an
- // ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an
- // order of deserialization guarantee otherwise.
- String methodInfoName = "method" + targetIndex;
- info.AddValue(methodInfoName, method);
-
- return de;
- }
- #endregion
-
- #region Definitions
- [Serializable]
- internal class DelegateEntry
- {
- #region Internal Data Members
- internal String type;
- internal String assembly;
- internal Object target;
- internal String targetTypeAssembly;
- internal String targetTypeName;
- internal String methodName;
- internal DelegateEntry delegateEntry;
- #endregion
-
- #region Constructor
- internal DelegateEntry(
- String type, String assembly, Object target, String targetTypeAssembly, String targetTypeName, String methodName)
- {
- this.type = type;
- this.assembly = assembly;
- this.target = target;
- this.targetTypeAssembly = targetTypeAssembly;
- this.targetTypeName = targetTypeName;
- this.methodName = methodName;
- }
- #endregion
-
- #region Internal Members
- internal DelegateEntry Entry
- {
- get { return delegateEntry; }
- set { delegateEntry = value; }
- }
- #endregion
- }
-
- #endregion
-
- #region Private Data Members
- private DelegateEntry m_delegateEntry;
- private MethodInfo[] m_methods;
- #endregion
-
- #region Constructor
- private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- bool bNewWire = true;
-
- try
- {
- m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
- }
- catch
- {
- // Old wire format
- m_delegateEntry = OldDelegateWireFormat(info, context);
- bNewWire = false;
- }
-
- if (bNewWire)
- {
- // retrieve the targets
- DelegateEntry deiter = m_delegateEntry;
- int count = 0;
- while (deiter != null)
- {
- if (deiter.target != null)
- {
- string stringTarget = deiter.target as string; //need test to pass older wire format
- if (stringTarget != null)
- deiter.target = info.GetValue(stringTarget, typeof(Object));
- }
- count++;
- deiter = deiter.delegateEntry;
- }
-
- // If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack
- // them into an ordered array if present.
- MethodInfo[] methods = new MethodInfo[count];
- int i;
- for (i = 0; i < count; i++)
- {
- String methodInfoName = "method" + i;
- methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo));
- if (methods[i] == null)
- break;
- }
-
- // If we got the info then make the array available for deserialization.
- if (i == count)
- m_methods = methods;
- }
- }
- #endregion
-
- #region Private Members
- private void ThrowInsufficientState(string field)
- {
- throw new SerializationException(
- SR.Format(SR.Serialization_InsufficientDeserializationState, field));
- }
-
- private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- String delegateType = info.GetString("DelegateType");
- String delegateAssembly = info.GetString("DelegateAssembly");
- Object target = info.GetValue("Target", typeof(Object));
- String targetTypeAssembly = info.GetString("TargetTypeAssembly");
- String targetTypeName = info.GetString("TargetTypeName");
- String methodName = info.GetString("MethodName");
-
- return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName);
- }
-
- private Delegate GetDelegate(DelegateEntry de, int index)
- {
- Delegate d;
-
- try
- {
- if (de.methodName == null || de.methodName.Length == 0)
- ThrowInsufficientState("MethodName");
-
- if (de.assembly == null || de.assembly.Length == 0)
- ThrowInsufficientState("DelegateAssembly");
-
- if (de.targetTypeName == null || de.targetTypeName.Length == 0)
- ThrowInsufficientState("TargetTypeName");
-
- // We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
- RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type);
-
- // {de.targetTypeAssembly, de.targetTypeName} do not actually refer to the type of the target, but the reflected
- // type of the method. Those types may be the same when the method is on the target's type or on a type in its
- // inheritance chain, but those types may not be the same when the method is an extension method for the
- // target's type or a type in its inheritance chain.
-
- // If we received the new style delegate encoding we already have the target MethodInfo in hand.
- if (m_methods != null)
- {
- // The method info is serialized, so the target type info is redundant. The desktop framework does no
- // additional verification on the target type info.
- d = Delegate.CreateDelegateNoSecurityCheck(type, de.target, m_methods[index]);
- }
- else
- {
- if (de.target != null)
- {
- // For consistency with the desktop framework, when the method info is not serialized for a closed
- // delegate, the method is assumed to be on the target's type or in its inheritance chain. An extension
- // method would not work on this path for the above reason and also because the delegate binds to
- // instance methods only. The desktop framework does no additional verification on the target type info.
- d = Delegate.CreateDelegate(type, de.target, de.methodName);
- }
- else
- {
- RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);
- d = Delegate.CreateDelegate(type, targetType, de.methodName);
- }
- }
- }
- catch (Exception e)
- {
- if (e is SerializationException)
- throw e;
-
- throw new SerializationException(e.Message, e);
- }
-
- return d;
- }
- #endregion
-
- #region IObjectReference
- public Object GetRealObject(StreamingContext context)
- {
- int count = 0;
- for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
- count++;
-
- int maxindex = count - 1;
-
- if (count == 1)
- {
- return GetDelegate(m_delegateEntry, 0);
- }
- else
- {
- object[] invocationList = new object[count];
-
- for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
- {
- // Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to
- // the order we process the entries: we're actually looking at them in reverse order.
- --count;
- invocationList[count] = GetDelegate(de, maxindex - count);
- }
- return ((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length);
- }
- }
- #endregion
-
- #region ISerializable
- public void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- throw new NotSupportedException(SR.NotSupported_DelegateSerHolderSerial);
- }
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/AssertFilter.cs b/src/mscorlib/src/System/Diagnostics/AssertFilter.cs
index 7c861de58e..39ce93ff51 100644
--- a/src/mscorlib/src/System/Diagnostics/AssertFilter.cs
+++ b/src/mscorlib/src/System/Diagnostics/AssertFilter.cs
@@ -15,7 +15,6 @@ namespace System.Diagnostics
//
// The default filter brings up a simple Win32 dialog with 3 buttons.
- [Serializable]
abstract internal class AssertFilter
{
// Called when an assert fails. This should be overridden with logic which
diff --git a/src/mscorlib/src/System/Diagnostics/AssertFilters.cs b/src/mscorlib/src/System/Diagnostics/AssertFilters.cs
index 0f34b41dba..a97e8839ae 100644
--- a/src/mscorlib/src/System/Diagnostics/AssertFilters.cs
+++ b/src/mscorlib/src/System/Diagnostics/AssertFilters.cs
@@ -16,7 +16,6 @@ using System;
namespace System.Diagnostics
{
- [Serializable]
internal enum AssertFilters
{
FailDebug = 0,
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
index 09d1e6baca..d29b860bd1 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
@@ -186,7 +186,6 @@ namespace System.Diagnostics.Contracts
}
}
- [Serializable]
[SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")]
internal sealed class ContractException : Exception
{
@@ -218,21 +217,9 @@ namespace System.Diagnostics.Contracts
_Condition = condition;
}
- private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
- : base(info, context)
- {
- _Kind = (ContractFailureKind)info.GetInt32("Kind");
- _UserMessage = info.GetString("UserMessage");
- _Condition = info.GetString("Condition");
- }
-
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
-
- info.AddValue("Kind", _Kind);
- info.AddValue("UserMessage", _UserMessage);
- info.AddValue("Condition", _Condition);
}
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Debug.Unix.cs b/src/mscorlib/src/System/Diagnostics/Debug.Unix.cs
deleted file mode 100644
index 495f2f713c..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Debug.Unix.cs
+++ /dev/null
@@ -1,95 +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;
-
-namespace System.Diagnostics
-{
- public static partial class Debug
- {
- private static readonly bool s_shouldWriteToStdErr = Environment.GetEnvironmentVariable("COMPlus_DebugWriteToStdErr") == "1";
-
- private static void ShowAssertDialog(string stackTrace, string message, string detailMessage)
- {
- if (Debugger.IsAttached)
- {
- Debugger.Break();
- }
- else
- {
- // In Core, we do not show a dialog.
- // Fail in order to avoid anyone catching an exception and masking
- // an assert failure.
- var ex = new DebugAssertException(message, detailMessage, stackTrace);
- Environment.FailFast(ex.Message, ex);
- }
- }
-
- private static void WriteCore(string message)
- {
- WriteToDebugger(message);
-
- if (s_shouldWriteToStdErr)
- {
- WriteToStderr(message);
- }
- }
-
- private static void WriteToDebugger(string message)
- {
- if (Debugger.IsLogging())
- {
- Debugger.Log(0, null, message);
- }
- else
- {
- Interop.Sys.SysLog(Interop.Sys.SysLogPriority.LOG_USER | Interop.Sys.SysLogPriority.LOG_DEBUG, "%s", message);
- }
- }
-
- private static void WriteToStderr(string message)
- {
- // We don't want to write UTF-16 to a file like standard error. Ideally we would transcode this
- // to UTF8, but the downside of that is it pulls in a bunch of stuff into what is ideally
- // a path with minimal dependencies (as to prevent re-entrency), so we'll take the strategy
- // of just throwing away any non ASCII characters from the message and writing the rest
-
- const int BufferLength = 256;
-
- unsafe
- {
- byte* buf = stackalloc byte[BufferLength];
- int bufCount;
- int i = 0;
-
- while (i < message.Length)
- {
- for (bufCount = 0; bufCount < BufferLength && i < message.Length; i++)
- {
- if (message[i] <= 0x7F)
- {
- buf[bufCount] = (byte)message[i];
- bufCount++;
- }
- }
-
- int totalBytesWritten = 0;
- while (bufCount > 0)
- {
- int bytesWritten = Interop.Sys.Write(2 /* stderr */, buf + totalBytesWritten, bufCount);
- if (bytesWritten < 0)
- {
- // On error, simply stop writing the debug output. This could commonly happen if stderr
- // was piped to a program that ended before this program did, resulting in EPIPE errors.
- return;
- }
-
- bufCount -= bytesWritten;
- totalBytesWritten += bytesWritten;
- }
- }
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Debugger.cs b/src/mscorlib/src/System/Diagnostics/Debugger.cs
index 92df7e7f5f..cda3c4e729 100644
--- a/src/mscorlib/src/System/Diagnostics/Debugger.cs
+++ b/src/mscorlib/src/System/Diagnostics/Debugger.cs
@@ -5,101 +5,63 @@
// The Debugger class is a part of the System.Diagnostics package
// and is used for communicating with a debugger.
-using System;
-using System.IO;
-using System.Collections;
-using System.Reflection;
using System.Runtime.CompilerServices;
-using System.Security;
-using System.Runtime.Versioning;
namespace System.Diagnostics
{
- // No data, does not need to be marked with the serializable attribute
- public sealed class Debugger
+ public static class Debugger
{
- // This should have been a static class, but wasn't as of v3.5. Clearly, this is
- // broken. We'll keep this in V4 for binary compat, but marked obsolete as error
- // so migrated source code gets fixed.
- [Obsolete("Do not create instances of the Debugger class. Call the static methods directly on this type instead", true)]
- public Debugger()
- {
- // Should not have been instantiable - here for binary compatibility in V4.
- }
-
// Break causes a breakpoint to be signalled to an attached debugger. If no debugger
- // is attached, the user is asked if he wants to attach a debugger. If yes, then the
+ // is attached, the user is asked if he wants to attach a debugger. If yes, then the
// debugger is launched.
- [MethodImplAttribute(MethodImplOptions.NoInlining)]
- public static void Break()
- {
- // Causing a break is now allowed.
- BreakInternal();
- }
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ public static void Break() => BreakInternal();
- private static void BreakCanThrow()
- {
- BreakInternal();
- }
+ // The VM depends on this private method.
+ private static void BreakCanThrow() => BreakInternal();
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ [MethodImpl(MethodImplOptions.InternalCall)]
private static extern void BreakInternal();
// Launch launches & attaches a debugger to the process. If a debugger is already attached,
- // nothing happens.
+ // nothing happens.
//
- public static bool Launch()
- {
- if (Debugger.IsAttached)
- return (true);
-
- // Causing the debugger to launch is now allowed.
- return (LaunchInternal());
- }
+ public static bool Launch() => IsAttached ? true : LaunchInternal();
// This class implements code:ICustomDebuggerNotification and provides a type to be used to notify
- // the debugger that execution is about to enter a path that involves a cross-thread dependency.
- // See code:NotifyOfCrossThreadDependency for more details.
- private class CrossThreadDependencyNotification : ICustomDebuggerNotification
- {
- // constructor
- public CrossThreadDependencyNotification()
- {
- }
- }
-
- // Do not inline the slow path
- [MethodImplAttribute(MethodImplOptions.NoInlining)]
- private static void NotifyOfCrossThreadDependencySlow()
- {
- CrossThreadDependencyNotification notification = new CrossThreadDependencyNotification();
- CustomNotification(notification);
- }
-
- // Sends a notification to the debugger to indicate that execution is about to enter a path
- // involving a cross thread dependency. A debugger that has opted into this type of notification
- // can take appropriate action on receipt. For example, performing a funceval normally requires
- // freezing all threads but the one performing the funceval. If the funceval requires execution on
- // more than one thread, as might occur in remoting scenarios, the funceval will block. This
- // notification will apprise the debugger that it will need to slip a thread or abort the funceval
- // in such a situation. The notification is subject to collection after this function returns.
- //
+ // the debugger that execution is about to enter a path that involves a cross-thread dependency.
+ // See code:NotifyOfCrossThreadDependency for more details.
+ private class CrossThreadDependencyNotification : ICustomDebuggerNotification { }
+
+ // Do not inline the slow path
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void NotifyOfCrossThreadDependencySlow() =>
+ CustomNotification(new CrossThreadDependencyNotification());
+
+ // Sends a notification to the debugger to indicate that execution is about to enter a path
+ // involving a cross thread dependency. A debugger that has opted into this type of notification
+ // can take appropriate action on receipt. For example, performing a funceval normally requires
+ // freezing all threads but the one performing the funceval. If the funceval requires execution on
+ // more than one thread, as might occur in remoting scenarios, the funceval will block. This
+ // notification will apprise the debugger that it will need to slip a thread or abort the funceval
+ // in such a situation. The notification is subject to collection after this function returns.
+ //
public static void NotifyOfCrossThreadDependency()
{
- if (Debugger.IsAttached)
+ if (IsAttached)
{
NotifyOfCrossThreadDependencySlow();
}
}
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ [MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool LaunchInternal();
// Returns whether or not a debugger is attached to the process.
//
public static extern bool IsAttached
{
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ [MethodImpl(MethodImplOptions.InternalCall)]
get;
}
@@ -108,26 +70,26 @@ namespace System.Diagnostics
// An attached debugger can enable or disable which messages will
// actually be reported to the user through the COM+ debugger
// services API. This info is communicated to the runtime so only
- // desired events are actually reported to the debugger.
+ // desired events are actually reported to the debugger.
//
// Constant representing the default category
- public static readonly String DefaultCategory = null;
+ public static readonly string DefaultCategory = null;
// Posts a message for the attached debugger. If there is no
// debugger attached, has no effect. The debugger may or may not
- // report the message depending on its settings.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern void Log(int level, String category, String message);
+ // report the message depending on its settings.
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ public static extern void Log(int level, string category, string message);
// Checks to see if an attached debugger has logging enabled
- //
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ //
+ [MethodImpl(MethodImplOptions.InternalCall)]
public static extern bool IsLogging();
// Posts a custom notification for the attached debugger. If there is no
// debugger attached, has no effect. The debugger may or may not
- // report the notification depending on its settings.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ // report the notification depending on its settings.
+ [MethodImpl(MethodImplOptions.InternalCall)]
private static extern void CustomNotification(ICustomDebuggerNotification data);
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
index 5e1dfd82a5..34e65bcb3e 100644
--- a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
+++ b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
@@ -18,21 +18,18 @@ using System.Diagnostics.Contracts;
namespace System.Diagnostics
{
- [Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerStepThroughAttribute : Attribute
{
public DebuggerStepThroughAttribute() { }
}
- [Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerHiddenAttribute : Attribute
{
public DebuggerHiddenAttribute() { }
}
- [Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)]
public sealed class DebuggerNonUserCodeAttribute : Attribute
{
diff --git a/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs b/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs
index 8ad4fec082..6b8c150ab8 100644
--- a/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs
+++ b/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs
@@ -16,7 +16,6 @@ using System;
namespace System.Diagnostics
{
- [Serializable]
internal sealed class EditAndContinueHelper
{
#pragma warning disable 169
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs
new file mode 100644
index 0000000000..2f6fdf62ef
--- /dev/null
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs
@@ -0,0 +1,175 @@
+// 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.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using Microsoft.Win32;
+
+namespace System.Diagnostics.Tracing
+{
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct EventPipeProviderConfiguration
+ {
+ [MarshalAs(UnmanagedType.LPWStr)]
+ private string m_providerName;
+ private UInt64 m_keywords;
+ private uint m_loggingLevel;
+
+ internal EventPipeProviderConfiguration(
+ string providerName,
+ UInt64 keywords,
+ uint loggingLevel)
+ {
+ if(string.IsNullOrEmpty(providerName))
+ {
+ throw new ArgumentNullException(nameof(providerName));
+ }
+ if(loggingLevel > 5) // 5 == Verbose, the highest value in EventPipeLoggingLevel.
+ {
+ throw new ArgumentOutOfRangeException(nameof(loggingLevel));
+ }
+ m_providerName = providerName;
+ m_keywords = keywords;
+ m_loggingLevel = loggingLevel;
+ }
+
+ internal string ProviderName
+ {
+ get { return m_providerName; }
+ }
+
+ internal UInt64 Keywords
+ {
+ get { return m_keywords; }
+ }
+
+ internal uint LoggingLevel
+ {
+ get { return m_loggingLevel; }
+ }
+ }
+
+ internal sealed class EventPipeConfiguration
+ {
+ private string m_outputFile;
+ private uint m_circularBufferSizeInMB;
+ private List<EventPipeProviderConfiguration> m_providers;
+ private TimeSpan m_minTimeBetweenSamples = TimeSpan.FromMilliseconds(1);
+
+ internal EventPipeConfiguration(
+ string outputFile,
+ uint circularBufferSizeInMB)
+ {
+ if(string.IsNullOrEmpty(outputFile))
+ {
+ throw new ArgumentNullException(nameof(outputFile));
+ }
+ if(circularBufferSizeInMB == 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(circularBufferSizeInMB));
+ }
+ m_outputFile = outputFile;
+ m_circularBufferSizeInMB = circularBufferSizeInMB;
+ m_providers = new List<EventPipeProviderConfiguration>();
+ }
+
+ internal string OutputFile
+ {
+ get { return m_outputFile; }
+ }
+
+ internal uint CircularBufferSizeInMB
+ {
+ get { return m_circularBufferSizeInMB; }
+ }
+
+ internal EventPipeProviderConfiguration[] Providers
+ {
+ get { return m_providers.ToArray(); }
+ }
+
+ internal long ProfilerSamplingRateInNanoseconds
+ {
+ // 100 nanoseconds == 1 tick.
+ get { return m_minTimeBetweenSamples.Ticks * 100; }
+ }
+
+ internal void EnableProvider(string providerName, UInt64 keywords, uint loggingLevel)
+ {
+ m_providers.Add(new EventPipeProviderConfiguration(
+ providerName,
+ keywords,
+ loggingLevel));
+ }
+
+ internal void SetProfilerSamplingRate(TimeSpan minTimeBetweenSamples)
+ {
+ if(minTimeBetweenSamples.Ticks <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(minTimeBetweenSamples));
+ }
+
+ m_minTimeBetweenSamples = minTimeBetweenSamples;
+ }
+ }
+
+ internal static class EventPipe
+ {
+ internal static void Enable(EventPipeConfiguration configuration)
+ {
+ if(configuration == null)
+ {
+ throw new ArgumentNullException(nameof(configuration));
+ }
+
+ EventPipeProviderConfiguration[] providers = configuration.Providers;
+
+ EventPipeInternal.Enable(
+ configuration.OutputFile,
+ configuration.CircularBufferSizeInMB,
+ configuration.ProfilerSamplingRateInNanoseconds,
+ providers,
+ providers.Length);
+ }
+
+ internal static void Disable()
+ {
+ EventPipeInternal.Disable();
+ }
+ }
+
+ internal static class EventPipeInternal
+ {
+ //
+ // These PInvokes are used by the configuration APIs to interact with EventPipe.
+ //
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern void Enable(string outputFile, uint circularBufferSizeInMB, long profilerSamplingRateInNanoseconds, EventPipeProviderConfiguration[] providers, int numProviders);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern void Disable();
+
+ //
+ // These PInvokes are used by EventSource to interact with the EventPipe.
+ //
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern IntPtr CreateProvider(Guid providerID, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback callbackFunc);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern unsafe IntPtr DefineEvent(IntPtr provHandle, uint eventID, Int64 keywords, uint eventVersion, uint level, void *pMetadata, uint metadataLength);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern void DeleteProvider(IntPtr provHandle);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern unsafe void WriteEvent(IntPtr eventHandle, uint eventID, void* pData, uint length, Guid* activityId, Guid* relatedActivityId);
+ }
+}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs
new file mode 100644
index 0000000000..d5bc4c2889
--- /dev/null
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs
@@ -0,0 +1,116 @@
+// 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.Concurrent;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using Microsoft.Win32;
+using System.Diagnostics;
+using System.Collections.Generic;
+
+namespace System.Diagnostics.Tracing
+{
+ internal sealed class EventPipeEventProvider : IEventProvider
+ {
+ // The EventPipeProvider handle.
+ private IntPtr m_provHandle = IntPtr.Zero;
+
+ // Register an event provider.
+ unsafe uint IEventProvider.EventRegister(
+ ref Guid providerId,
+ UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback,
+ void* callbackContext,
+ ref long registrationHandle)
+ {
+ uint returnStatus = 0;
+ m_provHandle = EventPipeInternal.CreateProvider(providerId, enableCallback);
+ if(m_provHandle != IntPtr.Zero)
+ {
+ // Fixed registration handle because a new EventPipeEventProvider
+ // will be created for each new EventSource.
+ registrationHandle = 1;
+ }
+ else
+ {
+ // Unable to create the provider.
+ returnStatus = 1;
+ }
+
+ return returnStatus;
+ }
+
+ // Unregister an event provider.
+ uint IEventProvider.EventUnregister(long registrationHandle)
+ {
+ EventPipeInternal.DeleteProvider(m_provHandle);
+ return 0;
+ }
+
+ // Write an event.
+ unsafe int IEventProvider.EventWriteTransferWrapper(
+ long registrationHandle,
+ ref EventDescriptor eventDescriptor,
+ IntPtr eventHandle,
+ Guid* activityId,
+ Guid* relatedActivityId,
+ int userDataCount,
+ EventProvider.EventData* userData)
+ {
+ uint eventID = (uint)eventDescriptor.EventId;
+ if(eventID != 0 && eventHandle != IntPtr.Zero)
+ {
+ if (userDataCount == 0)
+ {
+ EventPipeInternal.WriteEvent(eventHandle, eventID, null, 0, activityId, relatedActivityId);
+ return 0;
+ }
+
+ uint length = 0;
+ for (int i = 0; i < userDataCount; i++)
+ {
+ length += userData[i].Size;
+ }
+
+ byte[] data = new byte[length];
+ fixed (byte *pData = data)
+ {
+ uint offset = 0;
+ for (int i = 0; i < userDataCount; i++)
+ {
+ byte * singleUserDataPtr = (byte *)(userData[i].Ptr);
+ uint singleUserDataSize = userData[i].Size;
+ WriteToBuffer(pData, length, ref offset, singleUserDataPtr, singleUserDataSize);
+ }
+ EventPipeInternal.WriteEvent(eventHandle, eventID, pData, length, activityId, relatedActivityId);
+ }
+ }
+ return 0;
+ }
+
+ // Get or set the per-thread activity ID.
+ int IEventProvider.EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.ActivityControl ControlCode, ref Guid ActivityId)
+ {
+ return 0;
+ }
+
+ // Define an EventPipeEvent handle.
+ unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength)
+ {
+ IntPtr eventHandlePtr = EventPipeInternal.DefineEvent(m_provHandle, eventID, keywords, eventVersion, level, pMetadata, metadataLength);
+ return eventHandlePtr;
+ }
+
+ // Copy src to buffer and modify the offset.
+ // Note: We know the buffer size ahead of time to make sure no buffer overflow.
+ private static unsafe void WriteToBuffer(byte *buffer, uint bufferLength, ref uint offset, byte *src, uint srcLength)
+ {
+ Debug.Assert(bufferLength >= (offset + srcLength));
+ for (int i = 0; i < srcLength; i++)
+ {
+ *(byte *)(buffer + offset + i) = *(byte *)(src + i);
+ }
+ offset += srcLength;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
index b691dd38b9..01aac72cf6 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
@@ -11,6 +11,13 @@ namespace System.Diagnostics.Tracing
{
public partial class EventSource
{
+#if FEATURE_MANAGED_ETW && FEATURE_PERFTRACING
+ // For non-Windows, we use a thread-local variable to hold the activity ID.
+ // On Windows, ETW has it's own thread-local variable and we participate in its use.
+ [ThreadStatic]
+ private static Guid s_currentThreadActivityId;
+#endif // FEATURE_MANAGED_ETW && FEATURE_PERFTRACING
+
// ActivityID support (see also WriteEventWithRelatedActivityIdCore)
/// <summary>
/// When a thread starts work that is on behalf of 'something else' (typically another
@@ -40,9 +47,13 @@ namespace System.Diagnostics.Tracing
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
+#if FEATURE_PERFTRACING
+ s_currentThreadActivityId = activityId;
+#elif PLATFORM_WINDOWS
if (UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref activityId) == 0)
+#endif // FEATURE_PERFTRACING
{
#if FEATURE_ACTIVITYSAMPLING
var activityDying = s_activityDying;
@@ -86,9 +97,14 @@ namespace System.Diagnostics.Tracing
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
+#if FEATURE_PERFTRACING
+ oldActivityThatWillContinue = s_currentThreadActivityId;
+ s_currentThreadActivityId = activityId;
+#elif PLATFORM_WINDOWS
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref oldActivityThatWillContinue);
+#endif // FEATURE_PERFTRACING
#endif // FEATURE_MANAGED_ETW
// We don't call the activityDying callback here because the caller has declared that
@@ -108,9 +124,13 @@ namespace System.Diagnostics.Tracing
// errors. Note we can't access m_throwOnWrites because this is a static method.
Guid retVal = new Guid();
#if FEATURE_MANAGED_ETW
+#if FEATURE_PERFTRACING
+ retVal = s_currentThreadActivityId;
+#elif PLATFORM_WINDOWS
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID,
ref retVal);
+#endif // FEATURE_PERFTRACING
#endif // FEATURE_MANAGED_ETW
return retVal;
}
diff --git a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
index 29d6a1d4e6..d3994d48b8 100644
--- a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
+++ b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
@@ -11,7 +11,6 @@ using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics
{
- [Serializable]
internal class LogSwitch
{
// ! WARNING !
diff --git a/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs b/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs
index 6b5ea85ee1..22d6c95a97 100644
--- a/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs
+++ b/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs
@@ -21,7 +21,6 @@ namespace System.Diagnostics
// Constants representing the importance level of messages to be logged.
// This level can be used to organize messages, and also to filter which
// messages are displayed.
- [Serializable]
internal enum LoggingLevels
{
TraceLevel0 = 0,
diff --git a/src/mscorlib/src/System/Diagnostics/Stackframe.cs b/src/mscorlib/src/System/Diagnostics/Stackframe.cs
index b555a609e7..a6a7067af3 100644
--- a/src/mscorlib/src/System/Diagnostics/Stackframe.cs
+++ b/src/mscorlib/src/System/Diagnostics/Stackframe.cs
@@ -12,7 +12,6 @@ using System.Diagnostics.Contracts;
namespace System.Diagnostics
{
// There is no good reason for the methods of this class to be virtual.
- [Serializable]
public class StackFrame
{
private MethodBase method;
diff --git a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
index cdedb66ed8..6a138de327 100644
--- a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
+++ b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
@@ -22,7 +22,6 @@ namespace System.Diagnostics
// Modifying the order or fields of this object may require other changes
// to the unmanaged definition of the StackFrameHelper class, in
// VM\DebugDebugger.h. The binder will catch some of these layout problems.
- [Serializable]
internal class StackFrameHelper : IDisposable
{
[NonSerialized]
@@ -251,7 +250,6 @@ namespace System.Diagnostics
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
- [Serializable]
public class StackTrace
{
private StackFrame[] frames;
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
index c4c1ede525..15b3c7f4f7 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
@@ -17,7 +17,6 @@ using System;
namespace System.Diagnostics.SymbolStore
{
- [Serializable]
internal enum SymAddressKind
{
// ILOffset: addr1 = IL local var or param index.
diff --git a/src/mscorlib/src/System/Diagnostics/log.cs b/src/mscorlib/src/System/Diagnostics/log.cs
index b62ea493e7..5ed3a3e502 100644
--- a/src/mscorlib/src/System/Diagnostics/log.cs
+++ b/src/mscorlib/src/System/Diagnostics/log.cs
@@ -4,7 +4,6 @@
namespace System.Diagnostics
{
- using System.Runtime.Remoting;
using System;
using System.IO;
using System.Collections;
@@ -20,7 +19,6 @@ namespace System.Diagnostics
// NOTE: These are NOT triggered when the log switch setting is changed from the
// attached debugger.
//
- [Serializable]
internal delegate void LogSwitchLevelHandler(LogSwitch ls, LoggingLevels newLevel);
diff --git a/src/mscorlib/src/System/DllNotFoundException.cs b/src/mscorlib/src/System/DllNotFoundException.cs
deleted file mode 100644
index a3b46c76b3..0000000000
--- a/src/mscorlib/src/System/DllNotFoundException.cs
+++ /dev/null
@@ -1,45 +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.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: The exception class for some failed P/Invoke calls.
-**
-**
-=============================================================================*/
-
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class DllNotFoundException : TypeLoadException
- {
- public DllNotFoundException()
- : base(SR.Arg_DllNotFoundException)
- {
- HResult = __HResults.COR_E_DLLNOTFOUND;
- }
-
- public DllNotFoundException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_DLLNOTFOUND;
- }
-
- public DllNotFoundException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_DLLNOTFOUND;
- }
-
- protected DllNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Double.cs b/src/mscorlib/src/System/Double.cs
index f2c5cec219..30fa1a58b3 100644
--- a/src/mscorlib/src/System/Double.cs
+++ b/src/mscorlib/src/System/Double.cs
@@ -26,7 +26,7 @@ namespace System
public struct Double : IComparable, IFormattable, IConvertible
, IComparable<Double>, IEquatable<Double>
{
- internal double m_value;
+ private double m_value; // Do not rename (binary serialization)
//
// Public Constants
diff --git a/src/mscorlib/src/System/Empty.cs b/src/mscorlib/src/System/Empty.cs
index 502e8dfea7..2b585b3141 100644
--- a/src/mscorlib/src/System/Empty.cs
+++ b/src/mscorlib/src/System/Empty.cs
@@ -9,12 +9,10 @@
using System.Diagnostics.Contracts;
using System;
-using System.Runtime.Remoting;
using System.Runtime.Serialization;
namespace System
{
- [Serializable]
internal sealed class Empty : ISerializable
{
private Empty()
@@ -30,12 +28,7 @@ namespace System
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.EmptyUnity, null, null);
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/Environment.cs b/src/mscorlib/src/System/Environment.cs
index dddbdc242d..257deb27eb 100644
--- a/src/mscorlib/src/System/Environment.cs
+++ b/src/mscorlib/src/System/Environment.cs
@@ -77,9 +77,6 @@ namespace System
}
}
-
- private static volatile OperatingSystem m_os; // Cached OperatingSystem value
-
/*==================================TickCount===================================
**Action: Gets the number of ticks since the system was started.
**Returns: The number of ticks since the system was started.
diff --git a/src/mscorlib/src/System/Exception.cs b/src/mscorlib/src/System/Exception.cs
index 263b6b3c65..8d01b4c461 100644
--- a/src/mscorlib/src/System/Exception.cs
+++ b/src/mscorlib/src/System/Exception.cs
@@ -83,8 +83,7 @@ namespace System
_stackTraceString = info.GetString("StackTraceString");
_remoteStackTraceString = info.GetString("RemoteStackTraceString");
_remoteStackIndex = info.GetInt32("RemoteStackIndex");
-
- _exceptionMethodString = (String)(info.GetValue("ExceptionMethod", typeof(String)));
+
HResult = info.GetInt32("HResult");
_source = info.GetString("Source");
@@ -293,15 +292,8 @@ namespace System
{
return null;
}
-
- if (_exceptionMethodString != null)
- {
- _exceptionMethod = GetExceptionMethodFromString();
- }
- else
- {
- _exceptionMethod = GetExceptionMethodFromStackTrace();
- }
+
+ _exceptionMethod = GetExceptionMethodFromStackTrace();
return _exceptionMethod;
}
@@ -434,90 +426,6 @@ namespace System
return s;
}
- private String GetExceptionMethodString()
- {
- MethodBase methBase = GetTargetSiteInternal();
- if (methBase == null)
- {
- return null;
- }
- if (methBase is System.Reflection.Emit.DynamicMethod.RTDynamicMethod)
- {
- // DynamicMethods cannot be serialized
- return null;
- }
-
- // Note that the newline separator is only a separator, chosen such that
- // it won't (generally) occur in a method name. This string is used
- // only for serialization of the Exception Method.
- char separator = '\n';
- StringBuilder result = new StringBuilder();
- if (methBase is ConstructorInfo)
- {
- RuntimeConstructorInfo rci = (RuntimeConstructorInfo)methBase;
- Type t = rci.ReflectedType;
- result.Append((int)MemberTypes.Constructor);
- result.Append(separator);
- result.Append(rci.Name);
- if (t != null)
- {
- result.Append(separator);
- result.Append(t.Assembly.FullName);
- result.Append(separator);
- result.Append(t.FullName);
- }
- result.Append(separator);
- result.Append(rci.ToString());
- }
- else
- {
- Debug.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
- RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase;
- Type t = rmi.DeclaringType;
- result.Append((int)MemberTypes.Method);
- result.Append(separator);
- result.Append(rmi.Name);
- result.Append(separator);
- result.Append(rmi.Module.Assembly.FullName);
- result.Append(separator);
- if (t != null)
- {
- result.Append(t.FullName);
- result.Append(separator);
- }
- result.Append(rmi.ToString());
- }
-
- return result.ToString();
- }
-
- private MethodBase GetExceptionMethodFromString()
- {
- Debug.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
- String[] args = _exceptionMethodString.Split(new char[] { '\0', '\n' });
- if (args.Length != 5)
- {
- throw new SerializationException();
- }
- SerializationInfo si = new SerializationInfo(typeof(MemberInfoSerializationHolder), new FormatterConverter());
- si.AddValue("MemberType", (int)Int32.Parse(args[0], CultureInfo.InvariantCulture), typeof(Int32));
- si.AddValue("Name", args[1], typeof(String));
- si.AddValue("AssemblyName", args[2], typeof(String));
- si.AddValue("ClassName", args[3]);
- si.AddValue("Signature", args[4]);
- MethodBase result;
- StreamingContext sc = new StreamingContext(StreamingContextStates.All);
- try
- {
- result = (MethodBase)new MemberInfoSerializationHolder(si, sc).GetRealObject(sc);
- }
- catch (SerializationException)
- {
- result = null;
- }
- return result;
- }
-
protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
{
add { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); }
@@ -559,7 +467,7 @@ namespace System
info.AddValue("StackTraceString", tempStackTraceString, typeof(String));
info.AddValue("RemoteStackTraceString", _remoteStackTraceString, typeof(String));
info.AddValue("RemoteStackIndex", _remoteStackIndex, typeof(Int32));
- info.AddValue("ExceptionMethod", GetExceptionMethodString(), typeof(String));
+ info.AddValue("ExceptionMethod", null, typeof(String));
info.AddValue("HResult", HResult);
info.AddValue("Source", _source, typeof(String));
@@ -748,7 +656,7 @@ namespace System
private String _className; //Needed for serialization.
private MethodBase _exceptionMethod; //Needed for serialization.
- private String _exceptionMethodString; //Needed for serialization.
+ private String _exceptionMethodString; //Needed for serialization.
internal String _message;
private IDictionary _data;
private Exception _innerException;
diff --git a/src/mscorlib/src/System/GC.cs b/src/mscorlib/src/System/GC.cs
index aeb0ca5196..11ae8bf32e 100644
--- a/src/mscorlib/src/System/GC.cs
+++ b/src/mscorlib/src/System/GC.cs
@@ -28,7 +28,6 @@ using System.Diagnostics.Contracts;
namespace System
{
- [Serializable]
public enum GCCollectionMode
{
Default = 0,
@@ -39,7 +38,6 @@ namespace System
// !!!!!!!!!!!!!!!!!!!!!!!
// make sure you change the def in vm\gc.h
// if you change this!
- [Serializable]
internal enum InternalGCCollectionMode
{
NonBlocking = 0x00000001,
@@ -51,7 +49,6 @@ namespace System
// !!!!!!!!!!!!!!!!!!!!!!!
// make sure you change the def in vm\gc.h
// if you change this!
- [Serializable]
public enum GCNotificationStatus
{
Succeeded = 0,
diff --git a/src/mscorlib/src/System/Globalization/BidiCategory.cs b/src/mscorlib/src/System/Globalization/BidiCategory.cs
index f37c44b385..9d767c673b 100644
--- a/src/mscorlib/src/System/Globalization/BidiCategory.cs
+++ b/src/mscorlib/src/System/Globalization/BidiCategory.cs
@@ -12,7 +12,6 @@
namespace System.Globalization
{
- [Serializable]
internal enum BidiCategory
{
LeftToRight = 0,
diff --git a/src/mscorlib/src/System/Globalization/Calendar.cs b/src/mscorlib/src/System/Globalization/Calendar.cs
index c23e1088c1..86782c1f3b 100644
--- a/src/mscorlib/src/System/Globalization/Calendar.cs
+++ b/src/mscorlib/src/System/Globalization/Calendar.cs
@@ -28,7 +28,6 @@ namespace System.Globalization
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
- [Serializable]
public abstract partial class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
diff --git a/src/mscorlib/src/System/Globalization/CalendarData.Unix.cs b/src/mscorlib/src/System/Globalization/CalendarData.Unix.cs
deleted file mode 100644
index 319f66ae8c..0000000000
--- a/src/mscorlib/src/System/Globalization/CalendarData.Unix.cs
+++ /dev/null
@@ -1,339 +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.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
-using System.Security;
-using System.Text;
-
-namespace System.Globalization
-{
- // needs to be kept in sync with CalendarDataType in System.Globalization.Native
- internal enum CalendarDataType
- {
- Uninitialized = 0,
- NativeName = 1,
- MonthDay = 2,
- ShortDates = 3,
- LongDates = 4,
- YearMonths = 5,
- DayNames = 6,
- AbbrevDayNames = 7,
- MonthNames = 8,
- AbbrevMonthNames = 9,
- SuperShortDayNames = 10,
- MonthGenitiveNames = 11,
- AbbrevMonthGenitiveNames = 12,
- EraNames = 13,
- AbbrevEraNames = 14,
- }
-
- internal partial class CalendarData
- {
- private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId)
- {
- bool result = true;
- result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName);
- result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay);
- this.sMonthDay = NormalizeDatePattern(this.sMonthDay);
-
- result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates);
- result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates);
- result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths);
- result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames);
- result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames);
- result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames);
- result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames);
- result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames);
- result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames);
- result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames);
- result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames);
- result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames);
-
- return result;
- }
-
- internal static int GetTwoDigitYearMax(CalendarId calendarId)
- {
- // There is no user override for this value on Linux or in ICU.
- // So just return -1 to use the hard-coded defaults.
- return -1;
- }
-
- // Call native side to figure out which calendars are allowed
- internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- // NOTE: there are no 'user overrides' on Linux
- int count = Interop.GlobalizationInterop.GetCalendars(localeName, calendars, calendars.Length);
-
- // ensure there is at least 1 calendar returned
- if (count == 0 && calendars.Length > 0)
- {
- calendars[0] = CalendarId.GREGORIAN;
- count = 1;
- }
-
- return count;
- }
-
- private static bool SystemSupportsTaiwaneseCalendar()
- {
- return true;
- }
-
- // PAL Layer ends here
-
- private static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- return Interop.CallStringMethod(
- (locale, calId, type, stringBuilder) =>
- Interop.GlobalizationInterop.GetCalendarInfo(
- locale,
- calId,
- type,
- stringBuilder,
- stringBuilder.Capacity),
- localeName,
- calendarId,
- dataType,
- out calendarString);
- }
-
- private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] datePatterns)
- {
- datePatterns = null;
-
- CallbackContext callbackContext = new CallbackContext();
- callbackContext.DisallowDuplicates = true;
- bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
- if (result)
- {
- List<string> datePatternsList = callbackContext.Results;
-
- datePatterns = new string[datePatternsList.Count];
- for (int i = 0; i < datePatternsList.Count; i++)
- {
- datePatterns[i] = NormalizeDatePattern(datePatternsList[i]);
- }
- }
-
- return result;
- }
-
- /// <summary>
- /// The ICU date format characters are not exactly the same as the .NET date format characters.
- /// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern.
- /// </summary>
- /// <remarks>
- /// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime
- /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
- /// </remarks>
- private static string NormalizeDatePattern(string input)
- {
- StringBuilder destination = StringBuilderCache.Acquire(input.Length);
-
- int index = 0;
- while (index < input.Length)
- {
- switch (input[index])
- {
- case '\'':
- // single quotes escape characters, like 'de' in es-SP
- // so read verbatim until the next single quote
- destination.Append(input[index++]);
- while (index < input.Length)
- {
- char current = input[index++];
- destination.Append(current);
- if (current == '\'')
- {
- break;
- }
- }
- break;
- case 'E':
- case 'e':
- case 'c':
- // 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET
- // 'e' in ICU is the local day of the week, which has no representation in .NET, but
- // maps closest to 3 or 4 'd's in .NET
- // 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but
- // maps closest to 3 or 4 'd's in .NET
- NormalizeDayOfWeek(input, destination, ref index);
- break;
- case 'L':
- case 'M':
- // 'L' in ICU is the stand-alone name of the month,
- // which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns
- // 'M' in both ICU and .NET is the month,
- // but ICU supports 5 'M's, which is the super short month name
- int occurrences = CountOccurrences(input, input[index], ref index);
- if (occurrences > 4)
- {
- // 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET
- occurrences = 3;
- }
- destination.Append('M', occurrences);
- break;
- case 'G':
- // 'G' in ICU is the era, which maps to 'g' in .NET
- occurrences = CountOccurrences(input, 'G', ref index);
-
- // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they
- // have the same meaning
- destination.Append('g');
- break;
- case 'y':
- // a single 'y' in ICU is the year with no padding or trimming.
- // a single 'y' in .NET is the year with 1 or 2 digits
- // so convert any single 'y' to 'yyyy'
- occurrences = CountOccurrences(input, 'y', ref index);
- if (occurrences == 1)
- {
- occurrences = 4;
- }
- destination.Append('y', occurrences);
- break;
- default:
- const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
- Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
- string.Format(CultureInfo.InvariantCulture,
- "Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.",
- input[index]));
-
- destination.Append(input[index++]);
- break;
- }
- }
-
- return StringBuilderCache.GetStringAndRelease(destination);
- }
-
- private static void NormalizeDayOfWeek(string input, StringBuilder destination, ref int index)
- {
- char dayChar = input[index];
- int occurrences = CountOccurrences(input, dayChar, ref index);
- occurrences = Math.Max(occurrences, 3);
- if (occurrences > 4)
- {
- // 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET
- occurrences = 3;
- }
-
- destination.Append('d', occurrences);
- }
-
- private static int CountOccurrences(string input, char value, ref int index)
- {
- int startIndex = index;
- while (index < input.Length && input[index] == value)
- {
- index++;
- }
-
- return index - startIndex;
- }
-
- private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] monthNames)
- {
- monthNames = null;
-
- CallbackContext callbackContext = new CallbackContext();
- bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
- if (result)
- {
- // the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an
- // extra empty string to fill the array.
- if (callbackContext.Results.Count == 12)
- {
- callbackContext.Results.Add(string.Empty);
- }
-
- monthNames = callbackContext.Results.ToArray();
- }
-
- return result;
- }
-
- private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] eraNames)
- {
- bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames);
-
- // .NET expects that only the Japanese calendars have more than 1 era.
- // So for other calendars, only return the latest era.
- if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames.Length > 0)
- {
- string[] latestEraName = new string[] { eraNames[eraNames.Length - 1] };
- eraNames = latestEraName;
- }
-
- return result;
- }
-
- internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] calendarData)
- {
- calendarData = null;
-
- CallbackContext callbackContext = new CallbackContext();
- bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
- if (result)
- {
- calendarData = callbackContext.Results.ToArray();
- }
-
- return result;
- }
-
- private static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, CallbackContext callbackContext)
- {
- GCHandle context = GCHandle.Alloc(callbackContext);
- try
- {
- return Interop.GlobalizationInterop.EnumCalendarInfo(EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)context);
- }
- finally
- {
- context.Free();
- }
- }
-
- private static void EnumCalendarInfoCallback(string calendarString, IntPtr context)
- {
- CallbackContext callbackContext = (CallbackContext)((GCHandle)context).Target;
-
- if (callbackContext.DisallowDuplicates)
- {
- foreach (string existingResult in callbackContext.Results)
- {
- if (string.Equals(calendarString, existingResult, StringComparison.Ordinal))
- {
- // the value is already in the results, so don't add it again
- return;
- }
- }
- }
-
- callbackContext.Results.Add(calendarString);
- }
-
- private class CallbackContext
- {
- private List<string> _results = new List<string>();
-
- public CallbackContext()
- {
- }
-
- public List<string> Results { get { return _results; } }
-
- public bool DisallowDuplicates { get; set; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs b/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs
index 51a2727c7d..89de24d9d7 100644
--- a/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs
+++ b/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs
@@ -157,20 +157,9 @@ namespace System.Globalization
}
}
- GCHandle contextHandle = GCHandle.Alloc(data);
- try
- {
- // Now call the enumeration API. Work is done by our callback function
-#if CORECLR
- Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, (IntPtr)contextHandle);
-#else
- IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarsCallback);
- Interop.Kernel32.EnumCalendarInfoExEx(callback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, (IntPtr)contextHandle);
-#endif
- }
- finally
+ unsafe
{
- contextHandle.Free();
+ Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, Unsafe.AsPointer(ref data));
}
// Copy to the output array
@@ -300,15 +289,13 @@ namespace System.Globalization
}
// EnumCalendarInfoExEx callback itself.
-#if !CORECLR
- [NativeCallable(CallingConvention = CallingConvention.StdCall)]
-#endif
- private static unsafe Interop.BOOL EnumCalendarInfoCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr pReserved, IntPtr lParam)
+ // [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+ private static unsafe Interop.BOOL EnumCalendarInfoCallback(char* lpCalendarInfoString, uint calendar, IntPtr pReserved, void* lParam)
{
- EnumData context = (EnumData)((GCHandle)lParam).Target;
+ ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam);
try
{
- string calendarInfo = new string((char*)lpCalendarInfoString);
+ string calendarInfo = new string(lpCalendarInfoString);
// If we had a user override, check to make sure this differs
if (context.userOverride != calendarInfo)
@@ -343,7 +330,7 @@ namespace System.Globalization
string res = CultureData.GetLocaleInfoEx(localeName, lcType);
// if it succeeded remember the override for the later callers
- if (res != "")
+ if (res != null)
{
// Remember this was the override (so we can look for duplicates later in the enum function)
context.userOverride = res;
@@ -354,20 +341,10 @@ namespace System.Globalization
}
}
- GCHandle contextHandle = GCHandle.Alloc(context);
- try
+ unsafe
{
-#if CORECLR
- Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, (IntPtr)contextHandle);
-#else
// Now call the enumeration API. Work is done by our callback function
- IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarInfoCallback);
- Interop.Kernel32.EnumCalendarInfoExEx(callback, localeName, (uint)calendar, null, calType, (IntPtr)contextHandle);
-#endif // CORECLR
- }
- finally
- {
- contextHandle.Free();
+ Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, Unsafe.AsPointer(ref context));
}
// Now we have a list of data, fail if we didn't find anything.
@@ -464,12 +441,10 @@ namespace System.Globalization
public IntList calendars; // list of calendars found so far
}
-#if !CORECLR
- [NativeCallable(CallingConvention = CallingConvention.StdCall)]
-#endif
- private static Interop.BOOL EnumCalendarsCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr reserved, IntPtr lParam)
+ // [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+ private static unsafe Interop.BOOL EnumCalendarsCallback(char* lpCalendarInfoString, uint calendar, IntPtr reserved, void* lParam)
{
- EnumCalendarsData context = (EnumCalendarsData)((GCHandle)lParam).Target;
+ ref EnumCalendarsData context = ref Unsafe.As<byte, EnumCalendarsData>(ref *(byte*)lParam);
try
{
// If we had a user override, check to make sure this differs
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs
index d20bb9f9f3..eb4dc5613e 100644
--- a/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs
@@ -16,7 +16,7 @@ namespace System.Globalization
{
_sortName = culture.SortName;
- _name = culture._name;
+ m_name = culture._name;
_sortName = culture.SortName;
if (_invariantMode)
@@ -199,7 +199,7 @@ namespace System.Globalization
{
if (matchLengthPtr != null)
*matchLengthPtr = 0;
- return 0;
+ return startIndex;
}
if (source.Length == 0)
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/mscorlib/src/System/Globalization/CompareInfo.cs
index b2c2208db7..593e86415d 100644
--- a/src/mscorlib/src/System/Globalization/CompareInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.cs
@@ -20,7 +20,6 @@ using System.Runtime.Serialization;
namespace System.Globalization
{
[Flags]
- [Serializable]
public enum CompareOptions
{
None = 0x00000000,
@@ -64,20 +63,21 @@ namespace System.Globalization
// locale, which is what SCOMPAREINFO does.
[OptionalField(VersionAdded = 2)]
- private string _name; // The name used to construct this CompareInfo
- [NonSerialized]
- private string _sortName; // The name that defines our behavior
+ private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization)
+
+ [NonSerialized]
+ private string _sortName; // The name that defines our behavior.
[OptionalField(VersionAdded = 3)]
- private SortVersion _sortVersion;
+ private SortVersion m_sortVersion; // Do not rename (binary serialization)
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
- [NonSerialized]
+ [NonSerialized]
private readonly bool _invariantMode = GlobalizationMode.Invariant;
internal CompareInfo(CultureInfo culture)
{
- _name = culture._name;
+ m_name = culture._name;
InitSort(culture);
}
@@ -217,7 +217,7 @@ namespace System.Globalization
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
- _name = null;
+ m_name = null;
}
void IDeserializationCallback.OnDeserialization(Object sender)
@@ -233,9 +233,9 @@ namespace System.Globalization
private void OnDeserialized()
{
- if (_name != null)
+ if (m_name != null)
{
- InitSort(CultureInfo.GetCultureInfo(_name));
+ InitSort(CultureInfo.GetCultureInfo(m_name));
}
}
@@ -259,10 +259,10 @@ namespace System.Globalization
{
get
{
- Debug.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
- if (_name == "zh-CHT" || _name == "zh-CHS")
+ Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set");
+ if (m_name == "zh-CHT" || m_name == "zh-CHS")
{
- return _name;
+ return m_name;
}
return _sortName;
@@ -1208,11 +1208,11 @@ namespace System.Globalization
{
get
{
- if (_sortVersion == null)
+ if (m_sortVersion == null)
{
if (_invariantMode)
{
- _sortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0,
+ m_sortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0,
(byte) (CultureInfo.LOCALE_INVARIANT >> 24),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8),
@@ -1220,11 +1220,11 @@ namespace System.Globalization
}
else
{
- _sortVersion = GetSortVersion();
+ m_sortVersion = GetSortVersion();
}
}
- return _sortVersion;
+ return m_sortVersion;
}
}
diff --git a/src/mscorlib/src/System/Globalization/CultureData.Unix.cs b/src/mscorlib/src/System/Globalization/CultureData.Unix.cs
deleted file mode 100644
index 4f685de580..0000000000
--- a/src/mscorlib/src/System/Globalization/CultureData.Unix.cs
+++ /dev/null
@@ -1,431 +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.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
-using System.Security;
-using System.Text;
-
-namespace System.Globalization
-{
- internal partial class CultureData
- {
- // ICU constants
- const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value
- const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name
- const string ICU_COLLATION_KEYWORD = "@collation=";
-
-
- /// <summary>
- /// This method uses the sRealName field (which is initialized by the constructor before this is called) to
- /// initialize the rest of the state of CultureData based on the underlying OS globalization library.
- /// </summary>
- private unsafe bool InitCultureData()
- {
- Debug.Assert(_sRealName != null);
-
- Debug.Assert(!GlobalizationMode.Invariant);
-
- string alternateSortName = string.Empty;
- string realNameBuffer = _sRealName;
-
- // Basic validation
- if (realNameBuffer.Contains("@"))
- {
- return false; // don't allow ICU variants to come in directly
- }
-
- // Replace _ (alternate sort) with @collation= for ICU
- int index = realNameBuffer.IndexOf('_');
- if (index > 0)
- {
- if (index >= (realNameBuffer.Length - 1) // must have characters after _
- || realNameBuffer.Substring(index + 1).Contains("_")) // only one _ allowed
- {
- return false; // fail
- }
- alternateSortName = realNameBuffer.Substring(index + 1);
- realNameBuffer = realNameBuffer.Substring(0, index) + ICU_COLLATION_KEYWORD + alternateSortName;
- }
-
- // Get the locale name from ICU
- if (!GetLocaleName(realNameBuffer, out _sWindowsName))
- {
- return false; // fail
- }
-
- // Replace the ICU collation keyword with an _
- index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal);
- if (index >= 0)
- {
- _sName = _sWindowsName.Substring(0, index) + "_" + alternateSortName;
- }
- else
- {
- _sName = _sWindowsName;
- }
- _sRealName = _sName;
-
- _iLanguage = this.ILANGUAGE;
- if (_iLanguage == 0)
- {
- _iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED;
- }
-
- _bNeutral = (this.SISO3166CTRYNAME.Length == 0);
-
- _sSpecificCulture = _bNeutral ? LocaleData.GetSpecificCultureName(_sRealName) : _sRealName;
-
- // Remove the sort from sName unless custom culture
- if (index>0 && !_bNeutral && !IsCustomCultureId(_iLanguage))
- {
- _sName = _sWindowsName.Substring(0, index);
- }
- return true;
- }
-
- internal static bool GetLocaleName(string localeName, out string windowsName)
- {
- // Get the locale name from ICU
- StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
- if (!Interop.GlobalizationInterop.GetLocaleName(localeName, sb, sb.Capacity))
- {
- StringBuilderCache.Release(sb);
- windowsName = null;
- return false; // fail
- }
-
- // Success - use the locale name returned which may be different than realNameBuffer (casing)
- windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
- return true;
- }
-
- internal static bool GetDefaultLocaleName(out string windowsName)
- {
- // Get the default (system) locale name from ICU
- StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
- if (!Interop.GlobalizationInterop.GetDefaultLocaleName(sb, sb.Capacity))
- {
- StringBuilderCache.Release(sb);
- windowsName = null;
- return false; // fail
- }
-
- // Success - use the locale name returned which may be different than realNameBuffer (casing)
- windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
- return true;
- }
-
- private string GetLocaleInfo(LocaleStringData type)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
- return GetLocaleInfo(_sWindowsName, type);
- }
-
- // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
- // "windows" name, which can be specific for downlevel (< windows 7) os's.
- private string GetLocaleInfo(string localeName, LocaleStringData type)
- {
- Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
-
- switch (type)
- {
- case LocaleStringData.NegativeInfinitySymbol:
- // not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign
- return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) +
- GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol);
- }
-
- StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
-
- bool result = Interop.GlobalizationInterop.GetLocaleInfoString(localeName, (uint)type, sb, sb.Capacity);
- if (!result)
- {
- // Failed, just use empty string
- StringBuilderCache.Release(sb);
- Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
- return String.Empty;
- }
- return StringBuilderCache.GetStringAndRelease(sb);
- }
-
- private int GetLocaleInfo(LocaleNumberData type)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
-
- switch (type)
- {
- case LocaleNumberData.CalendarType:
- // returning 0 will cause the first supported calendar to be returned, which is the preferred calendar
- return 0;
- }
-
-
- int value = 0;
- bool result = Interop.GlobalizationInterop.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value);
- if (!result)
- {
- // Failed, just use 0
- Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
- }
-
- return value;
- }
-
- private int[] GetLocaleInfo(LocaleGroupingData type)
- {
- Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
-
- int primaryGroupingSize = 0;
- int secondaryGroupingSize = 0;
- bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
- if (!result)
- {
- Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
- }
-
- if (secondaryGroupingSize == 0)
- {
- return new int[] { primaryGroupingSize };
- }
-
- return new int[] { primaryGroupingSize, secondaryGroupingSize };
- }
-
- private string GetTimeFormatString()
- {
- return GetTimeFormatString(false);
- }
-
- private string GetTimeFormatString(bool shortFormat)
- {
- Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
-
- StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
-
- bool result = Interop.GlobalizationInterop.GetLocaleTimeFormat(_sWindowsName, shortFormat, sb, sb.Capacity);
- if (!result)
- {
- // Failed, just use empty string
- StringBuilderCache.Release(sb);
- Debug.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
- return String.Empty;
- }
-
- return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb));
- }
-
- private int GetFirstDayOfWeek()
- {
- return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek);
- }
-
- private String[] GetTimeFormats()
- {
- string format = GetTimeFormatString(false);
- return new string[] { format };
- }
-
- private String[] GetShortTimeFormats()
- {
- string format = GetTimeFormatString(true);
- return new string[] { format };
- }
-
- private static CultureData GetCultureDataFromRegionName(String regionName)
- {
- // no support to lookup by region name, other than the hard-coded list in CultureData
- return null;
- }
-
- private static string GetLanguageDisplayName(string cultureName)
- {
- return new CultureInfo(cultureName)._cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
- }
-
- private static string GetRegionDisplayName(string isoCountryCode)
- {
- // use the fallback which is to return NativeName
- return null;
- }
-
- private static CultureInfo GetUserDefaultCulture()
- {
- return CultureInfo.GetUserDefaultCulture();
- }
-
- private static string ConvertIcuTimeFormatString(string icuFormatString)
- {
- StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
- bool amPmAdded = false;
-
- for (int i = 0; i < icuFormatString.Length; i++)
- {
- switch(icuFormatString[i])
- {
- case ':':
- case '.':
- case 'H':
- case 'h':
- case 'm':
- case 's':
- sb.Append(icuFormatString[i]);
- break;
-
- case ' ':
- case '\u00A0':
- // Convert nonbreaking spaces into regular spaces
- sb.Append(' ');
- break;
-
- case 'a': // AM/PM
- if (!amPmAdded)
- {
- amPmAdded = true;
- sb.Append("tt");
- }
- break;
-
- }
- }
-
- return StringBuilderCache.GetStringAndRelease(sb);
- }
-
- private static string LCIDToLocaleName(int culture)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- return LocaleData.LCIDToLocaleName(culture);
- }
-
- private static int LocaleNameToLCID(string cultureName)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- int lcid = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.Lcid);
- return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid;
- }
-
- private static int GetAnsiCodePage(string cultureName)
- {
- int ansiCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.AnsiCodePage);
- return ansiCodePage == -1 ? CultureData.Invariant.IDEFAULTANSICODEPAGE : ansiCodePage;
- }
-
- private static int GetOemCodePage(string cultureName)
- {
- int oemCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.OemCodePage);
- return oemCodePage == -1 ? CultureData.Invariant.IDEFAULTOEMCODEPAGE : oemCodePage;
- }
-
- private static int GetMacCodePage(string cultureName)
- {
- int macCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.MacCodePage);
- return macCodePage == -1 ? CultureData.Invariant.IDEFAULTMACCODEPAGE : macCodePage;
- }
-
- private static int GetEbcdicCodePage(string cultureName)
- {
- int ebcdicCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.EbcdicCodePage);
- return ebcdicCodePage == -1 ? CultureData.Invariant.IDEFAULTEBCDICCODEPAGE : ebcdicCodePage;
- }
-
- private static int GetGeoId(string cultureName)
- {
- int geoId = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.GeoId);
- return geoId == -1 ? CultureData.Invariant.IGEOID : geoId;
- }
-
- private static int GetDigitSubstitution(string cultureName)
- {
- int digitSubstitution = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.DigitSubstitution);
- return digitSubstitution == -1 ? (int) DigitShapes.None : digitSubstitution;
- }
-
- private static string GetThreeLetterWindowsLanguageName(string cultureName)
- {
- string langName = LocaleData.GetThreeLetterWindowsLangageName(cultureName);
- return langName == null ? "ZZZ" /* default lang name */ : langName;
- }
-
- private static CultureInfo[] EnumCultures(CultureTypes types)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0)
- {
- return Array.Empty<CultureInfo>();
- }
-
- int bufferLength = Interop.GlobalizationInterop.GetLocales(null, 0);
- if (bufferLength <= 0)
- {
- return Array.Empty<CultureInfo>();
- }
-
- Char [] chars = new Char[bufferLength];
-
- bufferLength = Interop.GlobalizationInterop.GetLocales(chars, bufferLength);
- if (bufferLength <= 0)
- {
- return Array.Empty<CultureInfo>();
- }
-
- bool enumNeutrals = (types & CultureTypes.NeutralCultures) != 0;
- bool enumSpecificss = (types & CultureTypes.SpecificCultures) != 0;
-
- List<CultureInfo> list = new List<CultureInfo>();
- if (enumNeutrals)
- {
- list.Add(CultureInfo.InvariantCulture);
- }
-
- int index = 0;
- while (index < bufferLength)
- {
- int length = (int) chars[index++];
- if (index + length <= bufferLength)
- {
- CultureInfo ci = CultureInfo.GetCultureInfo(new String(chars, index, length));
- if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture))
- {
- list.Add(ci);
- }
- }
-
- index += length;
- }
-
- return list.ToArray();
- }
-
- private static string GetConsoleFallbackName(string cultureName)
- {
- return LocaleData.GetConsoleUICulture(cultureName);
- }
-
- internal bool IsFramework // not applicable on Linux based systems
- {
- get { return false; }
- }
-
- internal bool IsWin32Installed // not applicable on Linux based systems
- {
- get { return false; }
- }
-
- internal bool IsReplacementCulture // not applicable on Linux based systems
- {
- get { return false; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/CultureData.Windows.cs b/src/mscorlib/src/System/Globalization/CultureData.Windows.cs
index 6d2678b550..c39327e9e7 100644
--- a/src/mscorlib/src/System/Globalization/CultureData.Windows.cs
+++ b/src/mscorlib/src/System/Globalization/CultureData.Windows.cs
@@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.Diagnostics;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
@@ -179,7 +180,7 @@ namespace System.Globalization
return new String(pBuffer);
}
- return "";
+ return null;
}
internal static unsafe int GetLocaleInfoExInt(String localeName, uint field)
@@ -195,7 +196,7 @@ namespace System.Globalization
{
Debug.Assert(!GlobalizationMode.Invariant);
- return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, (IntPtr)lpLCData, cchData);
+ return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, lpLCData, cchData);
}
private string GetLocaleInfo(LocaleStringData type)
@@ -284,19 +285,9 @@ namespace System.Globalization
context.cultureName = null;
context.regionName = regionName;
- GCHandle contextHandle = GCHandle.Alloc(context);
- try
+ unsafe
{
-#if CORECLR
- Interop.Kernel32.EnumSystemLocalesEx(EnumSystemLocalesProc, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, (IntPtr)contextHandle, IntPtr.Zero);
-#else
- IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumSystemLocalesProc);
- Interop.Kernel32.EnumSystemLocalesEx(callback, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, (IntPtr)contextHandle, IntPtr.Zero);
-#endif
- }
- finally
- {
- contextHandle.Free();
+ Interop.Kernel32.EnumSystemLocalesEx(EnumSystemLocalesProc, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, Unsafe.AsPointer(ref context), IntPtr.Zero);
}
if (context.cultureName != null)
@@ -543,15 +534,13 @@ namespace System.Globalization
}
// EnumSystemLocaleEx callback.
-#if !CORECLR
- [NativeCallable(CallingConvention = CallingConvention.StdCall)]
-#endif
- private static unsafe Interop.BOOL EnumSystemLocalesProc(IntPtr lpLocaleString, uint flags, IntPtr contextHandle)
+ // [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+ private static unsafe Interop.BOOL EnumSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle)
{
- EnumLocaleData context = (EnumLocaleData)((GCHandle)contextHandle).Target;
+ ref EnumLocaleData context = ref Unsafe.As<byte, EnumLocaleData>(ref *(byte*)contextHandle);
try
{
- string cultureName = new string((char*)lpLocaleString);
+ string cultureName = new string(lpLocaleString);
string regionName = GetLocaleInfoEx(cultureName, LOCALE_SISO3166CTRYNAME);
if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase))
{
@@ -568,15 +557,13 @@ namespace System.Globalization
}
// EnumSystemLocaleEx callback.
-#if !CORECLR
- [NativeCallable(CallingConvention = CallingConvention.StdCall)]
-#endif
- private static unsafe Interop.BOOL EnumAllSystemLocalesProc(IntPtr lpLocaleString, uint flags, IntPtr contextHandle)
+ // [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+ private static unsafe Interop.BOOL EnumAllSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle)
{
- EnumData context = (EnumData)((GCHandle)contextHandle).Target;
+ ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)contextHandle);
try
{
- context.strings.Add(new string((char*)lpLocaleString));
+ context.strings.Add(new string(lpLocaleString));
return Interop.BOOL.TRUE;
}
catch (Exception)
@@ -592,16 +579,13 @@ namespace System.Globalization
}
// EnumTimeFormatsEx callback itself.
-#if !CORECLR
- [NativeCallable(CallingConvention = CallingConvention.StdCall)]
-#endif
- private static unsafe Interop.BOOL EnumTimeCallback(IntPtr lpTimeFormatString, IntPtr lParam)
+ // [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+ private static unsafe Interop.BOOL EnumTimeCallback(char* lpTimeFormatString, void* lParam)
{
- EnumData context = (EnumData)((GCHandle)lParam).Target;
-
+ ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam);
try
{
- context.strings.Add(new string((char*)lpTimeFormatString));
+ context.strings.Add(new string(lpTimeFormatString));
return Interop.BOOL.TRUE;
}
catch (Exception)
@@ -617,21 +601,9 @@ namespace System.Globalization
EnumData data = new EnumData();
data.strings = new StringList();
- GCHandle dataHandle = GCHandle.Alloc(data);
- try
- {
-#if CORECLR
- Interop.Kernel32.EnumTimeFormatsEx(EnumTimeCallback, localeName, (uint)dwFlags, (IntPtr)dataHandle);
-#else
- // Now call the enumeration API. Work is done by our callback function
- IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, IntPtr, Interop.BOOL>>(EnumTimeCallback);
- Interop.Kernel32.EnumTimeFormatsEx(callback, localeName, (uint)dwFlags, (IntPtr)dataHandle);
-#endif
- }
- finally
- {
- dataHandle.Free();
- }
+
+ // Now call the enumeration API. Work is done by our callback function
+ Interop.Kernel32.EnumTimeFormatsEx(EnumTimeCallback, localeName, (uint)dwFlags, Unsafe.AsPointer(ref data));
if (data.strings.Count > 0)
{
@@ -757,19 +729,10 @@ namespace System.Globalization
EnumData context = new EnumData();
context.strings = new StringList();
- GCHandle contextHandle = GCHandle.Alloc(context);
- try
- {
-#if CORECLR
- Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, flags, (IntPtr)contextHandle, IntPtr.Zero);
-#else
- IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumAllSystemLocalesProc);
- Interop.Kernel32.EnumSystemLocalesEx(callback, flags, (IntPtr)contextHandle, IntPtr.Zero);
-#endif
- }
- finally
+
+ unsafe
{
- contextHandle.Free();
+ Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, flags, Unsafe.AsPointer(ref context), IntPtr.Zero);
}
CultureInfo [] cultures = new CultureInfo[context.strings.Count];
@@ -802,19 +765,10 @@ namespace System.Globalization
{
EnumData context = new EnumData();
context.strings = new StringList();
- GCHandle contextHandle = GCHandle.Alloc(context);
- try
- {
-#if CORECLR
- Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, Interop.Kernel32.LOCALE_REPLACEMENT, (IntPtr)contextHandle, IntPtr.Zero);
-#else
- IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumAllSystemLocalesProc);
- Interop.Kernel32.EnumSystemLocalesEx(callback, Interop.Kernel32.LOCALE_REPLACEMENT, (IntPtr)contextHandle, IntPtr.Zero);
-#endif
- }
- finally
+
+ unsafe
{
- contextHandle.Free();
+ Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, Interop.Kernel32.LOCALE_REPLACEMENT, Unsafe.AsPointer(ref context), IntPtr.Zero);
}
for (int i=0; i<context.strings.Count; i++)
diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs
index 60938defac..16e2d291a1 100644
--- a/src/mscorlib/src/System/Globalization/CultureInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs
@@ -44,7 +44,6 @@ namespace System.Globalization
using StringLcidDictionary = LowLevelDictionary<int, CultureInfo>;
#endif
- [Serializable]
public partial class CultureInfo : IFormatProvider, ICloneable
{
//--------------------------------------------------------------------//
diff --git a/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs b/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs
index ffb2d46a9e..ccf9993453 100644
--- a/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs
@@ -4,7 +4,6 @@
namespace System.Globalization
{
- [Serializable]
internal class CodePageDataItem
{
private readonly int _codePage;
diff --git a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs
index b049eaf45d..00081016c3 100644
--- a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using System.Text;
-using System.Runtime.Remoting;
using System;
using System.Security;
@@ -18,7 +17,6 @@ namespace System.Globalization
// immediately because they don't require creating an object. Creating any of the string
// names is delayed until somebody actually asks for them and the names are then cached.
- [Serializable]
internal class CodePageDataItem
{
internal int m_dataIndex;
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
index 6dbf5b2786..9115b12bd0 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
@@ -13,9 +13,6 @@ namespace System.Globalization
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
-
- [Serializable]
-
public class GregorianCalendar : Calendar
{
/*
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
index bdc35f0734..1367e0d0ac 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
@@ -10,7 +10,6 @@ using System.Threading;
namespace System.Globalization
{
// Gregorian Calendars use Era Info
- [Serializable]
internal class EraInfo
{
internal int era; // The value of the era.
@@ -55,7 +54,6 @@ namespace System.Globalization
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
- [Serializable]
internal class GregorianCalendarHelper
{
// 1 tick = 100ns = 10E-7 second
diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.Unix.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.Unix.cs
deleted file mode 100644
index a6e8f73d3e..0000000000
--- a/src/mscorlib/src/System/Globalization/HijriCalendar.Unix.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.Globalization
-{
- public partial class HijriCalendar : Calendar
- {
- private static int GetHijriDateAdjustment()
- {
- // this setting is not supported on Unix, so always return 0
- return 0;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs
deleted file mode 100644
index 869b809bff..0000000000
--- a/src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs
+++ /dev/null
@@ -1,96 +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;
-
-namespace System.Globalization
-{
- public partial class HijriCalendar : Calendar
- {
- private int GetHijriDateAdjustment()
- {
- if (_hijriAdvance == Int32.MinValue)
- {
- // Never been set before. Use the system value from registry.
- _hijriAdvance = GetAdvanceHijriDate();
- }
- return (_hijriAdvance);
- }
-
- private const String InternationalRegKey = "Control Panel\\International";
- private const String HijriAdvanceRegKeyEntry = "AddHijriDate";
-
- /*=================================GetAdvanceHijriDate==========================
- **Action: Gets the AddHijriDate value from the registry.
- **Returns:
- **Arguments: None.
- **Exceptions:
- **Note:
- ** The HijriCalendar has a user-overidable calculation. That is, use can set a value from the control
- ** panel, so that the calculation of the Hijri Calendar can move ahead or backwards from -2 to +2 days.
- **
- ** The valid string values in the registry are:
- ** "AddHijriDate-2" => Add -2 days to the current calculated Hijri date.
- ** "AddHijriDate" => Add -1 day to the current calculated Hijri date.
- ** "" => Add 0 day to the current calculated Hijri date.
- ** "AddHijriDate+1" => Add +1 days to the current calculated Hijri date.
- ** "AddHijriDate+2" => Add +2 days to the current calculated Hijri date.
- ============================================================================*/
- private static int GetAdvanceHijriDate()
- {
- int hijriAdvance = 0;
- Microsoft.Win32.RegistryKey key = null;
-
- try
- {
- // Open in read-only mode.
- // Use InternalOpenSubKey so that we avoid the security check.
- key = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_USER).OpenSubKey(InternationalRegKey, false);
- }
- //If this fails for any reason, we'll just return 0.
- catch (ObjectDisposedException) { return 0; }
- catch (ArgumentException) { return 0; }
-
- if (key != null)
- {
- try
- {
- Object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false);
- if (value == null)
- {
- return (0);
- }
- String str = value.ToString();
- if (String.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0)
- {
- if (str.Length == HijriAdvanceRegKeyEntry.Length)
- hijriAdvance = -1;
- else
- {
- str = str.Substring(HijriAdvanceRegKeyEntry.Length);
- try
- {
- int advance = Int32.Parse(str.ToString(), CultureInfo.InvariantCulture);
- if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri))
- {
- hijriAdvance = advance;
- }
- }
- // If we got garbage from registry just ignore it.
- // hijriAdvance = 0 because of declaraction assignment up above.
- catch (ArgumentException) { }
- catch (FormatException) { }
- catch (OverflowException) { }
- }
- }
- }
- finally
- {
- key.Close();
- }
- }
- return (hijriAdvance);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.WinRT.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.WinRT.cs
deleted file mode 100644
index fb91c27ef6..0000000000
--- a/src/mscorlib/src/System/Globalization/HijriCalendar.WinRT.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.
-
-using Internal.Runtime.Augments;
-
-namespace System.Globalization
-{
- public partial class HijriCalendar : Calendar
- {
- private static int GetHijriDateAdjustment()
- {
- return WinRTInterop.Callbacks.GetHijriDateAdjustment();
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/IdnMapping.Unix.cs b/src/mscorlib/src/System/Globalization/IdnMapping.Unix.cs
deleted file mode 100644
index f1ad6f1d0a..0000000000
--- a/src/mscorlib/src/System/Globalization/IdnMapping.Unix.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.Diagnostics;
-
-namespace System.Globalization
-{
- sealed partial class IdnMapping
- {
- private unsafe string GetAsciiCore(char* unicode, int count)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- uint flags = Flags;
- CheckInvalidIdnCharacters(unicode, count, flags, nameof(unicode));
-
- const int StackallocThreshold = 512;
- // Each unicode character is represented by up to 3 ASCII chars
- // and the whole string is prefixed by "xn--" (length 4)
- int estimatedLength = (int)Math.Min(count * 3L + 4, StackallocThreshold);
- int actualLength;
- if (estimatedLength < StackallocThreshold)
- {
- char* outputStack = stackalloc char[estimatedLength];
- actualLength = Interop.GlobalizationInterop.ToAscii(flags, unicode, count, outputStack, estimatedLength);
- if (actualLength > 0 && actualLength <= estimatedLength)
- {
- return new string(outputStack, 0, actualLength);
- }
- }
- else
- {
- actualLength = Interop.GlobalizationInterop.ToAscii(flags, unicode, count, null, 0);
- }
- if (actualLength == 0)
- {
- throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(unicode));
- }
-
- char[] outputHeap = new char[actualLength];
- fixed (char* pOutputHeap = outputHeap)
- {
- actualLength = Interop.GlobalizationInterop.ToAscii(flags, unicode, count, pOutputHeap, actualLength);
- if (actualLength == 0 || actualLength > outputHeap.Length)
- {
- throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(unicode));
- }
- return new string(pOutputHeap, 0, actualLength);
- }
- }
-
- private unsafe string GetUnicodeCore(char* ascii, int count)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- uint flags = Flags;
- CheckInvalidIdnCharacters(ascii, count, flags, nameof(ascii));
-
- const int StackAllocThreshold = 512;
- if (count < StackAllocThreshold)
- {
- char* output = stackalloc char[count];
- return GetUnicodeCore(ascii, count, flags, output, count, reattempt: true);
- }
- else
- {
- char[] output = new char[count];
- fixed (char* pOutput = output)
- {
- return GetUnicodeCore(ascii, count, flags, pOutput, count, reattempt: true);
- }
- }
- }
-
- private unsafe string GetUnicodeCore(char* ascii, int count, uint flags, char* output, int outputLength, bool reattempt)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- int realLen = Interop.GlobalizationInterop.ToUnicode(flags, ascii, count, output, outputLength);
-
- if (realLen == 0)
- {
- throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(ascii));
- }
- else if (realLen <= outputLength)
- {
- return new string(output, 0, realLen);
- }
- else if (reattempt)
- {
- char[] newOutput = new char[realLen];
- fixed (char* pNewOutput = newOutput)
- {
- return GetUnicodeCore(ascii, count, flags, pNewOutput, realLen, reattempt: false);
- }
- }
-
- throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(ascii));
- }
-
- // -----------------------------
- // ---- PAL layer ends here ----
- // -----------------------------
-
- private uint Flags
- {
- get
- {
- int flags =
- (AllowUnassigned ? Interop.GlobalizationInterop.AllowUnassigned : 0) |
- (UseStd3AsciiRules ? Interop.GlobalizationInterop.UseStd3AsciiRules : 0);
- return (uint)flags;
- }
- }
-
- /// <summary>
- /// ICU doesn't check for invalid characters unless the STD3 rules option
- /// is enabled.
- ///
- /// To match Windows behavior, we walk the string ourselves looking for these
- /// bad characters so we can continue to throw ArgumentException in these cases.
- /// </summary>
- private static unsafe void CheckInvalidIdnCharacters(char* s, int count, uint flags, string paramName)
- {
- if ((flags & Interop.GlobalizationInterop.UseStd3AsciiRules) == 0)
- {
- for (int i = 0; i < count; i++)
- {
- char c = s[i];
-
- // These characters are prohibited regardless of the UseStd3AsciiRules property.
- // See https://msdn.microsoft.com/en-us/library/system.globalization.idnmapping.usestd3asciirules(v=vs.110).aspx
- if (c <= 0x1F || c == 0x7F)
- {
- throw new ArgumentException(SR.Argument_IdnIllegalName, paramName);
- }
- }
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs
deleted file mode 100644
index 51ff8095a3..0000000000
--- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs
+++ /dev/null
@@ -1,96 +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.Diagnostics;
-
-namespace System.Globalization
-{
- public partial class JapaneseCalendar : Calendar
- {
- private static EraInfo[] GetJapaneseEras()
- {
- if (GlobalizationMode.Invariant)
- {
- return null;
- }
-
- string[] eraNames;
- if (!CalendarData.EnumCalendarInfo("ja-JP", CalendarId.JAPAN, CalendarDataType.EraNames, out eraNames))
- {
- return null;
- }
-
- string[] abbrevEnglishEraNames;
- if (!CalendarData.EnumCalendarInfo("en", CalendarId.JAPAN, CalendarDataType.AbbrevEraNames, out abbrevEnglishEraNames))
- {
- return null;
- }
-
- List<EraInfo> eras = new List<EraInfo>();
- int lastMaxYear = GregorianCalendar.MaxYear;
-
- int latestEra = Interop.GlobalizationInterop.GetLatestJapaneseEra();
- for (int i = latestEra; i >= 0; i--)
- {
- DateTime dt;
- if (!GetJapaneseEraStartDate(i, out dt))
- {
- return null;
- }
-
- if (dt < JapaneseCalendar.calendarMinValue)
- {
- // only populate the Eras that are valid JapaneseCalendar date times
- break;
- }
-
- eras.Add(new EraInfo(i, dt.Year, dt.Month, dt.Day, dt.Year - 1, 1, lastMaxYear - dt.Year + 1,
- eraNames[i], GetAbbreviatedEraName(eraNames, i), abbrevEnglishEraNames[i]));
-
- lastMaxYear = dt.Year;
- }
-
- // remap the Era numbers, now that we know how many there will be
- for (int i = 0; i < eras.Count; i++)
- {
- eras[i].era = eras.Count - i;
- }
-
- return eras.ToArray();
- }
-
- // PAL Layer ends here
-
- private static string GetAbbreviatedEraName(string[] eraNames, int eraIndex)
- {
- // This matches the behavior on Win32 - only returning the first character of the era name.
- // See Calendar.EraAsString(Int32) - https://msdn.microsoft.com/en-us/library/windows/apps/br206751.aspx
- return eraNames[eraIndex].Substring(0, 1);
- }
-
- private static bool GetJapaneseEraStartDate(int era, out DateTime dateTime)
- {
- Debug.Assert(!GlobalizationMode.Invariant);
-
- dateTime = default(DateTime);
-
- int startYear;
- int startMonth;
- int startDay;
- bool result = Interop.GlobalizationInterop.GetJapaneseEraStartDate(
- era,
- out startYear,
- out startMonth,
- out startDay);
-
- if (result)
- {
- dateTime = new DateTime(startYear, startMonth, startDay);
- }
-
- return result;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs
deleted file mode 100644
index a83c4fad9e..0000000000
--- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs
+++ /dev/null
@@ -1,209 +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 Microsoft.Win32;
-
-namespace System.Globalization
-{
- public partial class JapaneseCalendar : Calendar
- {
- private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
- private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
-
- // We know about 4 built-in eras, however users may add additional era(s) from the
- // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
- //
- // Registry values look like:
- // yyyy.mm.dd=era_abbrev_english_englishabbrev
- //
- // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
- // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
- // era is the Japanese Era name
- // abbrev is the Abbreviated Japanese Era Name
- // english is the English name for the Era (unused)
- // englishabbrev is the Abbreviated English name for the era.
- // . is a delimiter, but the value of . doesn't matter.
- // '_' marks the space between the japanese era name, japanese abbreviated era name
- // english name, and abbreviated english names.
- private static EraInfo[] GetJapaneseEras()
- {
- // Look in the registry key and see if we can find any ranges
- int iFoundEras = 0;
- EraInfo[] registryEraRanges = null;
-
- try
- {
- // Need to access registry
- RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false);
-
- // Abort if we didn't find anything
- if (key == null) return null;
-
- // Look up the values in our reg key
- String[] valueNames = key.GetValueNames();
- if (valueNames != null && valueNames.Length > 0)
- {
- registryEraRanges = new EraInfo[valueNames.Length];
-
- // Loop through the registry and read in all the values
- for (int i = 0; i < valueNames.Length; i++)
- {
- // See if the era is a valid date
- EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
-
- // continue if not valid
- if (era == null) continue;
-
- // Remember we found one.
- registryEraRanges[iFoundEras] = era;
- iFoundEras++;
- }
- }
- }
- catch (System.Security.SecurityException)
- {
- // If we weren't allowed to read, then just ignore the error
- return null;
- }
- catch (System.IO.IOException)
- {
- // If key is being deleted just ignore the error
- return null;
- }
- catch (System.UnauthorizedAccessException)
- {
- // Registry access rights permissions, just ignore the error
- return null;
- }
-
- //
- // If we didn't have valid eras, then fail
- // should have at least 4 eras
- //
- if (iFoundEras < 4) return null;
-
- //
- // Now we have eras, clean them up.
- //
- // Clean up array length
- Array.Resize(ref registryEraRanges, iFoundEras);
-
- // Sort them
- Array.Sort(registryEraRanges, CompareEraRanges);
-
- // Clean up era information
- for (int i = 0; i < registryEraRanges.Length; i++)
- {
- // eras count backwards from length to 1 (and are 1 based indexes into string arrays)
- registryEraRanges[i].era = registryEraRanges.Length - i;
-
- // update max era year
- if (i == 0)
- {
- // First range is 'til the end of the calendar
- registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset;
- }
- else
- {
- // Rest are until the next era (remember most recent era is first in array)
- registryEraRanges[i].maxEraYear = registryEraRanges[i - 1].yearOffset + 1 - registryEraRanges[i].yearOffset;
- }
- }
-
- // Return our ranges
- return registryEraRanges;
- }
-
- //
- // Compare two era ranges, eg just the ticks
- // Remember the era array is supposed to be in reverse chronological order
- //
- private static int CompareEraRanges(EraInfo a, EraInfo b)
- {
- return b.ticks.CompareTo(a.ticks);
- }
-
- //
- // GetEraFromValue
- //
- // Parse the registry value name/data pair into an era
- //
- // Registry values look like:
- // yyyy.mm.dd=era_abbrev_english_englishabbrev
- //
- // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
- // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
- // era is the Japanese Era name
- // abbrev is the Abbreviated Japanese Era Name
- // english is the English name for the Era (unused)
- // englishabbrev is the Abbreviated English name for the era.
- // . is a delimiter, but the value of . doesn't matter.
- // '_' marks the space between the japanese era name, japanese abbreviated era name
- // english name, and abbreviated english names.
- private static EraInfo GetEraFromValue(String value, String data)
- {
- // Need inputs
- if (value == null || data == null) return null;
-
- //
- // Get Date
- //
- // Need exactly 10 characters in name for date
- // yyyy.mm.dd although the . can be any character
- if (value.Length != 10) return null;
-
- int year;
- int month;
- int day;
-
- if (!Int32.TryParse(value.Substring(0, 4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) ||
- !Int32.TryParse(value.Substring(5, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) ||
- !Int32.TryParse(value.Substring(8, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day))
- {
- // Couldn't convert integer, fail
- return null;
- }
-
- //
- // Get Strings
- //
- // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
- String[] names = data.Split('_');
-
- // Should have exactly 4 parts
- // 0 - Era Name
- // 1 - Abbreviated Era Name
- // 2 - English Era Name
- // 3 - Abbreviated English Era Name
- if (names.Length != 4) return null;
-
- // Each part should have data in it
- if (names[0].Length == 0 ||
- names[1].Length == 0 ||
- names[2].Length == 0 ||
- names[3].Length == 0)
- return null;
-
- //
- // Now we have an era we can build
- // Note that the era # and max era year need cleaned up after sorting
- // Don't use the full English Era Name (names[2])
- //
- return new EraInfo(0, year, month, day, year - 1, 1, 0,
- names[0], names[1], names[3]);
- }
-
- // PAL Layer ends here
-
- private static string[] s_japaneseErasEnglishNames = new String[] { "M", "T", "S", "H" };
-
- private static string GetJapaneseEnglishEraName(int era)
- {
- Debug.Assert(era > 0);
- return era <= s_japaneseErasEnglishNames.Length ? s_japaneseErasEnglishNames[era - 1] : " ";
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.cs
deleted file mode 100644
index 6a9df97200..0000000000
--- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.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.
-
-using System.Diagnostics;
-
-using Internal.Runtime.Augments;
-
-namespace System.Globalization
-{
- public partial class JapaneseCalendar : Calendar
- {
- private static EraInfo[] GetJapaneseEras()
- {
- int erasCount = WinRTInterop.Callbacks.GetJapaneseEraCount();
- if (erasCount < 4)
- {
- return null;
- }
-
- EraInfo[] eras = new EraInfo[erasCount];
- int lastMaxYear = GregorianCalendar.MaxYear;
-
- for (int i = erasCount; i > 0; i--)
- {
- DateTimeOffset dateOffset;
-
- string eraName;
- string abbreviatedEraName;
-
- if (!GetJapaneseEraInfo(i, out dateOffset, out eraName, out abbreviatedEraName))
- {
- return null;
- }
-
- DateTime dt = new DateTime(dateOffset.Ticks);
-
- eras[erasCount - i] = new EraInfo(i, dt.Year, dt.Month, dt.Day, dt.Year - 1, 1, lastMaxYear - dt.Year + 1,
- eraName, abbreviatedEraName, GetJapaneseEnglishEraName(i)); // era #4 start year/month/day, yearOffset, minEraYear
-
- lastMaxYear = dt.Year;
- }
-
- return eras;
- }
-
- // PAL Layer ends here
-
- private static string[] JapaneseErasEnglishNames = new String[] { "M", "T", "S", "H" };
-
- private static string GetJapaneseEnglishEraName(int era)
- {
- Debug.Assert(era > 0);
- return era <= JapaneseErasEnglishNames.Length ? JapaneseErasEnglishNames[era - 1] : " ";
- }
-
- private static bool GetJapaneseEraInfo(int era, out DateTimeOffset dateOffset, out string eraName, out string abbreviatedEraName)
- {
- return WinRTInterop.Callbacks.GetJapaneseEraInfo(era, out dateOffset, out eraName, out abbreviatedEraName);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs b/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
deleted file mode 100644
index c44c085a69..0000000000
--- a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
+++ /dev/null
@@ -1,900 +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.Diagnostics.Contracts;
-using System.Runtime.Serialization;
-using System.Text;
-
-namespace System.Globalization
-{
- //
- // Property Default Description
- // PositiveSign '+' Character used to indicate positive values.
- // NegativeSign '-' Character used to indicate negative values.
- // NumberDecimalSeparator '.' The character used as the decimal separator.
- // NumberGroupSeparator ',' The character used to separate groups of
- // digits to the left of the decimal point.
- // NumberDecimalDigits 2 The default number of decimal places.
- // NumberGroupSizes 3 The number of digits in each group to the
- // left of the decimal point.
- // NaNSymbol "NaN" The string used to represent NaN values.
- // PositiveInfinitySymbol"Infinity" The string used to represent positive
- // infinities.
- // NegativeInfinitySymbol"-Infinity" The string used to represent negative
- // infinities.
- //
- //
- //
- // Property Default Description
- // CurrencyDecimalSeparator '.' The character used as the decimal
- // separator.
- // CurrencyGroupSeparator ',' The character used to separate groups
- // of digits to the left of the decimal
- // point.
- // CurrencyDecimalDigits 2 The default number of decimal places.
- // CurrencyGroupSizes 3 The number of digits in each group to
- // the left of the decimal point.
- // CurrencyPositivePattern 0 The format of positive values.
- // CurrencyNegativePattern 0 The format of negative values.
- // CurrencySymbol "$" String used as local monetary symbol.
- //
-
- [Serializable]
- sealed public class NumberFormatInfo : IFormatProvider, ICloneable
- {
- // invariantInfo is constant irrespective of your current culture.
- private static volatile NumberFormatInfo s_invariantInfo;
-
- // READTHIS READTHIS READTHIS
- // This class has an exact mapping onto a native structure defined in COMNumber.cpp
- // DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END.
- // ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets.
- // READTHIS READTHIS READTHIS
- internal int[] numberGroupSizes = new int[] { 3 };
- internal int[] currencyGroupSizes = new int[] { 3 };
- internal int[] percentGroupSizes = new int[] { 3 };
- internal String positiveSign = "+";
- internal String negativeSign = "-";
- internal String numberDecimalSeparator = ".";
- internal String numberGroupSeparator = ",";
- internal String currencyGroupSeparator = ",";
- internal String currencyDecimalSeparator = ".";
- internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund.
- internal String nanSymbol = "NaN";
- internal String positiveInfinitySymbol = "Infinity";
- internal String negativeInfinitySymbol = "-Infinity";
- internal String percentDecimalSeparator = ".";
- internal String percentGroupSeparator = ",";
- internal String percentSymbol = "%";
- internal String perMilleSymbol = "\u2030";
-
-
- [OptionalField(VersionAdded = 2)]
- internal String[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
-
- internal int numberDecimalDigits = 2;
- internal int currencyDecimalDigits = 2;
- internal int currencyPositivePattern = 0;
- internal int currencyNegativePattern = 0;
- internal int numberNegativePattern = 1;
- internal int percentPositivePattern = 0;
- internal int percentNegativePattern = 0;
- internal int percentDecimalDigits = 2;
-
- [OptionalField(VersionAdded = 2)]
- internal int digitSubstitution = (int) DigitShapes.None;
-
- internal bool isReadOnly = false;
-
- // Is this NumberFormatInfo for invariant culture?
-
- [OptionalField(VersionAdded = 2)]
- internal bool m_isInvariant = false;
-
- public NumberFormatInfo() : this(null)
- {
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx) { }
-
- [OnDeserializing]
- private void OnDeserializing(StreamingContext ctx) { }
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx) { }
-
- private static void VerifyDecimalSeparator(String decSep, String propertyName)
- {
- if (decSep == null)
- {
- throw new ArgumentNullException(propertyName,
- SR.ArgumentNull_String);
- }
-
- if (decSep.Length == 0)
- {
- throw new ArgumentException(SR.Argument_EmptyDecString);
- }
- Contract.EndContractBlock();
- }
-
- private static void VerifyGroupSeparator(String groupSep, String propertyName)
- {
- if (groupSep == null)
- {
- throw new ArgumentNullException(propertyName,
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
- }
-
- private static void VerifyNativeDigits(string [] nativeDig, string propertyName)
- {
- if (nativeDig == null)
- {
- throw new ArgumentNullException(propertyName, SR.ArgumentNull_Array);
- }
-
- if (nativeDig.Length != 10)
- {
- throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName);
- }
- Contract.EndContractBlock();
-
- for (int i = 0; i < nativeDig.Length; i++)
- {
- if (nativeDig[i] == null)
- {
- throw new ArgumentNullException(propertyName, SR.ArgumentNull_ArrayValue);
- }
-
- if (nativeDig[i].Length != 1)
- {
- if (nativeDig[i].Length != 2)
- {
- // Not 1 or 2 UTF-16 code points
- throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
- }
- else if (!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1]))
- {
- // 2 UTF-6 code points, but not a surrogate pair
- throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
- }
- }
-
- if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i &&
- CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse)
- {
- // Not the appropriate digit according to the Unicode data properties
- // (Digit 0 must be a 0, etc.).
- throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
- }
- }
- }
-
- private static void VerifyDigitSubstitution(DigitShapes digitSub, string propertyName)
- {
- switch (digitSub)
- {
- case DigitShapes.Context:
- case DigitShapes.None:
- case DigitShapes.NativeNational:
- // Success.
- break;
-
- default:
- throw new ArgumentException(SR.Argument_InvalidDigitSubstitution, propertyName);
- }
- }
-
- internal NumberFormatInfo(CultureData cultureData)
- {
- if (cultureData != null)
- {
- // We directly use fields here since these data is coming from data table or Win32, so we
- // don't need to verify their values (except for invalid parsing situations).
- cultureData.GetNFIValues(this);
-
- if (cultureData.IsInvariantCulture)
- {
- // For invariant culture
- this.m_isInvariant = true;
- }
- }
- }
-
- [Pure]
- private void VerifyWritable()
- {
- if (isReadOnly)
- {
- throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
- }
- Contract.EndContractBlock();
- }
-
- // Returns a default NumberFormatInfo that will be universally
- // supported and constant irrespective of the current culture.
- // Used by FromString methods.
- //
-
- public static NumberFormatInfo InvariantInfo
- {
- get
- {
- if (s_invariantInfo == null)
- {
- // Lazy create the invariant info. This cannot be done in a .cctor because exceptions can
- // be thrown out of a .cctor stack that will need this.
- NumberFormatInfo nfi = new NumberFormatInfo();
- nfi.m_isInvariant = true;
- s_invariantInfo = ReadOnly(nfi);
- }
- return s_invariantInfo;
- }
- }
-
- public static NumberFormatInfo GetInstance(IFormatProvider formatProvider)
- {
- // Fast case for a regular CultureInfo
- NumberFormatInfo info;
- CultureInfo cultureProvider = formatProvider as CultureInfo;
- if (cultureProvider != null && !cultureProvider._isInherited)
- {
- info = cultureProvider.numInfo;
- if (info != null)
- {
- return info;
- }
- else
- {
- return cultureProvider.NumberFormat;
- }
- }
- // Fast case for an NFI;
- info = formatProvider as NumberFormatInfo;
- if (info != null)
- {
- return info;
- }
- if (formatProvider != null)
- {
- info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
- if (info != null)
- {
- return info;
- }
- }
- return CurrentInfo;
- }
-
-
-
- public Object Clone()
- {
- NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone();
- n.isReadOnly = false;
- return n;
- }
-
-
- public int CurrencyDecimalDigits
- {
- get { return currencyDecimalDigits; }
- set
- {
- if (value < 0 || value > 99)
- {
- throw new ArgumentOutOfRangeException(
- nameof(CurrencyDecimalDigits),
- String.Format(
- CultureInfo.CurrentCulture,
- SR.ArgumentOutOfRange_Range,
- 0,
- 99));
- }
- Contract.EndContractBlock();
- VerifyWritable();
- currencyDecimalDigits = value;
- }
- }
-
-
- public String CurrencyDecimalSeparator
- {
- get { return currencyDecimalSeparator; }
- set
- {
- VerifyWritable();
- VerifyDecimalSeparator(value, "CurrencyDecimalSeparator");
- currencyDecimalSeparator = value;
- }
- }
-
-
- public bool IsReadOnly
- {
- get
- {
- return isReadOnly;
- }
- }
-
- //
- // Check the values of the groupSize array.
- //
- // Every element in the groupSize array should be between 1 and 9
- // excpet the last element could be zero.
- //
- internal static void CheckGroupSize(String propName, int[] groupSize)
- {
- for (int i = 0; i < groupSize.Length; i++)
- {
- if (groupSize[i] < 1)
- {
- if (i == groupSize.Length - 1 && groupSize[i] == 0)
- return;
- throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
- }
- else if (groupSize[i] > 9)
- {
- throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
- }
- }
- }
-
-
- public int[] CurrencyGroupSizes
- {
- get
- {
- return ((int[])currencyGroupSizes.Clone());
- }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(CurrencyGroupSizes),
- SR.ArgumentNull_Obj);
- }
- Contract.EndContractBlock();
- VerifyWritable();
-
- Int32[] inputSizes = (Int32[])value.Clone();
- CheckGroupSize(nameof(CurrencyGroupSizes), inputSizes);
- currencyGroupSizes = inputSizes;
- }
- }
-
-
-
- public int[] NumberGroupSizes
- {
- get
- {
- return ((int[])numberGroupSizes.Clone());
- }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(NumberGroupSizes),
- SR.ArgumentNull_Obj);
- }
- Contract.EndContractBlock();
- VerifyWritable();
-
- Int32[] inputSizes = (Int32[])value.Clone();
- CheckGroupSize(nameof(NumberGroupSizes), inputSizes);
- numberGroupSizes = inputSizes;
- }
- }
-
-
- public int[] PercentGroupSizes
- {
- get
- {
- return ((int[])percentGroupSizes.Clone());
- }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException("PercentGroupSizes",
- SR.ArgumentNull_Obj);
- }
- Contract.EndContractBlock();
- VerifyWritable();
- Int32[] inputSizes = (Int32[])value.Clone();
- CheckGroupSize("PercentGroupSizes", inputSizes);
- percentGroupSizes = inputSizes;
- }
- }
-
-
- public String CurrencyGroupSeparator
- {
- get { return currencyGroupSeparator; }
- set
- {
- VerifyWritable();
- VerifyGroupSeparator(value, nameof(CurrencyGroupSeparator));
- currencyGroupSeparator = value;
- }
- }
-
-
- public String CurrencySymbol
- {
- get { return currencySymbol; }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(CurrencySymbol),
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
- VerifyWritable();
- currencySymbol = value;
- }
- }
-
- // Returns the current culture's NumberFormatInfo. Used by Parse methods.
- //
-
- public static NumberFormatInfo CurrentInfo
- {
- get
- {
- System.Globalization.CultureInfo culture = CultureInfo.CurrentCulture;
- if (!culture._isInherited)
- {
- NumberFormatInfo info = culture.numInfo;
- if (info != null)
- {
- return info;
- }
- }
- return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)));
- }
- }
-
-
- public String NaNSymbol
- {
- get
- {
- return nanSymbol;
- }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(NaNSymbol),
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
- VerifyWritable();
- nanSymbol = value;
- }
- }
-
-
-
- public int CurrencyNegativePattern
- {
- get { return currencyNegativePattern; }
- set
- {
- if (value < 0 || value > 15)
- {
- throw new ArgumentOutOfRangeException(
- nameof(CurrencyNegativePattern),
- String.Format(
- CultureInfo.CurrentCulture,
- SR.ArgumentOutOfRange_Range,
- 0,
- 15));
- }
- Contract.EndContractBlock();
- VerifyWritable();
- currencyNegativePattern = value;
- }
- }
-
-
- public int NumberNegativePattern
- {
- get { return numberNegativePattern; }
- set
- {
- //
- // NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp.
- //
- if (value < 0 || value > 4)
- {
- throw new ArgumentOutOfRangeException(
- nameof(NumberNegativePattern),
- String.Format(
- CultureInfo.CurrentCulture,
- SR.ArgumentOutOfRange_Range,
- 0,
- 4));
- }
- Contract.EndContractBlock();
- VerifyWritable();
- numberNegativePattern = value;
- }
- }
-
-
- public int PercentPositivePattern
- {
- get { return percentPositivePattern; }
- set
- {
- //
- // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
- //
- if (value < 0 || value > 3)
- {
- throw new ArgumentOutOfRangeException(
- nameof(PercentPositivePattern),
- String.Format(
- CultureInfo.CurrentCulture,
- SR.ArgumentOutOfRange_Range,
- 0,
- 3));
- }
- Contract.EndContractBlock();
- VerifyWritable();
- percentPositivePattern = value;
- }
- }
-
-
- public int PercentNegativePattern
- {
- get { return percentNegativePattern; }
- set
- {
- //
- // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
- //
- if (value < 0 || value > 11)
- {
- throw new ArgumentOutOfRangeException(
- nameof(PercentNegativePattern),
- String.Format(
- CultureInfo.CurrentCulture,
- SR.ArgumentOutOfRange_Range,
- 0,
- 11));
- }
- Contract.EndContractBlock();
- VerifyWritable();
- percentNegativePattern = value;
- }
- }
-
-
- public String NegativeInfinitySymbol
- {
- get
- {
- return negativeInfinitySymbol;
- }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(NegativeInfinitySymbol),
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
- VerifyWritable();
- negativeInfinitySymbol = value;
- }
- }
-
-
- public String NegativeSign
- {
- get { return negativeSign; }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(NegativeSign),
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
- VerifyWritable();
- negativeSign = value;
- }
- }
-
-
- public int NumberDecimalDigits
- {
- get { return numberDecimalDigits; }
- set
- {
- if (value < 0 || value > 99)
- {
- throw new ArgumentOutOfRangeException(
- nameof(NumberDecimalDigits),
- String.Format(
- CultureInfo.CurrentCulture,
- SR.ArgumentOutOfRange_Range,
- 0,
- 99));
- }
- Contract.EndContractBlock();
- VerifyWritable();
- numberDecimalDigits = value;
- }
- }
-
-
- public String NumberDecimalSeparator
- {
- get { return numberDecimalSeparator; }
- set
- {
- VerifyWritable();
- VerifyDecimalSeparator(value, nameof(NumberDecimalSeparator));
- numberDecimalSeparator = value;
- }
- }
-
-
- public String NumberGroupSeparator
- {
- get { return numberGroupSeparator; }
- set
- {
- VerifyWritable();
- VerifyGroupSeparator(value, nameof(NumberGroupSeparator));
- numberGroupSeparator = value;
- }
- }
-
-
- public int CurrencyPositivePattern
- {
- get { return currencyPositivePattern; }
- set
- {
- if (value < 0 || value > 3)
- {
- throw new ArgumentOutOfRangeException(
- nameof(CurrencyPositivePattern),
- String.Format(
- CultureInfo.CurrentCulture,
- SR.ArgumentOutOfRange_Range,
- 0,
- 3));
- }
- Contract.EndContractBlock();
- VerifyWritable();
- currencyPositivePattern = value;
- }
- }
-
-
- public String PositiveInfinitySymbol
- {
- get
- {
- return positiveInfinitySymbol;
- }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(PositiveInfinitySymbol),
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
- VerifyWritable();
- positiveInfinitySymbol = value;
- }
- }
-
-
- public String PositiveSign
- {
- get { return positiveSign; }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(PositiveSign),
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
- VerifyWritable();
- positiveSign = value;
- }
- }
-
-
- public int PercentDecimalDigits
- {
- get { return percentDecimalDigits; }
- set
- {
- if (value < 0 || value > 99)
- {
- throw new ArgumentOutOfRangeException(
- nameof(PercentDecimalDigits),
- String.Format(
- CultureInfo.CurrentCulture,
- SR.ArgumentOutOfRange_Range,
- 0,
- 99));
- }
- Contract.EndContractBlock();
- VerifyWritable();
- percentDecimalDigits = value;
- }
- }
-
-
- public String PercentDecimalSeparator
- {
- get { return percentDecimalSeparator; }
- set
- {
- VerifyWritable();
- VerifyDecimalSeparator(value, nameof(PercentDecimalSeparator));
- percentDecimalSeparator = value;
- }
- }
-
-
- public String PercentGroupSeparator
- {
- get { return percentGroupSeparator; }
- set
- {
- VerifyWritable();
- VerifyGroupSeparator(value, nameof(PercentGroupSeparator));
- percentGroupSeparator = value;
- }
- }
-
-
- public String PercentSymbol
- {
- get
- {
- return percentSymbol;
- }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(PercentSymbol),
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
- VerifyWritable();
- percentSymbol = value;
- }
- }
-
-
- public String PerMilleSymbol
- {
- get { return perMilleSymbol; }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(PerMilleSymbol),
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
- VerifyWritable();
- perMilleSymbol = value;
- }
- }
-
- public string [] NativeDigits
- {
- get { return (String[]) nativeDigits.Clone(); }
- set
- {
- VerifyWritable();
- VerifyNativeDigits(value, nameof(NativeDigits));
- nativeDigits = value;
- }
- }
-
- public DigitShapes DigitSubstitution
- {
- get { return (DigitShapes) digitSubstitution; }
- set
- {
- VerifyWritable();
- VerifyDigitSubstitution(value, nameof(DigitSubstitution));
- digitSubstitution = (int) value;
- }
- }
-
- public Object GetFormat(Type formatType)
- {
- return formatType == typeof(NumberFormatInfo) ? this : null;
- }
-
- public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi)
- {
- if (nfi == null)
- {
- throw new ArgumentNullException(nameof(nfi));
- }
- Contract.EndContractBlock();
- if (nfi.IsReadOnly)
- {
- return (nfi);
- }
- NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone());
- info.isReadOnly = true;
- return info;
- }
-
- // private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00);
- private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
- | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
- | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
- | NumberStyles.AllowThousands | NumberStyles.AllowExponent
- | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
-
- internal static void ValidateParseStyleInteger(NumberStyles style)
- {
- // Check for undefined flags
- if ((style & InvalidNumberStyles) != 0)
- {
- throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
- }
- Contract.EndContractBlock();
- if ((style & NumberStyles.AllowHexSpecifier) != 0)
- { // Check for hex number
- if ((style & ~NumberStyles.HexNumber) != 0)
- {
- throw new ArgumentException(SR.Arg_InvalidHexStyle);
- }
- }
- }
-
- internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
- {
- // Check for undefined flags
- if ((style & InvalidNumberStyles) != 0)
- {
- throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
- }
- Contract.EndContractBlock();
- if ((style & NumberStyles.AllowHexSpecifier) != 0)
- { // Check for hex number
- throw new ArgumentException(SR.Arg_HexStyleNotSupported);
- }
- }
- } // NumberFormatInfo
-}
-
-
-
-
-
-
-
-
-
diff --git a/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/mscorlib/src/System/Globalization/RegionInfo.cs
index c3d5e659ca..ab52002fdc 100644
--- a/src/mscorlib/src/System/Globalization/RegionInfo.cs
+++ b/src/mscorlib/src/System/Globalization/RegionInfo.cs
@@ -20,7 +20,6 @@ using System.Runtime.Serialization;
namespace System.Globalization
{
- [Serializable]
public class RegionInfo
{
//--------------------------------------------------------------------//
diff --git a/src/mscorlib/src/System/Globalization/SortKey.cs b/src/mscorlib/src/System/Globalization/SortKey.cs
deleted file mode 100644
index 0930965e5d..0000000000
--- a/src/mscorlib/src/System/Globalization/SortKey.cs
+++ /dev/null
@@ -1,203 +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.
-
-////////////////////////////////////////////////////////////////////////////
-//
-//
-// Purpose: This class implements a set of methods for retrieving
-// sort key information.
-//
-//
-////////////////////////////////////////////////////////////////////////////
-
-namespace System.Globalization
-{
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- public partial class SortKey
- {
- //--------------------------------------------------------------------//
- // Internal Information //
- //--------------------------------------------------------------------//
-
- [OptionalField(VersionAdded = 3)]
- internal string _localeName; // locale identifier
-
- [OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it
- internal int _win32LCID;
- // Whidbey serialization
-
- internal CompareOptions _options; // options
- internal string _string; // original string
- internal byte[] _keyData; // sortkey data
-
- //
- // The following constructor is designed to be called from CompareInfo to get the
- // the sort key of specific string for synthetic culture
- //
- internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData)
- {
- _keyData = keyData;
- _localeName = localeName;
- _options = options;
- _string = str;
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext context)
- {
- //set LCID to proper value for Whidbey serialization (no other use)
- if (_win32LCID == 0)
- {
- _win32LCID = CultureInfo.GetCultureInfo(_localeName).LCID;
- }
- }
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext context)
- {
- //set locale name to proper value after Whidbey deserialization
- if (String.IsNullOrEmpty(_localeName) && _win32LCID != 0)
- {
- _localeName = CultureInfo.GetCultureInfo(_win32LCID).Name;
- }
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // GetOriginalString
- //
- // Returns the original string used to create the current instance
- // of SortKey.
- //
- ////////////////////////////////////////////////////////////////////////
- public virtual String OriginalString
- {
- get
- {
- return (_string);
- }
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // GetKeyData
- //
- // Returns a byte array representing the current instance of the
- // sort key.
- //
- ////////////////////////////////////////////////////////////////////////
- public virtual byte[] KeyData
- {
- get
- {
- return (byte[])(_keyData.Clone());
- }
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // Compare
- //
- // Compares the two sort keys. Returns 0 if the two sort keys are
- // equal, a number less than 0 if sortkey1 is less than sortkey2,
- // and a number greater than 0 if sortkey1 is greater than sortkey2.
- //
- ////////////////////////////////////////////////////////////////////////
- public static int Compare(SortKey sortkey1, SortKey sortkey2)
- {
- if (sortkey1==null || sortkey2==null)
- {
- throw new ArgumentNullException((sortkey1 == null ? nameof(sortkey1) : nameof(sortkey2)));
- }
- Contract.EndContractBlock();
- byte[] key1Data = sortkey1._keyData;
- byte[] key2Data = sortkey2._keyData;
-
- Debug.Assert(key1Data != null, "key1Data != null");
- Debug.Assert(key2Data != null, "key2Data != null");
-
- if (key1Data.Length == 0)
- {
- if (key2Data.Length == 0)
- {
- return (0);
- }
- return (-1);
- }
- if (key2Data.Length == 0)
- {
- return (1);
- }
-
- int compLen = (key1Data.Length < key2Data.Length) ? key1Data.Length : key2Data.Length;
-
- for (int i=0; i<compLen; i++)
- {
- if (key1Data[i]>key2Data[i])
- {
- return (1);
- }
- if (key1Data[i]<key2Data[i])
- {
- return (-1);
- }
- }
-
- return 0;
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // Equals
- //
- // Implements Object.Equals(). Returns a boolean indicating whether
- // or not object refers to the same SortKey as the current instance.
- //
- ////////////////////////////////////////////////////////////////////////
- public override bool Equals(Object value)
- {
- SortKey that = value as SortKey;
-
- if (that != null)
- {
- return Compare(this, that) == 0;
- }
-
- return (false);
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // GetHashCode
- //
- // Implements Object.GetHashCode(). Returns the hash code for the
- // SortKey. The hash code is guaranteed to be the same for
- // SortKey A and B where A.Equals(B) is true.
- //
- ////////////////////////////////////////////////////////////////////////
- public override int GetHashCode()
- {
- return (CompareInfo.GetCompareInfo(_localeName).GetHashCodeOfString(_string, _options));
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // ToString
- //
- // Implements Object.ToString(). Returns a string describing the
- // SortKey.
- //
- ////////////////////////////////////////////////////////////////////////
- public override String ToString()
- {
- return ("SortKey - " + _localeName + ", " + _options + ", " + _string);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/StringInfo.cs b/src/mscorlib/src/System/Globalization/StringInfo.cs
deleted file mode 100644
index f1dd30561b..0000000000
--- a/src/mscorlib/src/System/Globalization/StringInfo.cs
+++ /dev/null
@@ -1,374 +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.
-
-////////////////////////////////////////////////////////////////////////////
-//
-//
-// Purpose: This class defines behaviors specific to a writing system.
-// A writing system is the collection of scripts and
-// orthographic rules required to represent a language as text.
-//
-//
-////////////////////////////////////////////////////////////////////////////
-
-using System;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Runtime.Serialization;
-
-namespace System.Globalization
-{
- [Serializable]
- public class StringInfo
- {
- [OptionalField(VersionAdded = 2)]
- private string _str;
-
- [NonSerialized]
- private int[] _indexes;
-
- // Legacy constructor
- public StringInfo() : this("") { }
-
- // Primary, useful constructor
- public StringInfo(string value)
- {
- this.String = value;
- }
-
- [OnDeserializing]
- private void OnDeserializing(StreamingContext ctx)
- {
- _str = String.Empty;
- }
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
- {
- if (_str.Length == 0)
- {
- _indexes = null;
- }
- }
-
- public override bool Equals(Object value)
- {
- StringInfo that = value as StringInfo;
- if (that != null)
- {
- return (_str.Equals(that._str));
- }
- return (false);
- }
-
- public override int GetHashCode()
- {
- return _str.GetHashCode();
- }
-
-
- // Our zero-based array of index values into the string. Initialize if
- // our private array is not yet, in fact, initialized.
- private int[] Indexes
- {
- get
- {
- if ((null == _indexes) && (0 < this.String.Length))
- {
- _indexes = StringInfo.ParseCombiningCharacters(this.String);
- }
-
- return (_indexes);
- }
- }
-
- public string String
- {
- get
- {
- return (_str);
- }
- set
- {
- if (null == value)
- {
- throw new ArgumentNullException("String",
- SR.ArgumentNull_String);
- }
- Contract.EndContractBlock();
-
- _str = value;
- _indexes = null;
- }
- }
-
- public int LengthInTextElements
- {
- get
- {
- if (null == this.Indexes)
- {
- // Indexes not initialized, so assume length zero
- return (0);
- }
-
- return (this.Indexes.Length);
- }
- }
-
- public string SubstringByTextElements(int startingTextElement)
- {
- // If the string is empty, no sense going further.
- if (null == this.Indexes)
- {
- // Just decide which error to give depending on the param they gave us....
- if (startingTextElement < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
- }
- else
- {
- throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
- }
- }
- return (SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement));
- }
-
- public string SubstringByTextElements(int startingTextElement, int lengthInTextElements)
- {
- if (startingTextElement < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
- }
-
- if (this.String.Length == 0 || startingTextElement >= Indexes.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
- }
-
- if (lengthInTextElements < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.ArgumentOutOfRange_NeedPosNum);
- }
-
- if (startingTextElement > Indexes.Length - lengthInTextElements)
- {
- throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.Arg_ArgumentOutOfRangeException);
- }
-
- int start = Indexes[startingTextElement];
-
- if (startingTextElement + lengthInTextElements == Indexes.Length)
- {
- // We are at the last text element in the string and because of that
- // must handle the call differently.
- return (this.String.Substring(start));
- }
- else
- {
- return (this.String.Substring(start, (Indexes[lengthInTextElements + startingTextElement] - start)));
- }
- }
-
- public static string GetNextTextElement(string str)
- {
- return (GetNextTextElement(str, 0));
- }
-
-
- ////////////////////////////////////////////////////////////////////////
- //
- // Get the code point count of the current text element.
- //
- // A combining class is defined as:
- // A character/surrogate that has the following Unicode category:
- // * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
- // * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
- // * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
- //
- // In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
- //
- // 1. If a character/surrogate is in the following category, it is a text element.
- // It can NOT further combine with characters in the combinging class to form a text element.
- // * one of the Unicode category in the combinging class
- // * UnicodeCategory.Format
- // * UnicodeCateogry.Control
- // * UnicodeCategory.OtherNotAssigned
- // 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
- //
- // Return:
- // The length of the current text element
- //
- // Parameters:
- // String str
- // index The starting index
- // len The total length of str (to define the upper boundary)
- // ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element.
- // currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
- //
- ////////////////////////////////////////////////////////////////////////
-
- internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
- {
- Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
- Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
- if (index + currentCharCount == len)
- {
- // This is the last character/surrogate in the string.
- return (currentCharCount);
- }
-
- // Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
- int nextCharCount;
- UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
- if (CharUnicodeInfo.IsCombiningCategory(ucNext))
- {
- // The next element is a combining class.
- // Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
- // not a format character, and not a control character).
-
- if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
- || (ucCurrent == UnicodeCategory.Format)
- || (ucCurrent == UnicodeCategory.Control)
- || (ucCurrent == UnicodeCategory.OtherNotAssigned)
- || (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
- {
- // Will fall thru and return the currentCharCount
- }
- else
- {
- int startIndex = index; // Remember the current index.
-
- // We have a valid base characters, and we have a character (or surrogate) that is combining.
- // Check if there are more combining characters to follow.
- // Check if the next character is a nonspacing character.
- index += currentCharCount + nextCharCount;
-
- while (index < len)
- {
- ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
- if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
- {
- ucCurrent = ucNext;
- currentCharCount = nextCharCount;
- break;
- }
- index += nextCharCount;
- }
- return (index - startIndex);
- }
- }
- // The return value will be the currentCharCount.
- int ret = currentCharCount;
- ucCurrent = ucNext;
- // Update currentCharCount.
- currentCharCount = nextCharCount;
- return (ret);
- }
-
- // Returns the str containing the next text element in str starting at
- // index index. If index is not supplied, then it will start at the beginning
- // of str. It recognizes a base character plus one or more combining
- // characters or a properly formed surrogate pair as a text element. See also
- // the ParseCombiningCharacters() and the ParseSurrogates() methods.
- public static string GetNextTextElement(string str, int index)
- {
- //
- // Validate parameters.
- //
- if (str == null)
- {
- throw new ArgumentNullException(nameof(str));
- }
- Contract.EndContractBlock();
-
- int len = str.Length;
- if (index < 0 || index >= len)
- {
- if (index == len)
- {
- return (String.Empty);
- }
- throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
- }
-
- int charLen;
- UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
- return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
- }
-
- public static TextElementEnumerator GetTextElementEnumerator(string str)
- {
- return (GetTextElementEnumerator(str, 0));
- }
-
- public static TextElementEnumerator GetTextElementEnumerator(string str, int index)
- {
- //
- // Validate parameters.
- //
- if (str == null)
- {
- throw new ArgumentNullException(nameof(str));
- }
- Contract.EndContractBlock();
-
- int len = str.Length;
- if (index < 0 || (index > len))
- {
- throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
- }
-
- return (new TextElementEnumerator(str, index, len));
- }
-
- /*
- * Returns the indices of each base character or properly formed surrogate pair
- * within the str. It recognizes a base character plus one or more combining
- * characters or a properly formed surrogate pair as a text element and returns
- * the index of the base character or high surrogate. Each index is the
- * beginning of a text element within a str. The length of each element is
- * easily computed as the difference between successive indices. The length of
- * the array will always be less than or equal to the length of the str. For
- * example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would
- * return the indices: 0, 2, 4.
- */
-
- public static int[] ParseCombiningCharacters(string str)
- {
- if (str == null)
- {
- throw new ArgumentNullException(nameof(str));
- }
- Contract.EndContractBlock();
-
- int len = str.Length;
- int[] result = new int[len];
- if (len == 0)
- {
- return (result);
- }
-
- int resultCount = 0;
-
- int i = 0;
- int currentCharLen;
- UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
-
- while (i < len)
- {
- result[resultCount++] = i;
- i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
- }
-
- if (resultCount < len)
- {
- int[] returnArray = new int[resultCount];
- Array.Copy(result, returnArray, resultCount);
- return (returnArray);
- }
- return (result);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
index 464897b03f..a875b70463 100644
--- a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
+++ b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
@@ -20,7 +20,6 @@ namespace System.Globalization
// This is public because GetTextElement() is public.
//
- [Serializable]
public class TextElementEnumerator : IEnumerator
{
private String _str;
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs
index fecd2b2970..dd542579d9 100644
--- a/src/mscorlib/src/System/Globalization/TextInfo.cs
+++ b/src/mscorlib/src/System/Globalization/TextInfo.cs
@@ -19,7 +19,6 @@ using System.Text;
namespace System.Globalization
{
- [Serializable]
public partial class TextInfo : ICloneable, IDeserializationCallback
{
////--------------------------------------------------------------------//
@@ -93,38 +92,9 @@ namespace System.Globalization
FinishInitialization(_textInfoName);
}
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx) { }
-
- [OnDeserializing]
- private void OnDeserializing(StreamingContext ctx)
- {
- // Clear these so we can check if we've fixed them yet
- _cultureData = null;
- _cultureName = null;
- }
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
- {
- OnDeserialized();
- }
-
void IDeserializationCallback.OnDeserialization(Object sender)
{
- OnDeserialized();
- }
-
- private void OnDeserialized()
- {
- // this method will be called twice because of the support of IDeserializationCallback
- if (_cultureData == null)
- {
- // Get the text info name belonging to that culture
- _cultureData = CultureInfo.GetCultureInfo(_cultureName)._cultureData;
- _textInfoName = _cultureData.STEXTINFO;
- FinishInitialization(_textInfoName);
- }
+ throw new PlatformNotSupportedException();
}
//
diff --git a/src/mscorlib/src/System/IO/BinaryWriter.cs b/src/mscorlib/src/System/IO/BinaryWriter.cs
index 3d9839f46e..644226fa79 100644
--- a/src/mscorlib/src/System/IO/BinaryWriter.cs
+++ b/src/mscorlib/src/System/IO/BinaryWriter.cs
@@ -27,7 +27,6 @@ namespace System.IO
// primitives to an arbitrary stream. A subclass can override methods to
// give unique encodings.
//
- [Serializable]
public class BinaryWriter : IDisposable
{
public static readonly BinaryWriter Null = new BinaryWriter();
diff --git a/src/mscorlib/src/System/IO/DriveNotFoundException.cs b/src/mscorlib/src/System/IO/DriveNotFoundException.cs
index 27b6f9015d..7e9b0c9f36 100644
--- a/src/mscorlib/src/System/IO/DriveNotFoundException.cs
+++ b/src/mscorlib/src/System/IO/DriveNotFoundException.cs
@@ -17,7 +17,6 @@ using System.Runtime.Serialization;
namespace System.IO
{
//Thrown when trying to access a drive that is not availabe.
- [Serializable]
internal class DriveNotFoundException : IOException
{
public DriveNotFoundException()
@@ -34,6 +33,7 @@ namespace System.IO
protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/IO/EncodingCache.cs b/src/mscorlib/src/System/IO/EncodingCache.cs
deleted file mode 100644
index 53379bc77f..0000000000
--- a/src/mscorlib/src/System/IO/EncodingCache.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.
-
-using System.Text;
-
-namespace System.IO
-{
- internal static class EncodingCache
- {
- internal static readonly Encoding UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
- }
-}
diff --git a/src/mscorlib/src/System/IO/File.cs b/src/mscorlib/src/System/IO/File.cs
index 4aba1488ec..da962f6feb 100644
--- a/src/mscorlib/src/System/IO/File.cs
+++ b/src/mscorlib/src/System/IO/File.cs
@@ -150,13 +150,16 @@ namespace System.IO
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
String tempPath = path.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
+#if !PLATFORM_UNIX
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
- // SetErrorMode will let us disable this, but we should set the error
+ // SetThreadErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
- int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
+ uint oldMode;
+ bool errorModeSuccess = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
+#endif
bool error = false;
SafeFindHandle handle = Win32Native.FindFirstFile(tempPath, findData);
try
@@ -197,31 +200,41 @@ namespace System.IO
}
}
}
+#if !PLATFORM_UNIX
}
finally
{
- Win32Native.SetErrorMode(oldMode);
+ if (errorModeSuccess)
+ Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
+#endif
// Copy the information to data
data.PopulateFrom(findData);
}
else
{
+ bool success = false;
+
+#if !PLATFORM_UNIX
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
- // SetErrorMode will let us disable this, but we should set the error
+ // SetThreadErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
- bool success = false;
- int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
+ uint oldMode;
+ bool errorModeSuccess = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
+#endif
success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data);
+#if !PLATFORM_UNIX
}
finally
{
- Win32Native.SetErrorMode(oldMode);
+ if (errorModeSuccess)
+ Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
+#endif
if (!success)
{
diff --git a/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
index f6415670e3..d4ce9a9ab9 100644
--- a/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
+++ b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
@@ -27,7 +27,10 @@ namespace System.IO
GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format));
string message = null;
- GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
+ if (hResult == System.__HResults.COR_E_BADEXEFORMAT)
+ message = SR.Arg_BadImageFormatException;
+ else
+ GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
return string.Format(CultureInfo.CurrentCulture, format, fileName, message);
}
diff --git a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
index 0316de0f93..5e19fbed36 100644
--- a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
+++ b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
@@ -146,8 +146,10 @@ namespace System.IO
private SearchOption searchOption;
private String fullPath;
private String normalizedSearchPath;
- private int oldMode;
-
+#if !PLATFORM_UNIX
+ private int _oldMode;
+ private bool _setBackOldMode;
+#endif
internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler<TSource> resultHandler, bool checkHost)
{
Contract.Requires(path != null);
@@ -156,7 +158,9 @@ namespace System.IO
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Requires(resultHandler != null);
- oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
+#if !PLATFORM_UNIX
+ _setBackOldMode = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out _oldMode);
+#endif
searchStack = new List<Directory.SearchData>();
@@ -284,7 +288,14 @@ namespace System.IO
}
finally
{
- Win32Native.SetErrorMode(oldMode);
+#if !PLATFORM_UNIX
+ if (_setBackOldMode)
+ {
+ uint _ignore;
+ Interop.Kernel32.SetThreadErrorMode(_oldMode, out _ignore);
+ }
+#endif
+
base.Dispose(disposing);
}
}
diff --git a/src/mscorlib/src/System/IO/IOException.cs b/src/mscorlib/src/System/IO/IOException.cs
index 2628f7b652..65504de863 100644
--- a/src/mscorlib/src/System/IO/IOException.cs
+++ b/src/mscorlib/src/System/IO/IOException.cs
@@ -18,7 +18,6 @@ using System.Runtime.Serialization;
namespace System.IO
{
- [Serializable]
public class IOException : SystemException
{
// For debugging purposes, store the complete path in the IOException
@@ -68,6 +67,7 @@ namespace System.IO
protected IOException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/IO/MemoryStream.cs b/src/mscorlib/src/System/IO/MemoryStream.cs
index 3d5668d774..daf09d1274 100644
--- a/src/mscorlib/src/System/IO/MemoryStream.cs
+++ b/src/mscorlib/src/System/IO/MemoryStream.cs
@@ -34,7 +34,6 @@ namespace System.IO
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
- [Serializable]
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
diff --git a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
deleted file mode 100644
index 284cd927dc..0000000000
--- a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
+++ /dev/null
@@ -1,76 +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.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Pins a byte[], exposing it as an unmanaged memory
-** stream. Used in ResourceReader for corner cases.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.InteropServices;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-
-namespace System.IO
-{
- internal sealed unsafe class PinnedBufferMemoryStream : UnmanagedMemoryStream
- {
- private byte[] _array;
- private GCHandle _pinningHandle;
-
- // The new inheritance model requires a Critical default ctor since base (UnmanagedMemoryStream) has one
- private PinnedBufferMemoryStream() : base() { }
-
- internal PinnedBufferMemoryStream(byte[] array)
- {
- Debug.Assert(array != null, "Array can't be null");
-
- int len = array.Length;
- // Handle 0 length byte arrays specially.
- if (len == 0)
- {
- array = new byte[1];
- len = 0;
- }
-
- _array = array;
- _pinningHandle = new GCHandle(array, GCHandleType.Pinned);
- // Now the byte[] is pinned for the lifetime of this instance.
- // But I also need to get a pointer to that block of memory...
- fixed (byte* ptr = &_array[0])
- Initialize(ptr, len, len, FileAccess.Read);
- }
-
- ~PinnedBufferMemoryStream()
- {
- Dispose(false);
- }
-
- protected override void Dispose(bool disposing)
- {
- if (_isOpen)
- {
- _pinningHandle.Free();
- _isOpen = false;
- }
-#if _DEBUG
- // To help track down lifetime issues on checked builds, force
- //a full GC here.
- if (disposing)
- {
- GC.Collect();
- GC.WaitForPendingFinalizers();
- }
-#endif
- base.Dispose(disposing);
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/SearchOption.cs b/src/mscorlib/src/System/IO/SearchOption.cs
index 75909d7499..c2f7e0db6e 100644
--- a/src/mscorlib/src/System/IO/SearchOption.cs
+++ b/src/mscorlib/src/System/IO/SearchOption.cs
@@ -20,7 +20,6 @@ using System;
namespace System.IO
{
- [Serializable]
internal enum SearchOption
{
// Include only the current directory in the search operation
diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs
index 65cc4ddcb9..786dfedef9 100644
--- a/src/mscorlib/src/System/IO/Stream.cs
+++ b/src/mscorlib/src/System/IO/Stream.cs
@@ -30,7 +30,6 @@ using System.Reflection;
namespace System.IO
{
- [Serializable]
public abstract class Stream : MarshalByRefObject, IDisposable
{
public static readonly Stream Null = new NullStream();
@@ -854,7 +853,6 @@ namespace System.IO
SynchronousAsyncResult.EndWrite(asyncResult);
}
- [Serializable]
private sealed class NullStream : Stream
{
internal NullStream() { }
@@ -1093,7 +1091,6 @@ namespace System.IO
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
- [Serializable]
internal sealed class SyncStream : Stream, IDisposable
{
private Stream _stream;
diff --git a/src/mscorlib/src/System/IO/StreamReader.cs b/src/mscorlib/src/System/IO/StreamReader.cs
index dfb928c85d..1fc72bffd1 100644
--- a/src/mscorlib/src/System/IO/StreamReader.cs
+++ b/src/mscorlib/src/System/IO/StreamReader.cs
@@ -16,7 +16,6 @@ namespace System.IO
// This is designed for character input in a particular Encoding,
// whereas the Stream class is designed for byte input and output.
//
- [Serializable]
internal class StreamReader : TextReader
{
// StreamReader.Null is threadsafe.
diff --git a/src/mscorlib/src/System/IO/TextReader.cs b/src/mscorlib/src/System/IO/TextReader.cs
index 3da68591b0..2531778d6d 100644
--- a/src/mscorlib/src/System/IO/TextReader.cs
+++ b/src/mscorlib/src/System/IO/TextReader.cs
@@ -30,7 +30,6 @@ namespace System.IO {
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
- [Serializable]
internal abstract class TextReader : MarshalByRefObject, IDisposable {
public static readonly TextReader Null = new NullTextReader();
@@ -263,7 +262,6 @@ namespace System.IO {
return new SyncTextReader(reader);
}
- [Serializable]
private sealed class NullTextReader : TextReader
{
public NullTextReader(){}
@@ -280,7 +278,6 @@ namespace System.IO {
}
}
- [Serializable]
internal sealed class SyncTextReader : TextReader
{
internal TextReader _in;
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
deleted file mode 100644
index f21fe47371..0000000000
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
+++ /dev/null
@@ -1,731 +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.
-
-/*============================================================
-**
-**
-**
-**
-** Purpose: Create a stream over unmanaged memory, mostly
-** useful for memory-mapped files.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Security;
-using System.Threading;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Threading.Tasks;
-
-
-namespace System.IO
-{
- /*
- * This class is used to access a contiguous block of memory, likely outside
- * the GC heap (or pinned in place in the GC heap, but a MemoryStream may
- * make more sense in those cases). It's great if you have a pointer and
- * a length for a section of memory mapped in by someone else and you don't
- * want to copy this into the GC heap. UnmanagedMemoryStream assumes these
- * two things:
- *
- * 1) All the memory in the specified block is readable or writable,
- * depending on the values you pass to the constructor.
- * 2) The lifetime of the block of memory is at least as long as the lifetime
- * of the UnmanagedMemoryStream.
- * 3) You clean up the memory when appropriate. The UnmanagedMemoryStream
- * currently will do NOTHING to free this memory.
- * 4) All calls to Write and WriteByte may not be threadsafe currently.
- *
- * It may become necessary to add in some sort of
- * DeallocationMode enum, specifying whether we unmap a section of memory,
- * call free, run a user-provided delegate to free the memory, etc.
- * We'll suggest user write a subclass of UnmanagedMemoryStream that uses
- * a SafeHandle subclass to hold onto the memory.
- * Check for problems when using this in the negative parts of a
- * process's address space. We may need to use unsigned longs internally
- * and change the overflow detection logic.
- *
- * -----SECURITY MODEL AND SILVERLIGHT-----
- * A few key notes about exposing UMS in silverlight:
- * 1. No ctors are exposed to transparent code. This version of UMS only
- * supports byte* (not SafeBuffer). Therefore, framework code can create
- * a UMS and hand it to transparent code. Transparent code can use most
- * operations on a UMS, but not operations that directly expose a
- * pointer.
- *
- * 2. Scope of "unsafe" and non-CLS compliant operations reduced: The
- * Whidbey version of this class has CLSCompliant(false) at the class
- * level and unsafe modifiers at the method level. These were reduced to
- * only where the unsafe operation is performed -- i.e. immediately
- * around the pointer manipulation. Note that this brings UMS in line
- * with recent changes in pu/clr to support SafeBuffer.
- *
- * 3. Currently, the only caller that creates a UMS is ResourceManager,
- * which creates read-only UMSs, and therefore operations that can
- * change the length will throw because write isn't supported. A
- * conservative option would be to formalize the concept that _only_
- * read-only UMSs can be creates, and enforce this by making WriteX and
- * SetLength SecurityCritical. However, this is a violation of
- * security inheritance rules, so we must keep these safe. The
- * following notes make this acceptable for future use.
- * a. a race condition in WriteX that could have allowed a thread to
- * read from unzeroed memory was fixed
- * b. memory region cannot be expanded beyond _capacity; in other
- * words, a UMS creator is saying a writable UMS is safe to
- * write to anywhere in the memory range up to _capacity, specified
- * in the ctor. Even if the caller doesn't specify a capacity, then
- * length is used as the capacity.
- */
- public class UnmanagedMemoryStream : Stream
- {
- private const long UnmanagedMemStreamMaxLength = Int64.MaxValue;
-
- private SafeBuffer _buffer;
- private unsafe byte* _mem;
- private long _length;
- private long _capacity;
- private long _position;
- private long _offset;
- private FileAccess _access;
- internal bool _isOpen;
- [NonSerialized]
- private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
-
-
- // Needed for subclasses that need to map a file, etc.
- protected UnmanagedMemoryStream()
- {
- unsafe
- {
- _mem = null;
- }
- _isOpen = false;
- }
-
- public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length)
- {
- Initialize(buffer, offset, length, FileAccess.Read);
- }
-
- public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access)
- {
- Initialize(buffer, offset, length, access);
- }
-
- protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access)
- {
- if (buffer == null)
- {
- throw new ArgumentNullException(nameof(buffer));
- }
- if (offset < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
- }
- if (length < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
- }
- if (buffer.ByteLength < (ulong)(offset + length))
- {
- throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen);
- }
- if (access < FileAccess.Read || access > FileAccess.ReadWrite)
- {
- throw new ArgumentOutOfRangeException(nameof(access));
- }
- Contract.EndContractBlock();
-
- if (_isOpen)
- {
- throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
- }
-
- // check for wraparound
- unsafe
- {
- byte* pointer = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- buffer.AcquirePointer(ref pointer);
- if ((pointer + offset + length) < pointer)
- {
- throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
- }
- }
- finally
- {
- if (pointer != null)
- {
- buffer.ReleasePointer();
- }
- }
- }
-
- _offset = offset;
- _buffer = buffer;
- _length = length;
- _capacity = length;
- _access = access;
- _isOpen = true;
- }
-
- [CLSCompliant(false)]
- public unsafe UnmanagedMemoryStream(byte* pointer, long length)
- {
- Initialize(pointer, length, length, FileAccess.Read);
- }
-
- [CLSCompliant(false)]
- public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
- {
- Initialize(pointer, length, capacity, access);
- }
-
- [CLSCompliant(false)]
- protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
- {
- if (pointer == null)
- throw new ArgumentNullException(nameof(pointer));
- if (length < 0 || capacity < 0)
- throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
- if (length > capacity)
- throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
- Contract.EndContractBlock();
- // Check for wraparound.
- if (((byte*)((long)pointer + capacity)) < pointer)
- throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
- if (access < FileAccess.Read || access > FileAccess.ReadWrite)
- throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum);
- if (_isOpen)
- throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
-
- _mem = pointer;
- _offset = 0;
- _length = length;
- _capacity = capacity;
- _access = access;
- _isOpen = true;
- }
-
- public override bool CanRead
- {
- [Pure]
- get { return _isOpen && (_access & FileAccess.Read) != 0; }
- }
-
- public override bool CanSeek
- {
- [Pure]
- get { return _isOpen; }
- }
-
- public override bool CanWrite
- {
- [Pure]
- get { return _isOpen && (_access & FileAccess.Write) != 0; }
- }
-
- protected override void Dispose(bool disposing)
- {
- _isOpen = false;
- unsafe { _mem = null; }
-
- // Stream allocates WaitHandles for async calls. So for correctness
- // call base.Dispose(disposing) for better perf, avoiding waiting
- // for the finalizers to run on those types.
- base.Dispose(disposing);
- }
-
- public override void Flush()
- {
- if (!_isOpen) __Error.StreamIsClosed();
- }
-
- public override Task FlushAsync(CancellationToken cancellationToken)
- {
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled(cancellationToken);
-
- try
- {
- Flush();
- return Task.CompletedTask;
- }
- catch (Exception ex)
- {
- return Task.FromException(ex);
- }
- }
-
-
- public override long Length
- {
- get
- {
- if (!_isOpen) __Error.StreamIsClosed();
- return Interlocked.Read(ref _length);
- }
- }
-
- public long Capacity
- {
- get
- {
- if (!_isOpen) __Error.StreamIsClosed();
- return _capacity;
- }
- }
-
- public override long Position
- {
- get
- {
- if (!CanSeek) __Error.StreamIsClosed();
- Contract.EndContractBlock();
- return Interlocked.Read(ref _position);
- }
- set
- {
- if (value < 0)
- throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
- if (!CanSeek) __Error.StreamIsClosed();
-
-#if !BIT64
- unsafe {
- // On 32 bit machines, ensure we don't wrap around.
- if (value > (long) Int32.MaxValue || _mem + value < _mem)
- throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
- }
-#endif
- Interlocked.Exchange(ref _position, value);
- }
- }
-
- [CLSCompliant(false)]
- public unsafe byte* PositionPointer
- {
- get
- {
- if (_buffer != null)
- {
- throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
- }
-
- // Use a temp to avoid a race
- long pos = Interlocked.Read(ref _position);
- if (pos > _capacity)
- throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition);
- byte* ptr = _mem + pos;
- if (!_isOpen) __Error.StreamIsClosed();
- return ptr;
- }
- set
- {
- if (_buffer != null)
- throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
- if (!_isOpen) __Error.StreamIsClosed();
-
- // Note: subtracting pointers returns an Int64. Working around
- // to avoid hitting compiler warning CS0652 on this line.
- if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength)
- throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
- if (value < _mem)
- throw new IOException(SR.IO_SeekBeforeBegin);
-
- Interlocked.Exchange(ref _position, value - _mem);
- }
- }
-
- internal unsafe byte* Pointer
- {
- get
- {
- if (_buffer != null)
- throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
-
- return _mem;
- }
- }
-
- public override int Read([In, Out] byte[] buffer, int offset, int count)
- {
- if (buffer == null)
- throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
- if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
- if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
- if (buffer.Length - offset < count)
- throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync
-
- if (!_isOpen) __Error.StreamIsClosed();
- if (!CanRead) __Error.ReadNotSupported();
-
- // Use a local variable to avoid a race where another thread
- // changes our position after we decide we can read some bytes.
- long pos = Interlocked.Read(ref _position);
- long len = Interlocked.Read(ref _length);
- long n = len - pos;
- if (n > count)
- n = count;
- if (n <= 0)
- return 0;
-
- int nInt = (int)n; // Safe because n <= count, which is an Int32
- if (nInt < 0)
- return 0; // _position could be beyond EOF
- Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
-
- unsafe
- {
- fixed (byte* pBuffer = buffer)
- {
- if (_buffer != null)
- {
- byte* pointer = null;
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- _buffer.AcquirePointer(ref pointer);
- Buffer.Memcpy(pBuffer + offset, pointer + pos + _offset, nInt);
- }
- finally
- {
- if (pointer != null)
- {
- _buffer.ReleasePointer();
- }
- }
- }
- else
- {
- Buffer.Memcpy(pBuffer + offset, _mem + pos, nInt);
- }
- }
- }
- Interlocked.Exchange(ref _position, pos + n);
- return nInt;
- }
-
- public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
- {
- if (buffer == null)
- throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
- if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
- if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
- if (buffer.Length - offset < count)
- throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.EndContractBlock(); // contract validation copied from Read(...)
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled<Int32>(cancellationToken);
-
- try
- {
- Int32 n = Read(buffer, offset, count);
- Task<Int32> t = _lastReadTask;
- return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
- }
- catch (Exception ex)
- {
- Debug.Assert(!(ex is OperationCanceledException));
- return Task.FromException<Int32>(ex);
- }
- }
-
- public override int ReadByte()
- {
- if (!_isOpen) __Error.StreamIsClosed();
- if (!CanRead) __Error.ReadNotSupported();
-
- long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
- long len = Interlocked.Read(ref _length);
- if (pos >= len)
- return -1;
- Interlocked.Exchange(ref _position, pos + 1);
- int result;
- if (_buffer != null)
- {
- unsafe
- {
- byte* pointer = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- _buffer.AcquirePointer(ref pointer);
- result = *(pointer + pos + _offset);
- }
- finally
- {
- if (pointer != null)
- {
- _buffer.ReleasePointer();
- }
- }
- }
- }
- else
- {
- unsafe
- {
- result = _mem[pos];
- }
- }
- return result;
- }
-
- public override long Seek(long offset, SeekOrigin loc)
- {
- if (!_isOpen) __Error.StreamIsClosed();
- if (offset > UnmanagedMemStreamMaxLength)
- throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
- switch (loc)
- {
- case SeekOrigin.Begin:
- if (offset < 0)
- throw new IOException(SR.IO_SeekBeforeBegin);
- Interlocked.Exchange(ref _position, offset);
- break;
-
- case SeekOrigin.Current:
- long pos = Interlocked.Read(ref _position);
- if (offset + pos < 0)
- throw new IOException(SR.IO_SeekBeforeBegin);
- Interlocked.Exchange(ref _position, offset + pos);
- break;
-
- case SeekOrigin.End:
- long len = Interlocked.Read(ref _length);
- if (len + offset < 0)
- throw new IOException(SR.IO_SeekBeforeBegin);
- Interlocked.Exchange(ref _position, len + offset);
- break;
-
- default:
- throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
- }
-
- long finalPos = Interlocked.Read(ref _position);
- Debug.Assert(finalPos >= 0, "_position >= 0");
- return finalPos;
- }
-
- public override void SetLength(long value)
- {
- if (value < 0)
- throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
- if (_buffer != null)
- throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
- if (!_isOpen) __Error.StreamIsClosed();
- if (!CanWrite) __Error.WriteNotSupported();
-
- if (value > _capacity)
- throw new IOException(SR.IO_FixedCapacity);
-
- long pos = Interlocked.Read(ref _position);
- long len = Interlocked.Read(ref _length);
- if (value > len)
- {
- unsafe
- {
- Buffer.ZeroMemory(_mem + len, value - len);
- }
- }
- Interlocked.Exchange(ref _length, value);
- if (pos > value)
- {
- Interlocked.Exchange(ref _position, value);
- }
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- if (buffer == null)
- throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
- if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
- if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
- if (buffer.Length - offset < count)
- throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..)
-
- if (!_isOpen) __Error.StreamIsClosed();
- if (!CanWrite) __Error.WriteNotSupported();
-
- long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
- long len = Interlocked.Read(ref _length);
- long n = pos + count;
- // Check for overflow
- if (n < 0)
- throw new IOException(SR.IO_StreamTooLong);
-
- if (n > _capacity)
- {
- throw new NotSupportedException(SR.IO_FixedCapacity);
- }
-
- if (_buffer == null)
- {
- // Check to see whether we are now expanding the stream and must
- // zero any memory in the middle.
- if (pos > len)
- {
- unsafe
- {
- Buffer.ZeroMemory(_mem + len, pos - len);
- }
- }
-
- // set length after zeroing memory to avoid race condition of accessing unzeroed memory
- if (n > len)
- {
- Interlocked.Exchange(ref _length, n);
- }
- }
-
- unsafe
- {
- fixed (byte* pBuffer = buffer)
- {
- if (_buffer != null)
- {
- long bytesLeft = _capacity - pos;
- if (bytesLeft < count)
- {
- throw new ArgumentException(SR.Arg_BufferTooSmall);
- }
-
- byte* pointer = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- _buffer.AcquirePointer(ref pointer);
- Buffer.Memcpy(pointer + pos + _offset, pBuffer + offset, count);
- }
- finally
- {
- if (pointer != null)
- {
- _buffer.ReleasePointer();
- }
- }
- }
- else
- {
- Buffer.Memcpy(_mem + pos, pBuffer + offset, count);
- }
- }
- }
- Interlocked.Exchange(ref _position, n);
- return;
- }
-
- public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
- {
- if (buffer == null)
- throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
- if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
- if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
- if (buffer.Length - offset < count)
- throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.EndContractBlock(); // contract validation copied from Write(..)
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled(cancellationToken);
-
- try
- {
- Write(buffer, offset, count);
- return Task.CompletedTask;
- }
- catch (Exception ex)
- {
- Debug.Assert(!(ex is OperationCanceledException));
- return Task.FromException<Int32>(ex);
- }
- }
-
-
- public override void WriteByte(byte value)
- {
- if (!_isOpen) __Error.StreamIsClosed();
- if (!CanWrite) __Error.WriteNotSupported();
-
- long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
- long len = Interlocked.Read(ref _length);
- long n = pos + 1;
- if (pos >= len)
- {
- // Check for overflow
- if (n < 0)
- throw new IOException(SR.IO_StreamTooLong);
-
- if (n > _capacity)
- throw new NotSupportedException(SR.IO_FixedCapacity);
-
- // Check to see whether we are now expanding the stream and must
- // zero any memory in the middle.
- // don't do if created from SafeBuffer
- if (_buffer == null)
- {
- if (pos > len)
- {
- unsafe
- {
- Buffer.ZeroMemory(_mem + len, pos - len);
- }
- }
-
- // set length after zeroing memory to avoid race condition of accessing unzeroed memory
- Interlocked.Exchange(ref _length, n);
- }
- }
-
- if (_buffer != null)
- {
- unsafe
- {
- byte* pointer = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- _buffer.AcquirePointer(ref pointer);
- *(pointer + pos + _offset) = value;
- }
- finally
- {
- if (pointer != null)
- {
- _buffer.ReleasePointer();
- }
- }
- }
- }
- else
- {
- unsafe
- {
- _mem[pos] = value;
- }
- }
- Interlocked.Exchange(ref _position, n);
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
deleted file mode 100644
index 86e4707dfd..0000000000
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
+++ /dev/null
@@ -1,220 +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.
-
-/*============================================================
-**
-**
-**
-**
-** Purpose: Create a Memorystream over an UnmanagedMemoryStream
-**
-===========================================================*/
-
-using System;
-using System.Runtime.InteropServices;
-using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.IO
-{
- // Needed for backwards compatibility with V1.x usages of the
- // ResourceManager, where a MemoryStream is now returned as an
- // UnmanagedMemoryStream from ResourceReader.
- internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream
- {
- private UnmanagedMemoryStream _unmanagedStream;
-
- internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream)
- {
- _unmanagedStream = stream;
- }
-
- public override bool CanRead
- {
- [Pure]
- get { return _unmanagedStream.CanRead; }
- }
-
- public override bool CanSeek
- {
- [Pure]
- get { return _unmanagedStream.CanSeek; }
- }
-
- public override bool CanWrite
- {
- [Pure]
- get { return _unmanagedStream.CanWrite; }
- }
-
- protected override void Dispose(bool disposing)
- {
- try
- {
- if (disposing)
- _unmanagedStream.Close();
- }
- finally
- {
- base.Dispose(disposing);
- }
- }
-
- public override void Flush()
- {
- _unmanagedStream.Flush();
- }
-
- public override byte[] GetBuffer()
- {
- throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
- }
-
- public override bool TryGetBuffer(out ArraySegment<byte> buffer)
- {
- buffer = default(ArraySegment<byte>);
- return false;
- }
-
- public override int Capacity
- {
- get
- {
- return (int)_unmanagedStream.Capacity;
- }
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- set
- {
- throw new IOException(SR.IO_FixedCapacity);
- }
- }
-
- public override long Length
- {
- get
- {
- return _unmanagedStream.Length;
- }
- }
-
- public override long Position
- {
- get
- {
- return _unmanagedStream.Position;
- }
- set
- {
- _unmanagedStream.Position = value;
- }
- }
-
- public override int Read([In, Out] byte[] buffer, int offset, int count)
- {
- return _unmanagedStream.Read(buffer, offset, count);
- }
-
- public override int ReadByte()
- {
- return _unmanagedStream.ReadByte();
- }
-
- public override long Seek(long offset, SeekOrigin loc)
- {
- return _unmanagedStream.Seek(offset, loc);
- }
-
- public unsafe override byte[] ToArray()
- {
- if (!_unmanagedStream._isOpen) __Error.StreamIsClosed();
- if (!_unmanagedStream.CanRead) __Error.ReadNotSupported();
-
- byte[] buffer = new byte[_unmanagedStream.Length];
- Buffer.Memcpy(buffer, 0, _unmanagedStream.Pointer, 0, (int)_unmanagedStream.Length);
- return buffer;
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- _unmanagedStream.Write(buffer, offset, count);
- }
-
- public override void WriteByte(byte value)
- {
- _unmanagedStream.WriteByte(value);
- }
-
- // Writes this MemoryStream to another stream.
- public unsafe override void WriteTo(Stream stream)
- {
- if (stream == null)
- throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
- Contract.EndContractBlock();
-
- if (!_unmanagedStream._isOpen) __Error.StreamIsClosed();
- if (!CanRead) __Error.ReadNotSupported();
-
- byte[] buffer = ToArray();
-
- stream.Write(buffer, 0, buffer.Length);
- }
-
- public override void SetLength(Int64 value)
- {
- // This was probably meant to call _unmanagedStream.SetLength(value), but it was forgotten in V.4.0.
- // Now this results in a call to the base which touches the underlying array which is never actually used.
- // We cannot fix it due to compat now, but we should fix this at the next SxS release oportunity.
- base.SetLength(value);
- }
-
-
- public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
- {
- // The parameter checks must be in sync with the base version:
- if (destination == null)
- throw new ArgumentNullException(nameof(destination));
-
- if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
-
- if (!CanRead && !CanWrite)
- throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
-
- if (!destination.CanRead && !destination.CanWrite)
- throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed);
-
- if (!CanRead)
- throw new NotSupportedException(SR.NotSupported_UnreadableStream);
-
- if (!destination.CanWrite)
- throw new NotSupportedException(SR.NotSupported_UnwritableStream);
-
- Contract.EndContractBlock();
-
- return _unmanagedStream.CopyToAsync(destination, bufferSize, cancellationToken);
- }
-
-
- public override Task FlushAsync(CancellationToken cancellationToken)
- {
- return _unmanagedStream.FlushAsync(cancellationToken);
- }
-
-
- public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
- {
- return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken);
- }
-
-
- public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
- {
- return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken);
- }
- } // class UnmanagedMemoryStreamWrapper
-} // namespace
-
-
diff --git a/src/mscorlib/src/System/IO/__Error.cs b/src/mscorlib/src/System/IO/__Error.cs
index 70f83261ed..1af195ef77 100644
--- a/src/mscorlib/src/System/IO/__Error.cs
+++ b/src/mscorlib/src/System/IO/__Error.cs
@@ -206,11 +206,5 @@ namespace System.IO
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
-
- // From WinError.h
- internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND;
- internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND;
- internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED;
- internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER;
}
}
diff --git a/src/mscorlib/src/System/InsufficientMemoryException.cs b/src/mscorlib/src/System/InsufficientMemoryException.cs
index eb5e4d7430..8f7aa96ff7 100644
--- a/src/mscorlib/src/System/InsufficientMemoryException.cs
+++ b/src/mscorlib/src/System/InsufficientMemoryException.cs
@@ -22,7 +22,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public sealed class InsufficientMemoryException : OutOfMemoryException
{
public InsufficientMemoryException()
@@ -42,9 +41,5 @@ namespace System
{
HResult = __HResults.COR_E_INSUFFICIENTMEMORY;
}
-
- private InsufficientMemoryException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- }
}
}
diff --git a/src/mscorlib/src/System/Int16.cs b/src/mscorlib/src/System/Int16.cs
index 69f71af278..aced05df6d 100644
--- a/src/mscorlib/src/System/Int16.cs
+++ b/src/mscorlib/src/System/Int16.cs
@@ -25,7 +25,7 @@ namespace System
public struct Int16 : IComparable, IFormattable, IConvertible
, IComparable<Int16>, IEquatable<Int16>
{
- internal short m_value;
+ private short m_value; // Do not rename (binary serialization)
public const short MaxValue = (short)0x7FFF;
public const short MinValue = unchecked((short)0x8000);
diff --git a/src/mscorlib/src/System/Int32.cs b/src/mscorlib/src/System/Int32.cs
index 90b70a9554..afee0e42d7 100644
--- a/src/mscorlib/src/System/Int32.cs
+++ b/src/mscorlib/src/System/Int32.cs
@@ -25,7 +25,7 @@ namespace System
public struct Int32 : IComparable, IFormattable, IConvertible
, IComparable<Int32>, IEquatable<Int32>
{
- internal int m_value;
+ private int m_value; // Do not rename (binary serialization)
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
diff --git a/src/mscorlib/src/System/Int64.cs b/src/mscorlib/src/System/Int64.cs
index 3d64362e30..619bf7e5d7 100644
--- a/src/mscorlib/src/System/Int64.cs
+++ b/src/mscorlib/src/System/Int64.cs
@@ -24,7 +24,7 @@ namespace System
public struct Int64 : IComparable, IFormattable, IConvertible
, IComparable<Int64>, IEquatable<Int64>
{
- internal long m_value;
+ private long m_value; // Do not rename (binary serialization)
public const long MaxValue = 0x7fffffffffffffffL;
public const long MinValue = unchecked((long)0x8000000000000000L);
diff --git a/src/mscorlib/src/System/IntPtr.cs b/src/mscorlib/src/System/IntPtr.cs
index 28f1b1baa8..55c86e3795 100644
--- a/src/mscorlib/src/System/IntPtr.cs
+++ b/src/mscorlib/src/System/IntPtr.cs
@@ -25,7 +25,7 @@ namespace System
[Serializable]
public struct IntPtr : IEquatable<IntPtr>, ISerializable
{
- unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior
+ unsafe private void* _value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior
public static readonly IntPtr Zero;
@@ -33,16 +33,16 @@ namespace System
[Pure]
internal unsafe bool IsNull()
{
- return (m_value == null);
+ return (_value == null);
}
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(int value)
{
#if BIT64
- m_value = (void*)(long)value;
+ _value = (void*)(long)value;
#else // !BIT64 (32)
- m_value = (void *)value;
+ _value = (void *)value;
#endif
}
@@ -50,9 +50,9 @@ namespace System
public unsafe IntPtr(long value)
{
#if BIT64
- m_value = (void*)value;
+ _value = (void*)value;
#else // !BIT64 (32)
- m_value = (void *)checked((int)value);
+ _value = (void *)checked((int)value);
#endif
}
@@ -60,7 +60,7 @@ namespace System
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(void* value)
{
- m_value = value;
+ _value = value;
}
private unsafe IntPtr(SerializationInfo info, StreamingContext context)
@@ -72,7 +72,7 @@ namespace System
throw new ArgumentException(SR.Serialization_InvalidPtrValue);
}
- m_value = (void*)l;
+ _value = (void*)l;
}
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
@@ -83,9 +83,9 @@ namespace System
}
Contract.EndContractBlock();
#if BIT64
- info.AddValue("value", (long)(m_value));
+ info.AddValue("value", (long)(_value));
#else // !BIT64 (32)
- info.AddValue("value", (long)((int)m_value));
+ info.AddValue("value", (long)((int)_value));
#endif
}
@@ -93,23 +93,23 @@ namespace System
{
if (obj is IntPtr)
{
- return (m_value == ((IntPtr)obj).m_value);
+ return (_value == ((IntPtr)obj)._value);
}
return false;
}
unsafe bool IEquatable<IntPtr>.Equals(IntPtr other)
{
- return m_value == other.m_value;
+ return _value == other._value;
}
public unsafe override int GetHashCode()
{
#if BIT64
- long l = (long)m_value;
+ long l = (long)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else // !BIT64 (32)
- return unchecked((int)m_value);
+ return unchecked((int)_value);
#endif
}
@@ -117,10 +117,10 @@ namespace System
public unsafe int ToInt32()
{
#if BIT64
- long l = (long)m_value;
+ long l = (long)_value;
return checked((int)l);
#else // !BIT64 (32)
- return (int)m_value;
+ return (int)_value;
#endif
}
@@ -128,18 +128,18 @@ namespace System
public unsafe long ToInt64()
{
#if BIT64
- return (long)m_value;
+ return (long)_value;
#else // !BIT64 (32)
- return (long)(int)m_value;
+ return (long)(int)_value;
#endif
}
public unsafe override String ToString()
{
#if BIT64
- return ((long)m_value).ToString(CultureInfo.InvariantCulture);
+ return ((long)_value).ToString(CultureInfo.InvariantCulture);
#else // !BIT64 (32)
- return ((int)m_value).ToString(CultureInfo.InvariantCulture);
+ return ((int)_value).ToString(CultureInfo.InvariantCulture);
#endif
}
@@ -148,9 +148,9 @@ namespace System
Contract.Ensures(Contract.Result<String>() != null);
#if BIT64
- return ((long)m_value).ToString(format, CultureInfo.InvariantCulture);
+ return ((long)_value).ToString(format, CultureInfo.InvariantCulture);
#else // !BIT64 (32)
- return ((int)m_value).ToString(format, CultureInfo.InvariantCulture);
+ return ((int)_value).ToString(format, CultureInfo.InvariantCulture);
#endif
}
@@ -178,17 +178,17 @@ namespace System
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator void* (IntPtr value)
{
- return value.m_value;
+ return value._value;
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator int(IntPtr value)
{
#if BIT64
- long l = (long)value.m_value;
+ long l = (long)value._value;
return checked((int)l);
#else // !BIT64 (32)
- return (int)value.m_value;
+ return (int)value._value;
#endif
}
@@ -196,22 +196,22 @@ namespace System
public unsafe static explicit operator long(IntPtr value)
{
#if BIT64
- return (long)value.m_value;
+ return (long)value._value;
#else // !BIT64 (32)
- return (long)(int)value.m_value;
+ return (long)(int)value._value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator ==(IntPtr value1, IntPtr value2)
{
- return value1.m_value == value2.m_value;
+ return value1._value == value2._value;
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator !=(IntPtr value1, IntPtr value2)
{
- return value1.m_value != value2.m_value;
+ return value1._value != value2._value;
}
[System.Runtime.Versioning.NonVersionable]
@@ -265,7 +265,7 @@ namespace System
[System.Runtime.Versioning.NonVersionable]
public unsafe void* ToPointer()
{
- return m_value;
+ return _value;
}
}
}
diff --git a/src/mscorlib/src/System/MissingFieldException.cs b/src/mscorlib/src/System/MissingFieldException.cs
index 5668f9e9b3..668d5f2a31 100644
--- a/src/mscorlib/src/System/MissingFieldException.cs
+++ b/src/mscorlib/src/System/MissingFieldException.cs
@@ -11,14 +11,12 @@
using System;
-using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Globalization;
namespace System
{
- [Serializable]
public class MissingFieldException : MissingMemberException, ISerializable
{
public MissingFieldException()
@@ -41,6 +39,7 @@ namespace System
protected MissingFieldException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
public override String Message
diff --git a/src/mscorlib/src/System/MissingMemberException.cs b/src/mscorlib/src/System/MissingMemberException.cs
index 51150e113c..1fb0c55e40 100644
--- a/src/mscorlib/src/System/MissingMemberException.cs
+++ b/src/mscorlib/src/System/MissingMemberException.cs
@@ -13,7 +13,6 @@
using System;
-using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Globalization;
@@ -22,7 +21,6 @@ using System.Diagnostics.Contracts;
namespace System
{
- [Serializable]
public class MissingMemberException : MemberAccessException, ISerializable
{
public MissingMemberException()
@@ -45,9 +43,7 @@ namespace System
protected MissingMemberException(SerializationInfo info, StreamingContext context) : base(info, context)
{
- ClassName = (String)info.GetString("MMClassName");
- MemberName = (String)info.GetString("MMMemberName");
- Signature = (byte[])info.GetValue("MMSignature", typeof(byte[]));
+ throw new PlatformNotSupportedException();
}
public override String Message
@@ -78,15 +74,7 @@ namespace System
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
base.GetObjectData(info, context);
- info.AddValue("MMClassName", ClassName, typeof(String));
- info.AddValue("MMMemberName", MemberName, typeof(String));
- info.AddValue("MMSignature", Signature, typeof(byte[]));
}
diff --git a/src/mscorlib/src/System/MulticastDelegate.cs b/src/mscorlib/src/System/MulticastDelegate.cs
index 440c9a60bc..988bf2bb60 100644
--- a/src/mscorlib/src/System/MulticastDelegate.cs
+++ b/src/mscorlib/src/System/MulticastDelegate.cs
@@ -13,7 +13,6 @@ using System.Reflection.Emit;
namespace System
{
- [Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MulticastDelegate : Delegate
{
@@ -50,49 +49,7 @@ namespace System
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
- int targetIndex = 0;
- Object[] invocationList = _invocationList as Object[];
- if (invocationList == null)
- {
- MethodInfo method = Method;
- // A MethodInfo object can be a RuntimeMethodInfo, a RefEmit method (MethodBuilder, etc), or a DynamicMethod
- // One can only create delegates on RuntimeMethodInfo and DynamicMethod.
- // If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, throw
- if (!(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr())
- throw new SerializationException(SR.Serialization_InvalidDelegateType);
-
- // We can't deal with secure delegates either.
- if (!InvocationListLogicallyNull() && !_invocationCount.IsNull() && !_methodPtrAux.IsNull())
- throw new SerializationException(SR.Serialization_InvalidDelegateType);
-
- DelegateSerializationHolder.GetDelegateSerializationInfo(info, this.GetType(), Target, method, targetIndex);
- }
- else
- {
- DelegateSerializationHolder.DelegateEntry nextDe = null;
- int invocationCount = (int)_invocationCount;
- for (int i = invocationCount; --i >= 0;)
- {
- MulticastDelegate d = (MulticastDelegate)invocationList[i];
- MethodInfo method = d.Method;
- // If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, skip
- if (!(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr())
- continue;
-
- // We can't deal with secure delegates either.
- if (!d.InvocationListLogicallyNull() && !d._invocationCount.IsNull() && !d._methodPtrAux.IsNull())
- continue;
-
- DelegateSerializationHolder.DelegateEntry de = DelegateSerializationHolder.GetDelegateSerializationInfo(info, d.GetType(), d.Target, method, targetIndex++);
- if (nextDe != null)
- nextDe.Entry = de;
-
- nextDe = de;
- }
- // if nothing was serialized it is a delegate over a DynamicMethod, so just throw
- if (nextDe == null)
- throw new SerializationException(SR.Serialization_InvalidDelegateType);
- }
+ throw new SerializationException(SR.Serialization_DelegatesNotSupported);
}
// equals returns true IIF the delegate is not null and has the
diff --git a/src/mscorlib/src/System/Object.cs b/src/mscorlib/src/System/Object.cs
index 3c304422ac..a476557911 100644
--- a/src/mscorlib/src/System/Object.cs
+++ b/src/mscorlib/src/System/Object.cs
@@ -201,7 +201,6 @@ namespace System
// The name "__Canon" will never been seen by users but it will appear a lot in debugger stack traces
// involving generics so it is kept deliberately short as to avoid being a nuisance.
- [Serializable]
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
internal class __Canon
diff --git a/src/mscorlib/src/System/OleAutBinder.cs b/src/mscorlib/src/System/OleAutBinder.cs
index 1db61bb30e..3a9f03c5f0 100644
--- a/src/mscorlib/src/System/OleAutBinder.cs
+++ b/src/mscorlib/src/System/OleAutBinder.cs
@@ -15,7 +15,6 @@ namespace System
using CultureInfo = System.Globalization.CultureInfo;
// Made serializable in anticipation of this class eventually having state.
- [Serializable]
internal class OleAutBinder : DefaultBinder
{
// ChangeType
diff --git a/src/mscorlib/src/System/OperatingSystem.cs b/src/mscorlib/src/System/OperatingSystem.cs
deleted file mode 100644
index 5eb1253fa5..0000000000
--- a/src/mscorlib/src/System/OperatingSystem.cs
+++ /dev/null
@@ -1,154 +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.
-
-/*============================================================
-**
-**
-**
-** Purpose:
-**
-**
-===========================================================*/
-
-using System.Runtime.Serialization;
-using System.Globalization;
-using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
-
-namespace System
-{
- [Serializable]
- internal sealed class OperatingSystem : ICloneable, ISerializable
- {
- private Version _version;
- private PlatformID _platform;
- private string _servicePack;
- private string _versionString;
-
- private OperatingSystem()
- {
- }
-
- internal OperatingSystem(PlatformID platform, Version version, string servicePack)
- {
- if (platform < PlatformID.Win32S || platform > PlatformID.MacOSX)
- {
- throw new ArgumentException(
- SR.Format(SR.Arg_EnumIllegalVal, (int)platform),
- nameof(platform));
- }
-
- if ((Object)version == null)
- throw new ArgumentNullException(nameof(version));
- Contract.EndContractBlock();
-
- _platform = platform;
- _version = (Version)version.Clone();
- _servicePack = servicePack;
- }
-
- private OperatingSystem(SerializationInfo info, StreamingContext context)
- {
- SerializationInfoEnumerator enumerator = info.GetEnumerator();
- while (enumerator.MoveNext())
- {
- switch (enumerator.Name)
- {
- case "_version":
- _version = (Version)info.GetValue("_version", typeof(Version));
- break;
- case "_platform":
- _platform = (PlatformID)info.GetValue("_platform", typeof(PlatformID));
- break;
- case "_servicePack":
- _servicePack = info.GetString("_servicePack");
- break;
- }
- }
-
- if (_version == null)
- {
- throw new SerializationException(SR.Format(SR.Serialization_MissField, "_version"));
- }
- }
-
- public void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
-
- info.AddValue("_version", _version);
- info.AddValue("_platform", _platform);
- info.AddValue("_servicePack", _servicePack);
- }
-
- public Version Version
- {
- get { return _version; }
- }
-
- public Object Clone()
- {
- return new OperatingSystem(_platform,
- _version, _servicePack);
- }
-
- public override String ToString()
- {
- return VersionString;
- }
-
- public String VersionString
- {
- get
- {
- if (_versionString != null)
- {
- return _versionString;
- }
-
- String os;
- switch (_platform)
- {
- case PlatformID.Win32NT:
- os = "Microsoft Windows NT ";
- break;
- case PlatformID.Win32Windows:
- if ((_version.Major > 4) ||
- ((_version.Major == 4) && (_version.Minor > 0)))
- os = "Microsoft Windows 98 ";
- else
- os = "Microsoft Windows 95 ";
- break;
- case PlatformID.Win32S:
- os = "Microsoft Win32S ";
- break;
- case PlatformID.WinCE:
- os = "Microsoft Windows CE ";
- break;
- case PlatformID.MacOSX:
- os = "Mac OS X ";
- break;
- default:
- os = "<unknown> ";
- break;
- }
-
- if (String.IsNullOrEmpty(_servicePack))
- {
- _versionString = os + _version.ToString();
- }
- else
- {
- _versionString = os + _version.ToString(3) + " " + _servicePack;
- }
-
- return _versionString;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/OperationCanceledException.cs b/src/mscorlib/src/System/OperationCanceledException.cs
deleted file mode 100644
index 826561776f..0000000000
--- a/src/mscorlib/src/System/OperationCanceledException.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.
-
-/*============================================================
-**
-**
-**
-** Purpose: Exception for cancelled IO requests.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-using System.Threading;
-
-namespace System
-{
- [Serializable]
- public class OperationCanceledException : SystemException
- {
- [NonSerialized]
- private CancellationToken _cancellationToken;
-
- public CancellationToken CancellationToken
- {
- get { return _cancellationToken; }
- private set { _cancellationToken = value; }
- }
-
- public OperationCanceledException()
- : base(SR.OperationCanceled)
- {
- HResult = __HResults.COR_E_OPERATIONCANCELED;
- }
-
- public OperationCanceledException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_OPERATIONCANCELED;
- }
-
- public OperationCanceledException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_OPERATIONCANCELED;
- }
-
-
- public OperationCanceledException(CancellationToken token)
- : this()
- {
- CancellationToken = token;
- }
-
- public OperationCanceledException(String message, CancellationToken token)
- : this(message)
- {
- CancellationToken = token;
- }
-
- public OperationCanceledException(String message, Exception innerException, CancellationToken token)
- : this(message, innerException)
- {
- CancellationToken = token;
- }
-
- protected OperationCanceledException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/OutOfMemoryException.cs b/src/mscorlib/src/System/OutOfMemoryException.cs
index 154d0f92e2..3bec542077 100644
--- a/src/mscorlib/src/System/OutOfMemoryException.cs
+++ b/src/mscorlib/src/System/OutOfMemoryException.cs
@@ -17,7 +17,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class OutOfMemoryException : SystemException
{
public OutOfMemoryException()
@@ -40,6 +39,7 @@ namespace System
protected OutOfMemoryException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/PlatformID.cs b/src/mscorlib/src/System/PlatformID.cs
deleted file mode 100644
index dfab2175ab..0000000000
--- a/src/mscorlib/src/System/PlatformID.cs
+++ /dev/null
@@ -1,27 +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.
-
-/*============================================================
-**
-**
-**
-** Purpose: Defines IDs for supported platforms
-**
-**
-===========================================================*/
-
-namespace System
-{
- [Serializable]
- internal enum PlatformID
- {
- Win32S = 0,
- Win32Windows = 1,
- Win32NT = 2,
- WinCE = 3,
- Unix = 4,
- Xbox = 5,
- MacOSX = 6
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs b/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs
index 708f79b64f..9d34b48177 100644
--- a/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs
+++ b/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs
@@ -15,34 +15,78 @@ namespace System.Reflection
{
public abstract partial class Assembly : ICustomAttributeProvider, ISerializable
{
+ private static volatile bool s_LoadFromResolveHandlerSetup = false;
+ private static object s_syncRootLoadFrom = new object();
+ private static List<string> s_LoadFromAssemblyList = new List<string>();
+ private static object s_syncLoadFromAssemblyList = new object();
+
+ private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs args)
+ {
+ Assembly requestingAssembly = args.RequestingAssembly;
+
+ // Requesting assembly for LoadFrom is always loaded in defaultContext - proceed only if that
+ // is the case.
+ if (AssemblyLoadContext.Default != AssemblyLoadContext.GetLoadContext(requestingAssembly))
+ return null;
+
+ // Get the path where requesting assembly lives and check if it is in the list
+ // of assemblies for which LoadFrom was invoked.
+ bool fRequestorLoadedViaLoadFrom = false;
+ string requestorPath = Path.GetFullPath(requestingAssembly.Location);
+ if (string.IsNullOrEmpty(requestorPath))
+ return null;
+
+ lock(s_syncLoadFromAssemblyList)
+ {
+ fRequestorLoadedViaLoadFrom = s_LoadFromAssemblyList.Contains(requestorPath);
+ }
+
+ // If the requestor assembly was not loaded using LoadFrom, exit.
+ if (!fRequestorLoadedViaLoadFrom)
+ return null;
+
+ // Requestor assembly was loaded using loadFrom, so look for its dependencies
+ // in the same folder as it.
+ // Form the name of the assembly using the path of the assembly that requested its load.
+ AssemblyName requestedAssemblyName = new AssemblyName(args.Name);
+ string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath), requestedAssemblyName.Name+".dll");
+
+ // Load the dependency via LoadFrom so that it goes through the same path of being in the LoadFrom list.
+ return Assembly.LoadFrom(requestedAssemblyPath);
+ }
+
public static Assembly LoadFrom(String assemblyFile)
{
if (assemblyFile == null)
throw new ArgumentNullException(nameof(assemblyFile));
+
string fullPath = Path.GetFullPath(assemblyFile);
- return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
- }
- // Evidence is protected in Assembly.Load()
- [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- internal static Assembly LoadFrom(String assemblyFile,
- Evidence securityEvidence)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
+ if (!s_LoadFromResolveHandlerSetup)
+ {
+ lock (s_syncRootLoadFrom)
+ {
+ if (!s_LoadFromResolveHandlerSetup)
+ {
+ AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromResolveHandler);
+ s_LoadFromResolveHandlerSetup = true;
+ }
+ }
+ }
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ // Add the path to the LoadFrom path list which we will consult
+ // before handling the resolves in our handler.
+ lock(s_syncLoadFromAssemblyList)
+ {
+ if (!s_LoadFromAssemblyList.Contains(fullPath))
+ {
+ s_LoadFromAssemblyList.Add(fullPath);
+ }
+ }
- return RuntimeAssembly.InternalLoadFrom(
- assemblyFile,
- securityEvidence,
- null, // hashValue
- AssemblyHashAlgorithm.None,
- false,// forIntrospection);
- ref stackMark);
+ return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
}
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly LoadFrom(String assemblyFile,
byte[] hashValue,
AssemblyHashAlgorithm hashAlgorithm)
diff --git a/src/mscorlib/src/System/Reflection/AssemblyName.cs b/src/mscorlib/src/System/Reflection/AssemblyName.cs
index 80fdf5d162..6bfc5b7496 100644
--- a/src/mscorlib/src/System/Reflection/AssemblyName.cs
+++ b/src/mscorlib/src/System/Reflection/AssemblyName.cs
@@ -27,7 +27,6 @@ namespace System.Reflection
using System.Diagnostics.Contracts;
using System.Text;
- [Serializable]
public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback
{
//
@@ -279,7 +278,11 @@ namespace System.Reflection
{
get
{
- return nToString();
+ if (this.Name == null)
+ return string.Empty;
+ // Do not call GetPublicKeyToken() here - that latches the result into AssemblyName which isn't a side effect we want.
+ byte[] pkt = _PublicKeyToken ?? nGetPublicKeyToken();
+ return AssemblyNameFormatter.ComputeDisplayName(Name, Version, CultureName, pkt, Flags, ContentType);
}
}
@@ -295,68 +298,12 @@ namespace System.Reflection
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- //Allocate the serialization info and serialize our static data.
- info.AddValue("_Name", _Name);
- info.AddValue("_PublicKey", _PublicKey, typeof(byte[]));
- info.AddValue("_PublicKeyToken", _PublicKeyToken, typeof(byte[]));
-#if FEATURE_USE_LCID
- info.AddValue("_CultureInfo", (_CultureInfo == null) ? -1 : _CultureInfo.LCID);
-#endif
- info.AddValue("_CodeBase", _CodeBase);
- info.AddValue("_Version", _Version);
- info.AddValue("_HashAlgorithm", _HashAlgorithm, typeof(AssemblyHashAlgorithm));
- info.AddValue("_HashAlgorithmForControl", _HashAlgorithmForControl, typeof(AssemblyHashAlgorithm));
- info.AddValue("_StrongNameKeyPair", _StrongNameKeyPair, typeof(StrongNameKeyPair));
- info.AddValue("_VersionCompatibility", _VersionCompatibility, typeof(AssemblyVersionCompatibility));
- info.AddValue("_Flags", _Flags, typeof(AssemblyNameFlags));
- info.AddValue("_HashForControl", _HashForControl, typeof(byte[]));
+ throw new PlatformNotSupportedException();
}
public void OnDeserialization(Object sender)
{
- // Deserialization has already been performed
- if (m_siInfo == null)
- return;
-
- _Name = m_siInfo.GetString("_Name");
- _PublicKey = (byte[])m_siInfo.GetValue("_PublicKey", typeof(byte[]));
- _PublicKeyToken = (byte[])m_siInfo.GetValue("_PublicKeyToken", typeof(byte[]));
-#if FEATURE_USE_LCID
- int lcid = (int)m_siInfo.GetInt32("_CultureInfo");
- if (lcid != -1)
- _CultureInfo = new CultureInfo(lcid);
-#endif
-
- _CodeBase = m_siInfo.GetString("_CodeBase");
- _Version = (Version)m_siInfo.GetValue("_Version", typeof(Version));
- _HashAlgorithm = (AssemblyHashAlgorithm)m_siInfo.GetValue("_HashAlgorithm", typeof(AssemblyHashAlgorithm));
- _StrongNameKeyPair = (StrongNameKeyPair)m_siInfo.GetValue("_StrongNameKeyPair", typeof(StrongNameKeyPair));
- _VersionCompatibility = (AssemblyVersionCompatibility)m_siInfo.GetValue("_VersionCompatibility", typeof(AssemblyVersionCompatibility));
- _Flags = (AssemblyNameFlags)m_siInfo.GetValue("_Flags", typeof(AssemblyNameFlags));
-
- try
- {
- _HashAlgorithmForControl = (AssemblyHashAlgorithm)m_siInfo.GetValue("_HashAlgorithmForControl", typeof(AssemblyHashAlgorithm));
- _HashForControl = (byte[])m_siInfo.GetValue("_HashForControl", typeof(byte[]));
- }
- catch (SerializationException)
- { // RTM did not have these defined
- _HashAlgorithmForControl = AssemblyHashAlgorithm.None;
- _HashForControl = null;
- }
-
- m_siInfo = null;
- }
-
- // Constructs a new AssemblyName during deserialization.
- internal AssemblyName(SerializationInfo info, StreamingContext context)
- {
- //The graph is not valid until OnDeserialization() has been called.
- m_siInfo = info;
+ throw new PlatformNotSupportedException();
}
public AssemblyName(String assemblyName)
diff --git a/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
index 96eb45f3e4..1cf00f17d8 100644
--- a/src/mscorlib/src/System/Reflection/CustomAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
@@ -20,7 +20,6 @@ using System.Diagnostics.Contracts;
namespace System.Reflection
{
- [Serializable]
public class CustomAttributeData
{
#region Public Static Members
@@ -570,7 +569,6 @@ namespace System.Reflection
#endregion
}
- [Serializable]
public struct CustomAttributeNamedArgument
{
#region Public Static Members
@@ -659,7 +657,6 @@ namespace System.Reflection
}
- [Serializable]
public struct CustomAttributeTypedArgument
{
#region Public Static Members
@@ -958,14 +955,12 @@ namespace System.Reflection
#endregion
}
- [Serializable]
internal struct CustomAttributeRecord
{
internal ConstArray blob;
internal MetadataToken tkCtor;
}
- [Serializable]
internal enum CustomAttributeEncoding : int
{
Undefined = 0,
@@ -990,7 +985,6 @@ namespace System.Reflection
Enum = 0x55
}
- [Serializable]
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeEncodedArgument
{
@@ -1045,7 +1039,6 @@ namespace System.Reflection
#endregion
}
- [Serializable]
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeNamedParameter
{
@@ -1077,7 +1070,6 @@ namespace System.Reflection
#endregion
}
- [Serializable]
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeCtorParameter
{
@@ -1099,7 +1091,6 @@ namespace System.Reflection
#endregion
}
- [Serializable]
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeType
{
@@ -2040,7 +2031,7 @@ namespace System.Reflection
count = 0;
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType))
+ if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
return Array.Empty<Attribute>();
List<Attribute> pcas = new List<Attribute>();
@@ -2078,7 +2069,7 @@ namespace System.Reflection
internal static bool IsDefined(RuntimeType type, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType))
+ if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
return false;
if (all || caType == (RuntimeType)typeof(SerializableAttribute))
@@ -2107,7 +2098,7 @@ namespace System.Reflection
count = 0;
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType))
+ if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
return Array.Empty<Attribute>();
List<Attribute> pcas = new List<Attribute>();
@@ -2140,7 +2131,7 @@ namespace System.Reflection
internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null)
+ if (!all && !s_pca.ContainsKey(caType))
return false;
if (all || caType == (RuntimeType)typeof(DllImportAttribute))
@@ -2170,7 +2161,7 @@ namespace System.Reflection
count = 0;
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null)
+ if (!all && !s_pca.ContainsKey(caType))
return null;
Attribute[] pcas = new Attribute[s_pcasCount];
@@ -2201,7 +2192,7 @@ namespace System.Reflection
internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null)
+ if (!all && !s_pca.ContainsKey(caType))
return false;
@@ -2231,7 +2222,7 @@ namespace System.Reflection
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType))
+ if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
return Array.Empty<Attribute>();
List<Attribute> pcas = new List<Attribute>();
@@ -2283,7 +2274,7 @@ namespace System.Reflection
count = 0;
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null)
+ if (!all && !s_pca.ContainsKey(caType))
return null;
Attribute[] pcas = new Attribute[s_pcasCount];
@@ -2309,7 +2300,7 @@ namespace System.Reflection
internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null)
+ if (!all && !s_pca.ContainsKey(caType))
return false;
if (all || caType == (RuntimeType)typeof(MarshalAsAttribute))
@@ -2334,7 +2325,7 @@ namespace System.Reflection
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType))
+ if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
return Array.Empty<Attribute>();
List<Attribute> pcas = new List<Attribute>();
@@ -2357,7 +2348,7 @@ namespace System.Reflection
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && s_pca.GetValueOrDefault(caType) == null)
+ if (!all && !s_pca.ContainsKey(caType))
return false;
if (all || IsSecurityAttribute(caType))
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
index ead2fafcef..b096960406 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
@@ -9,7 +9,6 @@ using System;
namespace System.Reflection.Emit
{
- [Serializable]
[Flags]
public enum AssemblyBuilderAccess
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
index 55aa5c5a8f..a36882b036 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
@@ -242,6 +242,8 @@ namespace System.Reflection.Emit
return m_typeBuilder.Attributes;
}
+ public override bool IsTypeDefinition => true;
+
public override bool IsSZArray => false;
protected override bool IsArrayImpl()
diff --git a/src/mscorlib/src/System/Reflection/Emit/EventToken.cs b/src/mscorlib/src/System/Reflection/Emit/EventToken.cs
index 18ec630b5f..e44dc3d0ce 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EventToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EventToken.cs
@@ -18,7 +18,6 @@ using System.Reflection;
namespace System.Reflection.Emit
{
- [Serializable]
public struct EventToken
{
public static readonly EventToken Empty = new EventToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs b/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs
index 6c5d778d8f..c7450ca301 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs
@@ -22,7 +22,6 @@ namespace System.Reflection.Emit
// by the Metadata to represent the field. FieldTokens are generated by
// Module.GetFieldToken(). There are no meaningful accessors on this class,
// but it can be passed to ILGenerator which understands it's internals.
- [Serializable]
public struct FieldToken
{
public static readonly FieldToken Empty = new FieldToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
index fb8564652f..531d229a5c 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
@@ -16,7 +16,6 @@ using System;
namespace System.Reflection.Emit
{
- [Serializable]
public enum FlowControl
{
Branch = 0,
diff --git a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
index dd5ffa92a9..75e4acc903 100644
--- a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
@@ -154,6 +154,8 @@ namespace System.Reflection.Emit
protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; }
+ public override bool IsTypeDefinition => false;
+
public override bool IsSZArray => false;
protected override bool IsArrayImpl() { return false; }
diff --git a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
index 4021410a33..fa31d66f6c 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
@@ -1605,7 +1605,6 @@ namespace System.Reflection.Emit
* takes place.
*
***************************/
- [Serializable]
internal enum ScopeAction
{
Open = 0x0,
diff --git a/src/mscorlib/src/System/Reflection/Emit/Label.cs b/src/mscorlib/src/System/Reflection/Emit/Label.cs
index f6315a67d2..d67c0e6a19 100644
--- a/src/mscorlib/src/System/Reflection/Emit/Label.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/Label.cs
@@ -26,7 +26,6 @@ namespace System.Reflection.Emit
// is passed to the MethodWriter.
// Labels are created by using ILGenerator.CreateLabel and their position is set
// by using ILGenerator.MarkLabel.
- [Serializable]
public struct Label
{
internal int m_label;
diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs b/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs
index 0905ac922a..9698b07333 100644
--- a/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs
@@ -18,7 +18,6 @@ using System.Reflection;
namespace System.Reflection.Emit
{
- [Serializable]
public struct MethodToken
{
public static readonly MethodToken Empty = new MethodToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
index 4f1b8eb713..4a9b774d15 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
@@ -19,7 +19,6 @@ namespace System.Reflection.Emit
// This is a package private class. This class hold all of the managed
// data member for ModuleBuilder. Note that what ever data members added to
// this class cannot be accessed from the EE.
- [Serializable]
internal class ModuleBuilderData
{
internal ModuleBuilderData(ModuleBuilder module, String strModuleName, String strFileName, int tkFile)
diff --git a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
index 2363d607fc..db7fa2f209 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
@@ -17,7 +17,6 @@ using System;
namespace System.Reflection.Emit
{
- [Serializable]
public enum OpCodeType
{
[Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
diff --git a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
index 033539b999..db113b1725 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
@@ -17,7 +17,6 @@ using System;
namespace System.Reflection.Emit
{
- [Serializable]
public enum OperandType
{
InlineBrTarget = 0,
diff --git a/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs b/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs
index f9246fce6d..f6606c477a 100644
--- a/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs
@@ -8,7 +8,6 @@ using System;
namespace System.Reflection.Emit
{
// This Enum matchs the CorFieldAttr defined in CorHdr.h
- [Serializable]
public enum PEFileKinds
{
Dll = 0x0001,
diff --git a/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs b/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs
index 42f85af464..067bc2d010 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs
@@ -20,7 +20,6 @@ namespace System.Reflection.Emit
{
// The ParameterToken class is an opaque representation of the Token returned
// by the Metadata to represent the parameter.
- [Serializable]
public struct ParameterToken
{
public static readonly ParameterToken Empty = new ParameterToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs b/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs
index b450b198d2..02f34881f4 100644
--- a/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs
@@ -18,7 +18,6 @@ using System.Reflection;
namespace System.Reflection.Emit
{
- [Serializable]
public struct PropertyToken
{
public static readonly PropertyToken Empty = new PropertyToken();
diff --git a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs
index afcf2ddf0a..b9054b709e 100644
--- a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs
@@ -17,7 +17,6 @@ using System;
namespace System.Reflection.Emit
{
- [Serializable]
public enum StackBehaviour
{
Pop0 = 0,
diff --git a/src/mscorlib/src/System/Reflection/Emit/StringToken.cs b/src/mscorlib/src/System/Reflection/Emit/StringToken.cs
index 1d90816fc6..cc5b734ae8 100644
--- a/src/mscorlib/src/System/Reflection/Emit/StringToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/StringToken.cs
@@ -18,7 +18,6 @@ using System.Reflection;
namespace System.Reflection.Emit
{
- [Serializable]
public struct StringToken
{
internal int m_string;
diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
index 16848b43dd..ca2f7d9d6e 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
@@ -12,7 +12,6 @@ namespace System.Reflection.Emit
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
- [Serializable]
internal enum TypeKind
{
IsArray = 1,
@@ -271,6 +270,9 @@ namespace System.Reflection.Emit
#endregion
#region Type Overrides
+
+ public override bool IsTypeDefinition => false;
+
public override bool IsSZArray => m_cRank <= 1 && m_isSzArray;
public override Type MakePointerType()
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
index a98af2bdcf..2f550a4e40 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
@@ -20,7 +20,6 @@ namespace System.Reflection.Emit
using System.Diagnostics.Contracts;
- [Serializable]
public enum PackingSize
{
Unspecified = 0,
@@ -1109,6 +1108,8 @@ namespace System.Reflection.Emit
return m_iAttr;
}
+ public override bool IsTypeDefinition => true;
+
public override bool IsSZArray => false;
protected override bool IsArrayImpl()
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
index 6d46362f91..64a38b0995 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
@@ -189,6 +189,7 @@ namespace System.Reflection.Emit
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; }
+ public override bool IsTypeDefinition => false;
public override bool IsSZArray => false;
protected override bool IsArrayImpl() { return false; }
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs b/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs
index 4f0c1b3dac..15a0816a50 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs
@@ -19,7 +19,6 @@ using System.Threading;
namespace System.Reflection.Emit
{
- [Serializable]
public struct TypeToken
{
public static readonly TypeToken Empty = new TypeToken();
diff --git a/src/mscorlib/src/System/Reflection/MdFieldInfo.cs b/src/mscorlib/src/System/Reflection/MdFieldInfo.cs
index 41ee4d9297..9645b7fef2 100644
--- a/src/mscorlib/src/System/Reflection/MdFieldInfo.cs
+++ b/src/mscorlib/src/System/Reflection/MdFieldInfo.cs
@@ -9,7 +9,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- [Serializable]
internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable
{
#region Private Data Members
diff --git a/src/mscorlib/src/System/Reflection/MdImport.cs b/src/mscorlib/src/System/Reflection/MdImport.cs
index a224a50513..9230ffa9ef 100644
--- a/src/mscorlib/src/System/Reflection/MdImport.cs
+++ b/src/mscorlib/src/System/Reflection/MdImport.cs
@@ -20,7 +20,6 @@ using System.Diagnostics.Contracts;
namespace System.Reflection
{
- [Serializable]
internal enum CorElementType : byte
{
End = 0x00,
@@ -61,7 +60,6 @@ namespace System.Reflection
Pinned = 0x45,
}
- [Serializable]
[Flags()]
internal enum MdSigCallingConvention : byte
{
@@ -85,7 +83,6 @@ namespace System.Reflection
}
- [Serializable]
[Flags()]
internal enum PInvokeAttributes
{
@@ -122,7 +119,6 @@ namespace System.Reflection
}
- [Serializable]
[Flags()]
internal enum MethodSemanticsAttributes
{
@@ -135,7 +131,6 @@ namespace System.Reflection
}
- [Serializable]
internal enum MetadataTokenType
{
Module = 0x00000000,
@@ -166,7 +161,6 @@ namespace System.Reflection
Invalid = 0x7FFFFFFF,
}
- [Serializable]
internal struct ConstArray
{
public IntPtr Signature { get { return m_constArray; } }
@@ -191,7 +185,6 @@ namespace System.Reflection
internal IntPtr m_constArray;
}
- [Serializable]
internal struct MetadataToken
{
#region Implicit Cast Operators
diff --git a/src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs b/src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs
deleted file mode 100644
index d25c746a85..0000000000
--- a/src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.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;
-using System.Text;
-using System.Reflection;
-using System.Diagnostics;
-using System.Collections.Generic;
-
-namespace System
-{
- internal static class MemberSerializationStringGenerator
- {
- //
- // Generate the "Signature2" binary serialization string for PropertyInfos
- //
- // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing
- // metadata prevents generating the string, this method throws a MissingMetadata exception.
- //
- public static string SerializationToString(this PropertyInfo property) => ((RuntimePropertyInfo)property).SerializationToString();
-
- //
- // Generate the "Signature2" binary serialization string for ConstructorInfos
- //
- // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing
- // metadata prevents generating the string, this method throws a MissingMetadata exception.
- //
- public static string SerializationToString(this ConstructorInfo constructor) => ((RuntimeConstructorInfo)constructor).SerializationToString();
-
- //
- // Generate the "Signature2" binary serialization string for MethodInfos
- //
- // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing
- // metadata prevents generating the string, this method throws a MissingMetadata exception.
- //
- public static string SerializationToString(this MethodInfo method) => ((RuntimeMethodInfo)method).SerializationToString();
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/RtFieldInfo.cs b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs
index 20d6e6392f..ddfc56b2aa 100644
--- a/src/mscorlib/src/System/Reflection/RtFieldInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs
@@ -11,7 +11,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- [Serializable]
internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo
{
#region FCalls
diff --git a/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs
index 4632525453..6737190c1c 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs
@@ -18,7 +18,6 @@ using System.Diagnostics.Contracts;
namespace System.Reflection
{
- [Serializable]
internal class RuntimeAssembly : Assembly
{
#if FEATURE_APPX
@@ -261,15 +260,7 @@ namespace System.Reflection
// ISerializable implementation
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
-
- Contract.EndContractBlock();
-
- UnitySerializationHolder.GetUnitySerializationInfo(info,
- UnitySerializationHolder.AssemblyUnity,
- this.FullName,
- this);
+ throw new PlatformNotSupportedException();
}
public override Module ManifestModule
@@ -320,26 +311,6 @@ namespace System.Reflection
return CustomAttributeData.GetCustomAttributesInternal(this);
}
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- internal static RuntimeAssembly InternalLoadFrom(String assemblyFile,
- Evidence securityEvidence,
- byte[] hashValue,
- AssemblyHashAlgorithm hashAlgorithm,
- bool forIntrospection,
- ref StackCrawlMark stackMark)
- {
- if (assemblyFile == null)
- throw new ArgumentNullException(nameof(assemblyFile));
-
- Contract.EndContractBlock();
-
- AssemblyName an = new AssemblyName();
- an.CodeBase = assemblyFile;
- an.SetHashControl(hashValue, hashAlgorithm);
- // The stack mark is used for MDA filtering
- return InternalLoadAssemblyName(an, securityEvidence, null, ref stackMark, true /*thrownOnFileNotFound*/, forIntrospection);
- }
-
// Wrapper function to wrap the typical use of InternalLoad.
internal static RuntimeAssembly InternalLoad(String assemblyString,
Evidence assemblySecurity,
diff --git a/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs
index 8c3b1fce98..e0fb3ec87d 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs
@@ -11,7 +11,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- [Serializable]
internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo
{
#region Private Data Members
@@ -465,10 +464,7 @@ namespace System.Reflection
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
- MemberInfoSerializationHolder.GetSerializationInfo(info, this);
+ throw new PlatformNotSupportedException();
}
internal string SerializationToString()
diff --git a/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs
index 930e1820bd..9e86867b6d 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs
@@ -10,7 +10,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- [Serializable]
internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable
{
#region Private Data Members
@@ -159,11 +158,7 @@ namespace System.Reflection
#region ISerializable
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- MemberInfoSerializationHolder.GetSerializationInfo(info, this);
+ throw new PlatformNotSupportedException();
}
#endregion
diff --git a/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs
index 29cc97d225..e61c0922d7 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs
@@ -9,7 +9,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- [Serializable]
internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable
{
#region Private Data Members
@@ -125,11 +124,7 @@ namespace System.Reflection
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- MemberInfoSerializationHolder.GetSerializationInfo(info, this);
+ throw new PlatformNotSupportedException();
}
#endregion
}
diff --git a/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs
index b8a2341e4e..3b2a75b1b7 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs
@@ -14,7 +14,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- [Serializable]
internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo
{
#region Private Data Members
@@ -772,14 +771,7 @@ namespace System.Reflection
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- if (m_reflectedTypeCache.IsGlobal)
- throw new NotSupportedException(SR.NotSupported_GlobalMethodSerialization);
-
- MemberInfoSerializationHolder.GetSerializationInfo(info, this);
+ throw new PlatformNotSupportedException();
}
internal string SerializationToString()
diff --git a/src/mscorlib/src/System/Reflection/RuntimeModule.cs b/src/mscorlib/src/System/Reflection/RuntimeModule.cs
index 75809cba01..f9b733736d 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeModule.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeModule.cs
@@ -12,7 +12,6 @@ using System.Diagnostics.Contracts;
namespace System.Reflection
{
- [Serializable]
internal class RuntimeModule : Module
{
internal RuntimeModule() { throw new NotSupportedException(); }
@@ -448,12 +447,7 @@ namespace System.Reflection
#region Public Virtuals
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly());
+ throw new PlatformNotSupportedException();
}
public override Type GetType(String className, bool throwOnError, bool ignoreCase)
diff --git a/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs
index addf68e75d..d21af03649 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs
@@ -11,7 +11,6 @@ using MdToken = System.Reflection.MetadataToken;
namespace System.Reflection
{
- [Serializable]
internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable
{
#region Static Members
@@ -164,35 +163,7 @@ namespace System.Reflection
#region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // We could be serializing for consumption by a pre-Whidbey
- // endpoint. Therefore we set up all the serialized fields to look
- // just like a v1.0/v1.1 instance.
-
- // Need to set the type to ParameterInfo so that pre-Whidbey and Whidbey code
- // can deserialize this. This is also why we cannot simply use [OnSerializing].
- info.SetType(typeof(ParameterInfo));
-
- // Use the properties intead of the fields in case the fields haven't been et
- // _importer, bExtraConstChecked, and m_cachedData don't need to be set
-
- // Now set the legacy fields that the current implementation doesn't
- // use any more. Note that _importer is a raw pointer that should
- // never have been serialized in V1. We set it to zero here; if the
- // deserializer uses it (by calling GetCustomAttributes() on this
- // instance) they'll AV, but at least it will be a well defined
- // exception and not a random AV.
-
- info.AddValue("AttrsImpl", Attributes);
- info.AddValue("ClassImpl", ParameterType);
- info.AddValue("DefaultValueImpl", DefaultValue);
- info.AddValue("MemberImpl", Member);
- info.AddValue("NameImpl", Name);
- info.AddValue("PositionImpl", Position);
- info.AddValue("_token", m_tkParamDef);
+ throw new PlatformNotSupportedException();
}
#endregion
diff --git a/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs b/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs
index b6a4792e4f..24f6de1e77 100644
--- a/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs
@@ -12,7 +12,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- [Serializable]
internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable
{
#region Private Data Members
@@ -451,11 +450,7 @@ namespace System.Reflection
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- MemberInfoSerializationHolder.GetSerializationInfo(info, this);
+ throw new PlatformNotSupportedException();
}
internal string SerializationToString()
diff --git a/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs b/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs
deleted file mode 100644
index 4ad7b4c93a..0000000000
--- a/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs
+++ /dev/null
@@ -1,96 +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.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Encapsulates CultureInfo fallback for resource
-** lookup
-**
-**
-===========================================================*/
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Runtime.Versioning;
-
-namespace System.Resources
-{
- internal class ResourceFallbackManager : IEnumerable<CultureInfo>
- {
- private CultureInfo m_startingCulture;
- private CultureInfo m_neutralResourcesCulture;
- private bool m_useParents;
-
- // This is a cache of the thread, process, user, and OS-preferred fallback cultures.
- // However, each thread may have a different value, and these may change during the
- // lifetime of the process. So this cache must be verified each time we use it.
- // Hence, we'll keep an array of strings for culture names & check it each time,
- // but we'll really cache an array of CultureInfo's. Using thread-local statics
- // as well to avoid differences across threads.
- [ThreadStatic]
- private static CultureInfo[] cachedOsFallbackArray;
-
- internal ResourceFallbackManager(CultureInfo startingCulture, CultureInfo neutralResourcesCulture, bool useParents)
- {
- if (startingCulture != null)
- {
- m_startingCulture = startingCulture;
- }
- else
- {
- m_startingCulture = CultureInfo.CurrentUICulture;
- }
-
- m_neutralResourcesCulture = neutralResourcesCulture;
- m_useParents = useParents;
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
-
- // WARING: This function must be kept in sync with ResourceManager.GetFirstResourceSet()
- public IEnumerator<CultureInfo> GetEnumerator()
- {
- bool reachedNeutralResourcesCulture = false;
-
- // 1. starting culture chain, up to neutral
- CultureInfo currentCulture = m_startingCulture;
- do
- {
- if (m_neutralResourcesCulture != null && currentCulture.Name == m_neutralResourcesCulture.Name)
- {
- // Return the invariant culture all the time, even if the UltimateResourceFallbackLocation
- // is a satellite assembly. This is fixed up later in ManifestBasedResourceGroveler::UltimateFallbackFixup.
- yield return CultureInfo.InvariantCulture;
- reachedNeutralResourcesCulture = true;
- break;
- }
- yield return currentCulture;
- currentCulture = currentCulture.Parent;
- } while (m_useParents && !currentCulture.HasInvariantCultureName);
-
- if (!m_useParents || m_startingCulture.HasInvariantCultureName)
- {
- yield break;
- }
-
- // 2. invariant
- // Don't return invariant twice though.
- if (reachedNeutralResourcesCulture)
- yield break;
-
- yield return CultureInfo.InvariantCulture;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Resources/ResourceManager.cs b/src/mscorlib/src/System/Resources/ResourceManager.cs
index 993efddbfc..e3981481f7 100644
--- a/src/mscorlib/src/System/Resources/ResourceManager.cs
+++ b/src/mscorlib/src/System/Resources/ResourceManager.cs
@@ -149,7 +149,6 @@ namespace System.Resources
// is one such example.
//
- [Serializable]
public class ResourceManager
{
internal class CultureNameResourceSetPair
diff --git a/src/mscorlib/src/System/Resources/ResourceSet.cs b/src/mscorlib/src/System/Resources/ResourceSet.cs
index 8775f6411a..b4029a7e9c 100644
--- a/src/mscorlib/src/System/Resources/ResourceSet.cs
+++ b/src/mscorlib/src/System/Resources/ResourceSet.cs
@@ -13,25 +13,25 @@
**
===========================================================*/
+using System;
+using System.Collections;
+using System.IO;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Reflection;
+using System.Runtime.Serialization;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+using System.Collections.Generic;
+
namespace System.Resources
{
- using System;
- using System.Collections;
- using System.IO;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Reflection;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
// A ResourceSet stores all the resources defined in one particular CultureInfo.
//
// The method used to load resources is straightforward - this class
// enumerates over an IResourceReader, loading every name and value, and
// stores them in a hash table. Custom IResourceReaders can be used.
- //
- [Serializable]
+ //
public class ResourceSet : IDisposable, IEnumerable
{
[NonSerialized] protected IResourceReader Reader;
@@ -39,11 +39,6 @@ namespace System.Resources
private Hashtable _caseInsensitiveTable; // For case-insensitive lookups.
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- [OptionalField]
- private Assembly _assembly; // For LooselyLinkedResourceReferences
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
protected ResourceSet()
{
// To not inconvenience people subclassing us, we should allocate a new
@@ -68,16 +63,6 @@ namespace System.Resources
ReadResources();
}
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- public ResourceSet(String fileName, Assembly assembly)
- {
- Reader = new ResourceReader(fileName);
- CommonInit();
- _assembly = assembly;
- ReadResources();
- }
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
// Creates a ResourceSet using the system default ResourceReader
// implementation. Use this constructor to read from an open stream
// of data.
@@ -89,16 +74,6 @@ namespace System.Resources
ReadResources();
}
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- public ResourceSet(Stream stream, Assembly assembly)
- {
- Reader = new ResourceReader(stream);
- CommonInit();
- _assembly = assembly;
- ReadResources();
- }
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
public ResourceSet(IResourceReader reader)
{
if (reader == null)
@@ -109,19 +84,6 @@ namespace System.Resources
ReadResources();
}
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- public ResourceSet(IResourceReader reader, Assembly assembly)
- {
- if (reader == null)
- throw new ArgumentNullException(nameof(reader));
- Contract.EndContractBlock();
- Reader = reader;
- CommonInit();
- _assembly = assembly;
- ReadResources();
- }
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
private void CommonInit()
{
Table = new Hashtable();
@@ -156,15 +118,6 @@ namespace System.Resources
Dispose(true);
}
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- // Optional - used for resolving assembly manifest resource references.
- // This can safely be null.
- public Assembly Assembly {
- get { return _assembly; }
- /*protected*/ set { _assembly = value; }
- }
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
// Returns the preferred IResourceReader class for this kind of ResourceSet.
// Subclasses of ResourceSet using their own Readers &; should override
// GetDefaultReader and GetDefaultWriter.
@@ -178,7 +131,8 @@ namespace System.Resources
// GetDefaultReader and GetDefaultWriter.
public virtual Type GetDefaultWriter()
{
- return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, throwOnError: true);
+ Assembly resourceWriterAssembly = Assembly.Load("System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
+ return resourceWriterAssembly.GetType("System.Resources.ResourceWriter", true);
}
public virtual IDictionaryEnumerator GetEnumerator()
@@ -271,12 +225,6 @@ namespace System.Resources
while (en.MoveNext())
{
Object value = en.Value;
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- if (Assembly != null && value is LooselyLinkedResourceReference) {
- LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value;
- value = assRef.Resolve(Assembly);
- }
-#endif //LOOSELYLINKEDRESOURCEREFERENCE
Table.Add(en.Key, value);
}
// While technically possible to close the Reader here, don't close it
@@ -308,10 +256,6 @@ namespace System.Resources
if (caseTable == null)
{
caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
-#if _DEBUG
- //Console.WriteLine("ResourceSet::GetObject loading up case-insensitive data");
- BCLDebug.Perf(false, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing " + name + " correctly in your source");
-#endif
IDictionaryEnumerator en = copyOfTable.GetEnumerator();
while (en.MoveNext())
diff --git a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs b/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
deleted file mode 100644
index e9c038a498..0000000000
--- a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
+++ /dev/null
@@ -1,462 +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.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: CultureInfo-specific collection of resources.
-**
-**
-===========================================================*/
-
-namespace System.Resources
-{
- using System;
- using System.IO;
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Reflection;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- // A RuntimeResourceSet stores all the resources defined in one
- // particular CultureInfo, with some loading optimizations.
- //
- // It is expected that nearly all the runtime's users will be satisfied with the
- // default resource file format, and it will be more efficient than most simple
- // implementations. Users who would consider creating their own ResourceSets and/or
- // ResourceReaders and ResourceWriters are people who have to interop with a
- // legacy resource file format, are creating their own resource file format
- // (using XML, for instance), or require doing resource lookups at runtime over
- // the network. This group will hopefully be small, but all the infrastructure
- // should be in place to let these users write & plug in their own tools.
- //
- // The Default Resource File Format
- //
- // The fundamental problems addressed by the resource file format are:
- //
- // * Versioning - A ResourceReader could in theory support many different
- // file format revisions.
- // * Storing intrinsic datatypes (ie, ints, Strings, DateTimes, etc) in a compact
- // format
- // * Support for user-defined classes - Accomplished using Serialization
- // * Resource lookups should not require loading an entire resource file - If you
- // look up a resource, we only load the value for that resource, minimizing working set.
- //
- //
- // There are four sections to the default file format. The first
- // is the Resource Manager header, which consists of a magic number
- // that identifies this as a Resource file, and a ResourceSet class name.
- // The class name is written here to allow users to provide their own
- // implementation of a ResourceSet (and a matching ResourceReader) to
- // control policy. If objects greater than a certain size or matching a
- // certain naming scheme shouldn't be stored in memory, users can tweak that
- // with their own subclass of ResourceSet.
- //
- // The second section in the system default file format is the
- // RuntimeResourceSet specific header. This contains a version number for
- // the .resources file, the number of resources in this file, the number of
- // different types contained in the file, followed by a list of fully
- // qualified type names. After this, we include an array of hash values for
- // each resource name, then an array of virtual offsets into the name section
- // of the file. The hashes allow us to do a binary search on an array of
- // integers to find a resource name very quickly without doing many string
- // compares (except for once we find the real type, of course). If a hash
- // matches, the index into the array of hash values is used as the index
- // into the name position array to find the name of the resource. The type
- // table allows us to read multiple different classes from the same file,
- // including user-defined types, in a more efficient way than using
- // Serialization, at least when your .resources file contains a reasonable
- // proportion of base data types such as Strings or ints. We use
- // Serialization for all the non-instrinsic types.
- //
- // The third section of the file is the name section. It contains a
- // series of resource names, written out as byte-length prefixed little
- // endian Unicode strings (UTF-16). After each name is a four byte virtual
- // offset into the data section of the file, pointing to the relevant
- // string or serialized blob for this resource name.
- //
- // The fourth section in the file is the data section, which consists
- // of a type and a blob of bytes for each item in the file. The type is
- // an integer index into the type table. The data is specific to that type,
- // but may be a number written in binary format, a String, or a serialized
- // Object.
- //
- // The system default file format (V1) is as follows:
- //
- // What Type of Data
- // ==================================================== ===========
- //
- // Resource Manager header
- // Magic Number (0xBEEFCACE) Int32
- // Resource Manager header version Int32
- // Num bytes to skip from here to get past this header Int32
- // Class name of IResourceReader to parse this file String
- // Class name of ResourceSet to parse this file String
- //
- // RuntimeResourceReader header
- // ResourceReader version number Int32
- // [Only in debug V2 builds - "***DEBUG***"] String
- // Number of resources in the file Int32
- // Number of types in the type table Int32
- // Name of each type Set of Strings
- // Padding bytes for 8-byte alignment (use PAD) Bytes (0-7)
- // Hash values for each resource name Int32 array, sorted
- // Virtual offset of each resource name Int32 array, coupled with hash values
- // Absolute location of Data section Int32
- //
- // RuntimeResourceReader Name Section
- // Name & virtual offset of each resource Set of (UTF-16 String, Int32) pairs
- //
- // RuntimeResourceReader Data Section
- // Type and Value of each resource Set of (Int32, blob of bytes) pairs
- //
- // This implementation, when used with the default ResourceReader class,
- // loads only the strings that you look up for. It can do string comparisons
- // without having to create a new String instance due to some memory mapped
- // file optimizations in the ResourceReader and FastResourceComparer
- // classes. This keeps the memory we touch to a minimum when loading
- // resources.
- //
- // If you use a different IResourceReader class to read a file, or if you
- // do case-insensitive lookups (and the case-sensitive lookup fails) then
- // we will load all the names of each resource and each resource value.
- // This could probably use some optimization.
- //
- // In addition, this supports object serialization in a similar fashion.
- // We build an array of class types contained in this file, and write it
- // to RuntimeResourceReader header section of the file. Every resource
- // will contain its type (as an index into the array of classes) with the data
- // for that resource. We will use the Runtime's serialization support for this.
- //
- // All strings in the file format are written with BinaryReader and
- // BinaryWriter, which writes out the length of the String in bytes as an
- // Int32 then the contents as Unicode chars encoded in UTF-8. In the name
- // table though, each resource name is written in UTF-16 so we can do a
- // string compare byte by byte against the contents of the file, without
- // allocating objects. Ideally we'd have a way of comparing UTF-8 bytes
- // directly against a String object, but that may be a lot of work.
- //
- // The offsets of each resource string are relative to the beginning
- // of the Data section of the file. This way, if a tool decided to add
- // one resource to a file, it would only need to increment the number of
- // resources, add the hash &amp; location of last byte in the name section
- // to the array of resource hashes and resource name positions (carefully
- // keeping these arrays sorted), add the name to the end of the name &amp;
- // offset list, possibly add the type list of types types (and increase
- // the number of items in the type table), and add the resource value at
- // the end of the file. The other offsets wouldn't need to be updated to
- // reflect the longer header section.
- //
- // Resource files are currently limited to 2 gigabytes due to these
- // design parameters. A future version may raise the limit to 4 gigabytes
- // by using unsigned integers, or may use negative numbers to load items
- // out of an assembly manifest. Also, we may try sectioning the resource names
- // into smaller chunks, each of size sqrt(n), would be substantially better for
- // resource files containing thousands of resources.
- //
- internal sealed class RuntimeResourceSet : ResourceSet, IEnumerable
- {
- internal const int Version = 2; // File format version number
-
- // Cache for resources. Key is the resource name, which can be cached
- // for arbitrarily long times, since the object is usually a string
- // literal that will live for the lifetime of the appdomain. The
- // value is a ResourceLocator instance, which might cache the object.
- private Dictionary<String, ResourceLocator> _resCache;
-
-
- // For our special load-on-demand reader, cache the cast. The
- // RuntimeResourceSet's implementation knows how to treat this reader specially.
- private ResourceReader _defaultReader;
-
- // This is a lookup table for case-insensitive lookups, and may be null.
- // Consider always using a case-insensitive resource cache, as we don't
- // want to fill this out if we can avoid it. The problem is resource
- // fallback will somewhat regularly cause us to look up resources that
- // don't exist.
- private Dictionary<String, ResourceLocator> _caseInsensitiveTable;
-
- // If we're not using our custom reader, then enumerate through all
- // the resources once, adding them into the table.
- private bool _haveReadFromReader;
-
- internal RuntimeResourceSet(String fileName) : base(false)
- {
- BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(String)");
- _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
- Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
- _defaultReader = new ResourceReader(stream, _resCache);
- Reader = _defaultReader;
- }
-
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- internal RuntimeResourceSet(Stream stream, Assembly assembly) : base(false)
- {
- BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(Stream)");
- _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
- _defaultReader = new ResourceReader(stream, _resCache);
- Reader = _defaultReader;
- Assembly = assembly;
- }
-#else
- internal RuntimeResourceSet(Stream stream) : base(false)
- {
- BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(Stream)");
- _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
- _defaultReader = new ResourceReader(stream, _resCache);
- Reader = _defaultReader;
- }
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
- protected override void Dispose(bool disposing)
- {
- if (Reader == null)
- return;
-
- if (disposing)
- {
- lock (Reader)
- {
- _resCache = null;
- if (_defaultReader != null)
- {
- _defaultReader.Close();
- _defaultReader = null;
- }
- _caseInsensitiveTable = null;
- // Set Reader to null to avoid a race in GetObject.
- base.Dispose(disposing);
- }
- }
- else
- {
- // Just to make sure we always clear these fields in the future...
- _resCache = null;
- _caseInsensitiveTable = null;
- _defaultReader = null;
- base.Dispose(disposing);
- }
- }
-
- public override IDictionaryEnumerator GetEnumerator()
- {
- return GetEnumeratorHelper();
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumeratorHelper();
- }
-
- private IDictionaryEnumerator GetEnumeratorHelper()
- {
- IResourceReader copyOfReader = Reader;
- if (copyOfReader == null || _resCache == null)
- throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
-
- return copyOfReader.GetEnumerator();
- }
-
-
- public override String GetString(String key)
- {
- Object o = GetObject(key, false, true);
- return (String)o;
- }
-
- public override String GetString(String key, bool ignoreCase)
- {
- Object o = GetObject(key, ignoreCase, true);
- return (String)o;
- }
-
- public override Object GetObject(String key)
- {
- return GetObject(key, false, false);
- }
-
- public override Object GetObject(String key, bool ignoreCase)
- {
- return GetObject(key, ignoreCase, false);
- }
-
- private Object GetObject(String key, bool ignoreCase, bool isString)
- {
- if (key == null)
- throw new ArgumentNullException(nameof(key));
- if (Reader == null || _resCache == null)
- throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
- Contract.EndContractBlock();
-
- Object value = null;
- ResourceLocator resLocation;
-
- lock (Reader)
- {
- if (Reader == null)
- throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
-
- if (_defaultReader != null)
- {
- BCLDebug.Log("RESMGRFILEFORMAT", "Going down fast path in RuntimeResourceSet::GetObject");
-
- // Find the offset within the data section
- int dataPos = -1;
- if (_resCache.TryGetValue(key, out resLocation))
- {
- value = resLocation.Value;
- dataPos = resLocation.DataPosition;
- }
-
- if (dataPos == -1 && value == null)
- {
- dataPos = _defaultReader.FindPosForResource(key);
- }
-
- if (dataPos != -1 && value == null)
- {
- Debug.Assert(dataPos >= 0, "data section offset cannot be negative!");
- // Normally calling LoadString or LoadObject requires
- // taking a lock. Note that in this case, we took a
- // lock on the entire RuntimeResourceSet, which is
- // sufficient since we never pass this ResourceReader
- // to anyone else.
- ResourceTypeCode typeCode;
- if (isString)
- {
- value = _defaultReader.LoadString(dataPos);
- typeCode = ResourceTypeCode.String;
- }
- else
- {
- value = _defaultReader.LoadObject(dataPos, out typeCode);
- }
-
- resLocation = new ResourceLocator(dataPos, (ResourceLocator.CanCache(typeCode)) ? value : null);
- lock (_resCache)
- {
- _resCache[key] = resLocation;
- }
- }
-
- if (value != null || !ignoreCase)
- {
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- if (Assembly != null && (value is LooselyLinkedResourceReference)) {
- LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value;
- value = assRef.Resolve(Assembly);
- }
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
- return value; // may be null
- }
- } // if (_defaultReader != null)
-
- // At this point, we either don't have our default resource reader
- // or we haven't found the particular resource we're looking for
- // and may have to search for it in a case-insensitive way.
- if (!_haveReadFromReader)
- {
- // If necessary, init our case insensitive hash table.
- if (ignoreCase && _caseInsensitiveTable == null)
- {
- _caseInsensitiveTable = new Dictionary<String, ResourceLocator>(StringComparer.OrdinalIgnoreCase);
- }
-#if _DEBUG
- BCLDebug.Perf(!ignoreCase, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing " + key + " correctly in your source");
-#endif
-
- if (_defaultReader == null)
- {
- IDictionaryEnumerator en = Reader.GetEnumerator();
- while (en.MoveNext())
- {
- DictionaryEntry entry = en.Entry;
- String readKey = (String)entry.Key;
- ResourceLocator resLoc = new ResourceLocator(-1, entry.Value);
- _resCache.Add(readKey, resLoc);
- if (ignoreCase)
- _caseInsensitiveTable.Add(readKey, resLoc);
- }
- // Only close the reader if it is NOT our default one,
- // since we need it around to resolve ResourceLocators.
- if (!ignoreCase)
- Reader.Close();
- }
- else
- {
- Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
- ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
- while (en.MoveNext())
- {
- // Note: Always ask for the resource key before the data position.
- String currentKey = (String)en.Key;
- int dataPos = en.DataPosition;
- ResourceLocator resLoc = new ResourceLocator(dataPos, null);
- _caseInsensitiveTable.Add(currentKey, resLoc);
- }
- }
- _haveReadFromReader = true;
- }
- Object obj = null;
- bool found = false;
- bool keyInWrongCase = false;
- if (_defaultReader != null)
- {
- if (_resCache.TryGetValue(key, out resLocation))
- {
- found = true;
- obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
- }
- }
- if (!found && ignoreCase)
- {
- if (_caseInsensitiveTable.TryGetValue(key, out resLocation))
- {
- found = true;
- keyInWrongCase = true;
- obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
- }
- }
- return obj;
- } // lock(Reader)
- }
-
- // The last parameter indicates whether the lookup required a
- // case-insensitive lookup to succeed, indicating we shouldn't add
- // the ResourceLocation to our case-sensitive cache.
- private Object ResolveResourceLocator(ResourceLocator resLocation, String key, Dictionary<String, ResourceLocator> copyOfCache, bool keyInWrongCase)
- {
- // We need to explicitly resolve loosely linked manifest
- // resources, and we need to resolve ResourceLocators with null objects.
- Object value = resLocation.Value;
- if (value == null)
- {
- ResourceTypeCode typeCode;
- lock (Reader)
- {
- value = _defaultReader.LoadObject(resLocation.DataPosition, out typeCode);
- }
- if (!keyInWrongCase && ResourceLocator.CanCache(typeCode))
- {
- resLocation.Value = value;
- copyOfCache[key] = resLocation;
- }
- }
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- if (Assembly != null && value is LooselyLinkedResourceReference) {
- LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value;
- value = assRef.Resolve(Assembly);
- }
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
- return value;
- }
- }
-}
diff --git a/src/mscorlib/src/System/RtType.cs b/src/mscorlib/src/System/RtType.cs
index ef3ba29787..68b9f5a75b 100644
--- a/src/mscorlib/src/System/RtType.cs
+++ b/src/mscorlib/src/System/RtType.cs
@@ -23,7 +23,6 @@ using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
-using System.Runtime.Remoting;
using MdSigCallingConvention = System.Signature.MdSigCallingConvention;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
using System.Runtime.InteropServices;
@@ -72,7 +71,6 @@ namespace System
FullName,
}
- [Serializable]
internal class RuntimeType :
System.Reflection.TypeInfo, ISerializable, ICloneable
{
@@ -1200,7 +1198,7 @@ namespace System
{
string name = eventInfo.Name;
- if (csEventInfos.GetValueOrDefault(name) != null)
+ if (csEventInfos.ContainsKey(name))
continue;
csEventInfos[name] = eventInfo;
@@ -1355,10 +1353,8 @@ namespace System
if (csPropertyInfos != null)
{
string name = propertyInfo.Name;
-
- List<RuntimePropertyInfo> cache = csPropertyInfos.GetValueOrDefault(name);
-
- if (cache == null)
+ List<RuntimePropertyInfo> cache;
+ if (!csPropertyInfos.TryGetValue(name, out cache))
{
cache = new List<RuntimePropertyInfo>(1);
csPropertyInfos[name] = cache;
@@ -3792,6 +3788,11 @@ namespace System
#endregion
#region Misc
+ public override bool IsTypeDefinition
+ {
+ get { return RuntimeTypeHandle.IsTypeDefinition(this); }
+ }
+
public override Type MakePointerType() { return new RuntimeTypeHandle(this).MakePointer(); }
public override Type MakeByRefType() { return new RuntimeTypeHandle(this).MakeByRef(); }
public override Type MakeArrayType() { return new RuntimeTypeHandle(this).MakeSZArray(); }
@@ -4444,11 +4445,7 @@ namespace System
#region ISerializable
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- UnitySerializationHolder.GetUnitySerializationInfo(info, this);
+ throw new PlatformNotSupportedException();
}
#endregion
@@ -4908,7 +4905,6 @@ namespace System
// method (RuntimeType) and an instance of this type will work around the reason to have this type in the
// first place. However given RuntimeType is not public all its methods are protected and require full trust
// to be accessed
- [Serializable]
internal class ReflectionOnlyType : RuntimeType
{
private ReflectionOnlyType() { }
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
index f32cc2b510..6c6f6ee472 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
@@ -651,16 +651,10 @@ namespace System.Runtime.CompilerServices
int bucket = hashCode & (_buckets.Length - 1);
for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
{
- if (_entries[entriesIndex].HashCode == hashCode)
+ if (_entries[entriesIndex].HashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out value) == key)
{
- object primary, secondary;
- _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
- if (primary == key)
- {
- GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
- value = secondary;
- return entriesIndex;
- }
+ GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+ return entriesIndex;
}
}
@@ -677,7 +671,7 @@ namespace System.Runtime.CompilerServices
if (index < _entries.Length)
{
object oKey, oValue;
- _entries[index].depHnd.GetPrimaryAndSecondary(out oKey, out oValue);
+ oKey = _entries[index].depHnd.GetPrimaryAndSecondary(out oValue);
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
if (oKey != null)
@@ -921,8 +915,8 @@ namespace System.Runtime.CompilerServices
{
for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
{
- object primary = null, secondary = null;
- _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
+ object primary, secondary;
+ primary = _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out secondary);
// Now that we've secured a strong reference to the secondary, must check the primary again
// to ensure it didn't expire (otherwise, we open a race where TryGetValue misreports an
@@ -951,7 +945,7 @@ namespace System.Runtime.CompilerServices
}
object thisKey, thisValue;
- _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue);
+ thisKey = _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisValue);
if (Equals(thisKey, key))
{
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
@@ -1069,10 +1063,8 @@ namespace System.Runtime.CompilerServices
#region Constructors
public DependentHandle(object primary, object secondary)
{
- IntPtr handle = (IntPtr)0;
- nInitialize(primary, secondary, out handle);
// no need to check for null result: nInitialize expected to throw OOM.
- _handle = handle;
+ _handle = nInitialize(primary, secondary);
}
#endregion
@@ -1084,14 +1076,12 @@ namespace System.Runtime.CompilerServices
// primary.
public object GetPrimary()
{
- object primary;
- nGetPrimary(_handle, out primary);
- return primary;
+ return nGetPrimary(_handle);
}
- public void GetPrimaryAndSecondary(out object primary, out object secondary)
+ public object GetPrimaryAndSecondary(out object secondary)
{
- nGetPrimaryAndSecondary(_handle, out primary, out secondary);
+ return nGetPrimaryAndSecondary(_handle, out secondary);
}
public void SetPrimary(object primary)
@@ -1121,13 +1111,13 @@ namespace System.Runtime.CompilerServices
#region Private Members
[MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void nInitialize(object primary, object secondary, out IntPtr dependentHandle);
+ private static extern IntPtr nInitialize(object primary, object secondary);
[MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void nGetPrimary(IntPtr dependentHandle, out object primary);
+ private static extern object nGetPrimary(IntPtr dependentHandle);
[MethodImpl(MethodImplOptions.InternalCall)]
- private static extern void nGetPrimaryAndSecondary(IntPtr dependentHandle, out object primary, out object secondary);
+ private static extern object nGetPrimaryAndSecondary(IntPtr dependentHandle, out object secondary);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void nSetPrimary(IntPtr dependentHandle, object primary);
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
index 8f4c79cd94..7393bb2bcd 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
@@ -7,7 +7,6 @@ using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
public abstract class CustomConstantAttribute : Attribute
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
index 7aca42b627..5155d0085d 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
@@ -7,7 +7,6 @@ using System.Diagnostics.Contracts;
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
public sealed class DateTimeConstantAttribute : CustomConstantAttribute
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
index 0e2b6f8418..f5fd5a21a3 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
@@ -12,7 +12,6 @@ using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
public sealed class DecimalConstantAttribute : Attribute
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
index b24018cf78..3c19ee8863 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
@@ -12,7 +12,6 @@ namespace System.Runtime.CompilerServices
// certain method properties.
// Custom attribute to specify additional method properties.
- [Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
sealed public class MethodImplAttribute : Attribute
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
index c050000169..df52f301e4 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
@@ -13,12 +13,10 @@
using System;
using System.Runtime.Serialization;
-using System.Runtime.Remoting;
using System.Diagnostics.Contracts;
namespace System.Runtime.CompilerServices
{
- [Serializable]
public sealed class RuntimeWrappedException : Exception
{
private RuntimeWrappedException(Object thrownObject)
@@ -37,19 +35,7 @@ namespace System.Runtime.CompilerServices
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
base.GetObjectData(info, context);
- info.AddValue("WrappedException", m_wrappedException, typeof(Object));
- }
-
- internal RuntimeWrappedException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- m_wrappedException = info.GetValue("WrappedException", typeof(Object));
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/GcSettings.cs b/src/mscorlib/src/System/Runtime/GcSettings.cs
index 993a24f986..ecb28e6034 100644
--- a/src/mscorlib/src/System/Runtime/GcSettings.cs
+++ b/src/mscorlib/src/System/Runtime/GcSettings.cs
@@ -13,14 +13,12 @@ namespace System.Runtime
// These settings are the same format as in clr\src\vm\gcpriv.h
// make sure you change that file if you change this file!
- [Serializable]
public enum GCLargeObjectHeapCompactionMode
{
Default = 1,
CompactOnce = 2
}
- [Serializable]
public enum GCLatencyMode
{
Batch = 0,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
index c4beb024b1..e009db277f 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
@@ -9,7 +9,6 @@ using System.Runtime.Versioning;
namespace System.Runtime.InteropServices
{
- [Serializable]
public struct ArrayWithOffset
{
//private ArrayWithOffset()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
index ccba51e840..668358995b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
@@ -46,7 +46,6 @@ namespace System.Runtime.InteropServices
public int Value { get { return _val; } }
}
- [Serializable]
public enum ComInterfaceType
{
InterfaceIsDual = 0,
@@ -84,7 +83,6 @@ namespace System.Runtime.InteropServices
public Type Value { get { return _val; } }
}
- [Serializable]
public enum ClassInterfaceType
{
None = 0,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
index 77c38139cd..586b03b366 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
@@ -17,7 +17,6 @@ using System.Security;
namespace System.Runtime.InteropServices
{
- [Serializable]
public sealed class BStrWrapper
{
public BStrWrapper(String value)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
index 889a74f6bc..8ee10ed349 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
@@ -22,7 +22,6 @@ namespace System.Runtime.InteropServices
{
// Exception for COM Interop errors where we don't recognize the HResult.
//
- [Serializable]
public class COMException : ExternalException
{
public COMException()
@@ -51,6 +50,7 @@ namespace System.Runtime.InteropServices
protected COMException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
public override String ToString()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
index 8198d9fd18..fe69f619fe 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
@@ -99,7 +99,6 @@
// code:ComEventsMethod.Invoke
using System;
-using System.Runtime.Remoting;
namespace System.Runtime.InteropServices
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs
index ea99781975..2de01465d3 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs
@@ -9,7 +9,6 @@ using System;
namespace System.Runtime.InteropServices
{
- [Serializable]
public enum ComMemberType
{
Method = 0,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs
index 967746f379..ae403d138c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs
@@ -15,7 +15,6 @@ using System;
namespace System.Runtime.InteropServices.ComTypes
{
- [Serializable]
public enum DESCKIND
{
DESCKIND_NONE = 0,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs
index 1857fdbb35..4cd102f76e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs
@@ -15,7 +15,6 @@ using System;
namespace System.Runtime.InteropServices.ComTypes
{
- [Serializable]
public enum TYPEKIND
{
TKIND_ENUM = 0,
@@ -29,7 +28,6 @@ namespace System.Runtime.InteropServices.ComTypes
TKIND_MAX = TKIND_UNION + 1
}
- [Serializable]
[Flags()]
public enum TYPEFLAGS : short
{
@@ -50,7 +48,6 @@ namespace System.Runtime.InteropServices.ComTypes
TYPEFLAG_FPROXY = 0x4000
}
- [Serializable]
[Flags()]
public enum IMPLTYPEFLAGS
{
@@ -106,7 +103,6 @@ namespace System.Runtime.InteropServices.ComTypes
public Int16 wFuncFlags; //WORD wFuncFlags;
}
- [Serializable]
[Flags()]
public enum IDLFLAG : short
{
@@ -125,7 +121,6 @@ namespace System.Runtime.InteropServices.ComTypes
public IDLFLAG wIDLFlags;
}
- [Serializable]
[Flags()]
public enum PARAMFLAG : short
{
@@ -173,7 +168,6 @@ namespace System.Runtime.InteropServices.ComTypes
public DESCUNION desc;
}
- [Serializable]
public enum VARKIND : int
{
VAR_PERINSTANCE = 0x0,
@@ -231,7 +225,6 @@ namespace System.Runtime.InteropServices.ComTypes
public Int32 scode;
}
- [Serializable]
public enum FUNCKIND : int
{
FUNC_VIRTUAL = 0,
@@ -241,7 +234,6 @@ namespace System.Runtime.InteropServices.ComTypes
FUNC_DISPATCH = 4
}
- [Serializable]
[Flags]
public enum INVOKEKIND : int
{
@@ -251,7 +243,6 @@ namespace System.Runtime.InteropServices.ComTypes
INVOKE_PROPERTYPUTREF = 0x8
}
- [Serializable]
public enum CALLCONV : int
{
CC_CDECL = 1,
@@ -266,7 +257,6 @@ namespace System.Runtime.InteropServices.ComTypes
CC_MAX = 9
}
- [Serializable]
[Flags()]
public enum FUNCFLAGS : short
{
@@ -285,7 +275,6 @@ namespace System.Runtime.InteropServices.ComTypes
FUNCFLAG_FIMMEDIATEBIND = 0x1000
}
- [Serializable]
[Flags()]
public enum VARFLAGS : short
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs
index 3ed6e42d08..05a9e3f176 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs
@@ -15,7 +15,6 @@ using System;
namespace System.Runtime.InteropServices.ComTypes
{
- [Serializable]
public enum SYSKIND
{
SYS_WIN16 = 0,
@@ -24,7 +23,6 @@ namespace System.Runtime.InteropServices.ComTypes
SYS_WIN64 = SYS_MAC + 1
}
- [Serializable]
[Flags()]
public enum LIBFLAGS : short
{
@@ -35,7 +33,6 @@ namespace System.Runtime.InteropServices.ComTypes
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- [Serializable]
public struct TYPELIBATTR
{
public Guid guid;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
index 4b436825e8..590925aafe 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
@@ -16,7 +16,6 @@ using System;
namespace System.Runtime.InteropServices
{
- [Serializable]
public sealed class CurrencyWrapper
{
public CurrencyWrapper(Decimal obj)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
index 87ec4ed15e..5fb78c56ad 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
@@ -17,7 +17,6 @@ using System.Security;
namespace System.Runtime.InteropServices
{
- [Serializable]
public sealed class DispatchWrapper
{
public DispatchWrapper(Object obj)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
index 73be2c5777..34237d539a 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
@@ -16,7 +16,6 @@ using System;
namespace System.Runtime.InteropServices
{
- [Serializable]
public sealed class ErrorWrapper
{
public ErrorWrapper(int errorCode)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
index dcb9e24258..2ee81a9f5c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
@@ -18,7 +18,6 @@ namespace System.Runtime.InteropServices
// IMPORTANT: These must match the definitions in ObjectHandle.h in the EE.
// IMPORTANT: If new values are added to the enum the GCHandle::MaxHandleType
// constant must be updated.
- [Serializable]
public enum GCHandleType
{
Weak = 0,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
index 4f4b10bbf0..f0aa35e7dd 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
@@ -19,7 +19,6 @@ namespace System.Runtime.InteropServices
//====================================================================
// The enum of the return value of IQuerable.GetInterface
//====================================================================
- [Serializable]
public enum CustomQueryInterfaceResult
{
Handled = 0,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
index 2fae2b6e52..bf89df94bb 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
@@ -17,7 +17,6 @@ using System.Runtime.Serialization;
namespace System.Runtime.InteropServices
{
- [Serializable]
public class InvalidComObjectException : SystemException
{
public InvalidComObjectException()
@@ -40,6 +39,7 @@ namespace System.Runtime.InteropServices
protected InvalidComObjectException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
index 5154a028ad..412853920e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System.Runtime.InteropServices
{
- [Serializable]
public class InvalidOleVariantTypeException : SystemException
{
public InvalidOleVariantTypeException()
@@ -39,6 +38,7 @@ namespace System.Runtime.InteropServices
protected InvalidOleVariantTypeException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
index 6fb631121b..03750bcb8b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
@@ -15,13 +15,13 @@
namespace System.Runtime.InteropServices
{
using System;
+ using System.Runtime;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Text;
using System.Threading;
- using System.Runtime.Remoting;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
@@ -31,8 +31,8 @@ namespace System.Runtime.InteropServices
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.ComTypes;
+ using System.StubHelpers;
- [Serializable]
public enum CustomQueryInterfaceMode
{
Ignore = 0,
@@ -406,9 +406,9 @@ namespace System.Runtime.InteropServices
//====================================================================
// Read from memory
//====================================================================
- public static byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
+ public static byte ReadByte(Object ptr, int ofs)
{
- throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
+ return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadByte(nativeHome, offset));
}
public static unsafe byte ReadByte(IntPtr ptr, int ofs)
@@ -430,9 +430,9 @@ namespace System.Runtime.InteropServices
return ReadByte(ptr, 0);
}
- public static short ReadInt16([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
+ public static short ReadInt16(Object ptr, int ofs)
{
- throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
+ return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt16(nativeHome, offset));
}
public static unsafe short ReadInt16(IntPtr ptr, int ofs)
@@ -467,9 +467,9 @@ namespace System.Runtime.InteropServices
return ReadInt16(ptr, 0);
}
- public static int ReadInt32([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
+ public static int ReadInt32(object ptr, int ofs)
{
- throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
+ return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt32(nativeHome, offset));
}
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
@@ -506,7 +506,7 @@ namespace System.Runtime.InteropServices
return ReadInt32(ptr, 0);
}
- public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
+ public static IntPtr ReadIntPtr(Object ptr, int ofs)
{
#if BIT64
return (IntPtr)ReadInt64(ptr, ofs);
@@ -535,7 +535,7 @@ namespace System.Runtime.InteropServices
public static long ReadInt64([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
{
- throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
+ return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt64(nativeHome, offset));
}
public static unsafe long ReadInt64(IntPtr ptr, int ofs)
@@ -576,6 +576,41 @@ namespace System.Runtime.InteropServices
return ReadInt64(ptr, 0);
}
+ //====================================================================
+ // Read value from marshaled object (marshaled using AsAny)
+ // It's quite slow and can return back dangling pointers
+ // It's only there for backcompact
+ // I don't think we should spend time optimizing it
+ // People should really call the IntPtr overload instead
+ //====================================================================
+ private static unsafe T ReadValueSlow<T>(object ptr, int ofs, Func<IntPtr, int, T> readValueHelper)
+ {
+ // We AV on desktop if passing NULL. So this is technically a breaking change but is an improvement
+ if (ptr == null)
+ throw new ArgumentNullException(nameof(ptr));
+
+ int dwFlags =
+ (int)AsAnyMarshaler.AsAnyFlags.In |
+ (int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
+ (int)AsAnyMarshaler.AsAnyFlags.IsBestFit;
+
+ MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState();
+ AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState));
+
+ IntPtr pNativeHome = IntPtr.Zero;
+
+ try
+ {
+ pNativeHome = marshaler.ConvertToNative(ptr, dwFlags);
+ return readValueHelper(pNativeHome, ofs);
+ }
+ finally
+ {
+ marshaler.ClearNative(pNativeHome);
+ }
+ }
+
+
//====================================================================
// Write to memory
@@ -594,9 +629,9 @@ namespace System.Runtime.InteropServices
}
}
- public static void WriteByte([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, byte val)
+ public static void WriteByte(Object ptr, int ofs, byte val)
{
- throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
+ WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, byte value) => Marshal.WriteByte(nativeHome, offset, value));
}
public static void WriteByte(IntPtr ptr, byte val)
@@ -629,9 +664,9 @@ namespace System.Runtime.InteropServices
}
}
- public static void WriteInt16([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, short val)
+ public static void WriteInt16(Object ptr, int ofs, short val)
{
- throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
+ WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, short value) => Marshal.WriteInt16(nativeHome, offset, value));
}
public static void WriteInt16(IntPtr ptr, short val)
@@ -681,9 +716,9 @@ namespace System.Runtime.InteropServices
}
}
- public static void WriteInt32([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, int val)
+ public static void WriteInt32(Object ptr, int ofs, int val)
{
- throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
+ WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, int value) => Marshal.WriteInt32(nativeHome, offset, value));
}
public static void WriteInt32(IntPtr ptr, int val)
@@ -700,7 +735,7 @@ namespace System.Runtime.InteropServices
#endif
}
- public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, IntPtr val)
+ public static void WriteIntPtr(Object ptr, int ofs, IntPtr val)
{
#if BIT64
WriteInt64(ptr, ofs, (long)val);
@@ -749,9 +784,9 @@ namespace System.Runtime.InteropServices
}
}
- public static void WriteInt64([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, long val)
+ public static void WriteInt64(Object ptr, int ofs, long val)
{
- throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
+ WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, long value) => Marshal.WriteInt64(nativeHome, offset, value));
}
public static void WriteInt64(IntPtr ptr, long val)
@@ -759,6 +794,41 @@ namespace System.Runtime.InteropServices
WriteInt64(ptr, 0, val);
}
+ //====================================================================
+ // Write value into marshaled object (marshaled using AsAny) and
+ // propagate the value back
+ // It's quite slow and is only there for backcompact
+ // I don't think we should spend time optimizing it
+ // People should really call the IntPtr overload instead
+ //====================================================================
+ private static unsafe void WriteValueSlow<T>(object ptr, int ofs, T val, Action<IntPtr, int, T> writeValueHelper)
+ {
+ // We AV on desktop if passing NULL. So this is technically a breaking change but is an improvement
+ if (ptr == null)
+ throw new ArgumentNullException(nameof(ptr));
+
+ int dwFlags =
+ (int)AsAnyMarshaler.AsAnyFlags.In |
+ (int)AsAnyMarshaler.AsAnyFlags.Out |
+ (int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
+ (int)AsAnyMarshaler.AsAnyFlags.IsBestFit;
+
+ MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState();
+ AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState));
+
+ IntPtr pNativeHome = IntPtr.Zero;
+
+ try
+ {
+ pNativeHome = marshaler.ConvertToNative(ptr, dwFlags);
+ writeValueHelper(pNativeHome, ofs, val);
+ marshaler.ConvertToManaged(ptr, pNativeHome);
+ }
+ finally
+ {
+ marshaler.ClearNative(pNativeHome);
+ }
+ }
//====================================================================
// GetLastWin32Error
@@ -1772,11 +1842,7 @@ namespace System.Runtime.InteropServices
}
Contract.EndContractBlock();
-#if FEATURE_COMINTEROP
return s.MarshalToBSTR();
-#else
- throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10443
-#endif
}
public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s)
@@ -1800,30 +1866,28 @@ namespace System.Runtime.InteropServices
return s.MarshalToString(globalAlloc: false, unicode: true);
}
-
-#if FEATURE_COMINTEROP
+
public static void ZeroFreeBSTR(IntPtr s)
{
- Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2));
+ RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2));
FreeBSTR(s);
}
-#endif
public static void ZeroFreeCoTaskMemAnsi(IntPtr s)
{
- Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
+ RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
FreeCoTaskMem(s);
}
public static void ZeroFreeCoTaskMemUnicode(IntPtr s)
{
- Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
+ RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
FreeCoTaskMem(s);
}
unsafe public static void ZeroFreeCoTaskMemUTF8(IntPtr s)
{
- Win32Native.ZeroMemory(s, (UIntPtr)System.StubHelpers.StubHelpers.strlen((sbyte*)s));
+ RuntimeImports.RhZeroMemory(s, (UIntPtr)System.StubHelpers.StubHelpers.strlen((sbyte*)s));
FreeCoTaskMem(s);
}
@@ -1851,13 +1915,13 @@ namespace System.Runtime.InteropServices
public static void ZeroFreeGlobalAllocAnsi(IntPtr s)
{
- Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
+ RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
FreeHGlobal(s);
}
public static void ZeroFreeGlobalAllocUnicode(IntPtr s)
{
- Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
+ RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
FreeHGlobal(s);
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
index 6fe7574e26..75b291af30 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
@@ -17,7 +17,6 @@ using System.Runtime.Serialization;
namespace System.Runtime.InteropServices
{
- [Serializable]
public class MarshalDirectiveException : SystemException
{
public MarshalDirectiveException()
@@ -40,6 +39,7 @@ namespace System.Runtime.InteropServices
protected MarshalDirectiveException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
index 7b7c5efb90..c79af8b459 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
@@ -171,11 +171,6 @@ namespace System.Runtime.InteropServices
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
-
- public static void ZeroFreeBSTR(System.IntPtr s)
- {
- throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
- }
}
public class DispatchWrapper
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs
index ed289fd14b..33f1b5f09c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs
@@ -16,7 +16,6 @@ using System;
namespace System.Runtime.InteropServices
{
// This Enum matchs the CorPinvokeMap defined in CorHdr.h
- [Serializable]
internal enum PInvokeMap
{
NoMangle = 0x0001, // Pinvoke is to use the member name as specified.
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMarshal.cs
new file mode 100644
index 0000000000..9eb60bdce7
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMarshal.cs
@@ -0,0 +1,24 @@
+// 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;
+
+namespace System.Runtime.InteropServices
+{
+ internal static class PInvokeMarshal
+ {
+ public static IntPtr AllocBSTR(int length)
+ {
+ IntPtr bstr = Win32Native.SysAllocStringLen(null, length);
+ if (bstr == IntPtr.Zero)
+ throw new OutOfMemoryException();
+ return bstr;
+ }
+
+ public static void FreeBSTR(IntPtr ptr)
+ {
+ Win32Native.SysFreeString(ptr);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
index 5595fadc43..d61e79757c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
@@ -19,7 +19,6 @@ namespace System.Runtime.InteropServices
{
// Exception for Structured Exception Handler exceptions.
//
- [Serializable]
public class SEHException : ExternalException
{
public SEHException()
@@ -42,6 +41,7 @@ namespace System.Runtime.InteropServices
protected SEHException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
// Exceptions can be resumable, meaning a filtered exception
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
index f39f1f3a41..9df858f0b1 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System.Runtime.InteropServices
{
- [Serializable]
public class SafeArrayRankMismatchException : SystemException
{
public SafeArrayRankMismatchException()
@@ -39,6 +38,7 @@ namespace System.Runtime.InteropServices
protected SafeArrayRankMismatchException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
index 2283263422..4b03691e82 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
@@ -17,7 +17,6 @@ using System.Runtime.Serialization;
namespace System.Runtime.InteropServices
{
- [Serializable]
public class SafeArrayTypeMismatchException : SystemException
{
public SafeArrayTypeMismatchException()
@@ -40,6 +39,7 @@ namespace System.Runtime.InteropServices
protected SafeArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs
index c758ae1b4f..de06cbf1a8 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs
@@ -16,7 +16,6 @@ using System;
namespace System.Runtime.InteropServices
{
- [Serializable]
public sealed class UnknownWrapper
{
public UnknownWrapper(Object obj)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs
index 50689e08f8..455f0759fe 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs
@@ -16,8 +16,6 @@ using System;
namespace System.Runtime.InteropServices
{
- [Serializable]
-
public sealed class VariantWrapper
{
public VariantWrapper(Object obj)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
index 4549a407e0..0ed0bb3f7b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
@@ -21,7 +21,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
/// </summary>
/// <typeparam name="TKey">Type of objects that act as keys.</typeparam>
/// <typeparam name="TValue">Type of objects that act as entries / values.</typeparam>
- [Serializable]
[DebuggerDisplay("Count = {Count}")]
internal sealed class ConstantSplittableMap<TKey, TValue> : IMapView<TKey, TValue>
{
@@ -169,7 +168,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
#region IKeyValuePair Enumerator
- [Serializable]
internal struct IKeyValuePairEnumerator : IEnumerator<IKeyValuePair<TKey, TValue>>
{
private KeyValuePair<TKey, TValue>[] _array;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
index 2a34aba717..f2434ce91d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
@@ -9,7 +9,6 @@ using System.Diagnostics;
namespace System.Runtime.InteropServices.WindowsRuntime
{
- [Serializable]
[DebuggerDisplay("Count = {Count}")]
internal sealed class DictionaryKeyCollection<TKey, TValue> : ICollection<TKey>
{
@@ -83,7 +82,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
} // public class DictionaryKeyCollection<TKey, TValue>
- [Serializable]
internal sealed class DictionaryKeyEnumerator<TKey, TValue> : IEnumerator<TKey>
{
private readonly IDictionary<TKey, TValue> dictionary;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
index 083b0ffcb1..6be0ddd9f0 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
@@ -13,7 +13,6 @@ using System.Runtime.InteropServices.WindowsRuntime;
namespace System.Runtime.InteropServices.WindowsRuntime
{
- [Serializable]
[DebuggerDisplay("Count = {Count}")]
internal sealed class DictionaryValueCollection<TKey, TValue> : ICollection<TValue>
{
@@ -91,7 +90,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
} // public class DictionaryValueCollection<TKey, TValue>
- [Serializable]
internal sealed class DictionaryValueEnumerator<TKey, TValue> : IEnumerator<TValue>
{
private readonly IDictionary<TKey, TValue> dictionary;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
index e06364dcae..0900012338 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
@@ -123,7 +123,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
// Note: One day we may make these return IReadOnlyCollection<T>
- [Serializable]
[DebuggerDisplay("Count = {Count}")]
internal sealed class ReadOnlyDictionaryKeyCollection<TKey, TValue> : IEnumerable<TKey>
{
@@ -178,7 +177,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
} // public class ReadOnlyDictionaryKeyCollection<TKey, TValue>
- [Serializable]
internal sealed class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> : IEnumerator<TKey>
{
private readonly IReadOnlyDictionary<TKey, TValue> dictionary;
@@ -220,7 +218,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
} // class ReadOnlyDictionaryKeyEnumerator<TKey, TValue>
- [Serializable]
[DebuggerDisplay("Count = {Count}")]
internal sealed class ReadOnlyDictionaryValueCollection<TKey, TValue> : IEnumerable<TValue>
{
@@ -279,7 +276,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
} // public class ReadOnlyDictionaryValueCollection<TKey, TValue>
- [Serializable]
internal sealed class ReadOnlyDictionaryValueEnumerator<TKey, TValue> : IEnumerator<TValue>
{
private readonly IReadOnlyDictionary<TKey, TValue> dictionary;
diff --git a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
index de8137f1ec..a7bf871a39 100644
--- a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
+++ b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
@@ -71,15 +71,9 @@ namespace System.Runtime.Loader
[SuppressUnmanagedCodeSecurity]
private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly);
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void GetLoadedAssembliesInternal(ObjectHandleOnStack assemblies);
-
public static Assembly[] GetLoadedAssemblies()
{
- Assembly[] assemblies = null;
- GetLoadedAssembliesInternal(JitHelpers.GetObjectHandleOnStack(ref assemblies));
- return assemblies;
+ return AppDomain.CurrentDomain.GetAssemblies(false);
}
// These are helpers that can be used by AssemblyLoadContext derivations.
diff --git a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
deleted file mode 100644
index e76882d6df..0000000000
--- a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
+++ /dev/null
@@ -1,40 +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.
-
-/*============================================================
-**
-**
-**
-** ObjectHandle wraps object references. A Handle allows a
-** marshal by value object to be returned through an
-** indirection allowing the caller to control when the
-** object is loaded into their domain.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace System.Runtime.Remoting
-{
- public class ObjectHandle
- {
- private Object WrappedObject;
-
- private ObjectHandle()
- {
- }
-
- internal ObjectHandle(Object o)
- {
- WrappedObject = o;
- }
-
- internal Object Unwrap()
- {
- return WrappedObject;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/RuntimeImports.cs b/src/mscorlib/src/System/Runtime/RuntimeImports.cs
index 16d41d3951..ed0c556575 100644
--- a/src/mscorlib/src/System/Runtime/RuntimeImports.cs
+++ b/src/mscorlib/src/System/Runtime/RuntimeImports.cs
@@ -8,7 +8,7 @@ using System.Runtime.InteropServices;
#if BIT64
using nuint = System.UInt64;
#else
- using nuint = System.UInt32;
+using nuint = System.UInt32;
#endif
namespace System.Runtime
@@ -26,8 +26,13 @@ namespace System.Runtime
}
}
+ internal unsafe static void RhZeroMemory(IntPtr p, UIntPtr byteLength)
+ {
+ RhZeroMemory((void*)p, (nuint)byteLength);
+ }
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- extern private unsafe static void RhZeroMemory(byte* b, nuint byteLength);
+ extern private unsafe static void RhZeroMemory(void* b, nuint byteLength);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern unsafe static void RhBulkMoveWithWriteBarrier(ref byte destination, ref byte source, nuint byteCount);
diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
index 18139324a3..b49b372b4b 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
@@ -17,7 +17,6 @@ using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Security;
-using System.Runtime.Remoting;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
index 7fc3ce27d9..8fb54c79a7 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
@@ -15,7 +15,6 @@
using System;
using System.Collections.Generic;
using System.Reflection;
-using System.Runtime.Remoting;
using System.Globalization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
diff --git a/src/mscorlib/src/System/RuntimeHandles.cs b/src/mscorlib/src/System/RuntimeHandles.cs
index ab125e741e..ceda5abfee 100644
--- a/src/mscorlib/src/System/RuntimeHandles.cs
+++ b/src/mscorlib/src/System/RuntimeHandles.cs
@@ -23,7 +23,6 @@ namespace System
using System.Diagnostics.Contracts;
using StackCrawlMark = System.Threading.StackCrawlMark;
- [Serializable]
public unsafe struct RuntimeTypeHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
@@ -127,6 +126,24 @@ namespace System
m_type = type;
}
+ internal static bool IsTypeDefinition(RuntimeType type)
+ {
+ 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;
+ }
+
internal static bool IsPrimitive(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
@@ -653,30 +670,9 @@ namespace System
return new MetadataImport(_GetMetadataImport(type), type);
}
- private RuntimeTypeHandle(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- RuntimeType m = (RuntimeType)info.GetValue("TypeObj", typeof(RuntimeType));
-
- m_type = m;
-
- if (m_type == null)
- throw new SerializationException(SR.Serialization_InsufficientState);
- }
-
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- if (m_type == null)
- throw new SerializationException(SR.Serialization_InvalidFieldState);
-
- info.AddValue("TypeObj", m_type, typeof(RuntimeType));
+ throw new PlatformNotSupportedException();
}
}
@@ -766,7 +762,6 @@ namespace System
}
}
- [Serializable]
public unsafe struct RuntimeMethodHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
@@ -796,33 +791,9 @@ namespace System
}
// ISerializable interface
- private RuntimeMethodHandle(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- MethodBase m = (MethodBase)info.GetValue("MethodObj", typeof(MethodBase));
-
- m_value = m.MethodHandle.m_value;
-
- if (m_value == null)
- throw new SerializationException(SR.Serialization_InsufficientState);
- }
-
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- if (m_value == null)
- throw new SerializationException(SR.Serialization_InvalidFieldState);
-
- // This is either a RuntimeMethodInfo or a RuntimeConstructorInfo
- MethodBase methodInfo = RuntimeType.GetMethodBase(m_value);
-
- info.AddValue("MethodObj", methodInfo, typeof(MethodBase));
+ throw new PlatformNotSupportedException();
}
public IntPtr Value
@@ -1149,7 +1120,6 @@ namespace System
}
}
- [Serializable]
public unsafe struct RuntimeFieldHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
@@ -1297,35 +1267,9 @@ namespace System
internal static extern void CheckAttributeAccess(RuntimeFieldHandle fieldHandle, RuntimeModule decoratedTarget);
// ISerializable interface
- private RuntimeFieldHandle(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- FieldInfo f = (RuntimeFieldInfo)info.GetValue("FieldObj", typeof(RuntimeFieldInfo));
-
- if (f == null)
- throw new SerializationException(SR.Serialization_InsufficientState);
-
- m_ptr = f.FieldHandle.m_ptr;
-
- if (m_ptr == null)
- throw new SerializationException(SR.Serialization_InsufficientState);
- }
-
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- if (m_ptr == null)
- throw new SerializationException(SR.Serialization_InvalidFieldState);
-
- RuntimeFieldInfo fldInfo = (RuntimeFieldInfo)RuntimeType.GetFieldInfo(this.GetRuntimeFieldInfo());
-
- info.AddValue("FieldObj", fldInfo, typeof(RuntimeFieldInfo));
+ throw new PlatformNotSupportedException();
}
}
diff --git a/src/mscorlib/src/System/SByte.cs b/src/mscorlib/src/System/SByte.cs
index 2f1b2da947..9e550936fe 100644
--- a/src/mscorlib/src/System/SByte.cs
+++ b/src/mscorlib/src/System/SByte.cs
@@ -24,7 +24,7 @@ namespace System
public struct SByte : IComparable, IFormattable, IConvertible
, IComparable<SByte>, IEquatable<SByte>
{
- private sbyte m_value;
+ private sbyte m_value; // Do not rename (binary serialization)
// The maximum value that a Byte may represent: 127.
public const sbyte MaxValue = (sbyte)0x7F;
diff --git a/src/mscorlib/src/System/SharedStatics.cs b/src/mscorlib/src/System/SharedStatics.cs
index a6a04d9614..5c37f25446 100644
--- a/src/mscorlib/src/System/SharedStatics.cs
+++ b/src/mscorlib/src/System/SharedStatics.cs
@@ -12,7 +12,6 @@
=============================================================================*/
using System.Threading;
-using System.Runtime.Remoting;
using System.Security;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
diff --git a/src/mscorlib/src/System/Single.cs b/src/mscorlib/src/System/Single.cs
index 1c39df7d94..24e6839be6 100644
--- a/src/mscorlib/src/System/Single.cs
+++ b/src/mscorlib/src/System/Single.cs
@@ -25,7 +25,7 @@ namespace System
public struct Single : IComparable, IFormattable, IConvertible
, IComparable<Single>, IEquatable<Single>
{
- internal float m_value;
+ private float m_value; // Do not rename (binary serialization)
//
// Public constants
diff --git a/src/mscorlib/src/System/StubHelpers.cs b/src/mscorlib/src/System/StubHelpers.cs
index f584ece6fc..716fa06a41 100644
--- a/src/mscorlib/src/System/StubHelpers.cs
+++ b/src/mscorlib/src/System/StubHelpers.cs
@@ -700,6 +700,17 @@ namespace System.StubHelpers
internal static class MngdNativeArrayMarshaler
{
+ // Needs to match exactly with MngdNativeArrayMarshaler in ilmarshalers.h
+ internal struct MarshalerState
+ {
+ IntPtr m_pElementMT;
+ IntPtr m_Array;
+ int m_NativeDataValid;
+ int m_BestFitMap;
+ int m_ThrowOnUnmappableChar;
+ short m_vt;
+ }
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags);
@@ -949,11 +960,21 @@ namespace System.StubHelpers
// Cleanup list to be destroyed when clearing the native view (for layouts with SafeHandles).
private CleanupWorkList cleanupWorkList;
- private static bool IsIn(int dwFlags) { return ((dwFlags & 0x10000000) != 0); }
- private static bool IsOut(int dwFlags) { return ((dwFlags & 0x20000000) != 0); }
- private static bool IsAnsi(int dwFlags) { return ((dwFlags & 0x00FF0000) != 0); }
- private static bool IsThrowOn(int dwFlags) { return ((dwFlags & 0x0000FF00) != 0); }
- private static bool IsBestFit(int dwFlags) { return ((dwFlags & 0x000000FF) != 0); }
+ [Flags]
+ internal enum AsAnyFlags
+ {
+ In = 0x10000000,
+ Out = 0x20000000,
+ IsAnsi = 0x00FF0000,
+ IsThrowOn = 0x0000FF00,
+ IsBestFit = 0x000000FF
+ }
+
+ private static bool IsIn(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.In) != 0); }
+ private static bool IsOut(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.Out) != 0); }
+ private static bool IsAnsi(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.IsAnsi) != 0); }
+ private static bool IsThrowOn(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.IsThrowOn) != 0); }
+ private static bool IsBestFit(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.IsBestFit) != 0); }
internal AsAnyMarshaler(IntPtr pvArrayMarshaler)
{
diff --git a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
index ad88ef4400..f70213f8d6 100644
--- a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
@@ -14,7 +14,6 @@ using System.Diagnostics.Contracts;
namespace System.Text
{
- [Serializable]
internal sealed class InternalDecoderBestFitFallback : DecoderFallback
{
// Our variables
diff --git a/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs b/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs
index b98ef74ed2..7a8db572d0 100644
--- a/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs
@@ -8,7 +8,6 @@ using System.Globalization;
namespace System.Text
{
- [Serializable]
public sealed class DecoderExceptionFallback : DecoderFallback
{
// Construction
@@ -99,7 +98,6 @@ namespace System.Text
}
// Exception for decoding unknown byte sequences.
- [Serializable]
public sealed class DecoderFallbackException : ArgumentException
{
private byte[] bytesUnknown = null;
@@ -125,6 +123,7 @@ namespace System.Text
internal DecoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
public DecoderFallbackException(
diff --git a/src/mscorlib/src/System/Text/DecoderFallback.cs b/src/mscorlib/src/System/Text/DecoderFallback.cs
index 9311cda585..2a56706b98 100644
--- a/src/mscorlib/src/System/Text/DecoderFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderFallback.cs
@@ -13,7 +13,6 @@ using System.Diagnostics.Contracts;
namespace System.Text
{
- [Serializable]
public abstract class DecoderFallback
{
internal bool bIsMicrosoftBestFitFallback = false;
diff --git a/src/mscorlib/src/System/Text/DecoderNLS.cs b/src/mscorlib/src/System/Text/DecoderNLS.cs
index 6fcfc79140..c2791e9227 100644
--- a/src/mscorlib/src/System/Text/DecoderNLS.cs
+++ b/src/mscorlib/src/System/Text/DecoderNLS.cs
@@ -21,7 +21,6 @@ namespace System.Text
// of Encoding objects.
//
- [Serializable]
internal class DecoderNLS : Decoder, ISerializable
{
// Remember our encoding
@@ -32,21 +31,10 @@ namespace System.Text
#region Serialization
- // Constructor called by serialization. called during deserialization.
- internal DecoderNLS(SerializationInfo info, StreamingContext context)
- {
- throw new NotSupportedException(
- String.Format(
- System.Globalization.CultureInfo.CurrentCulture,
- SR.NotSupported_TypeCannotDeserialized, this.GetType()));
- }
-
- // ISerializable implementation. called during serialization.
+ // ISerializable implementation.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- SerializeDecoder(info);
- info.AddValue("encoding", this.m_encoding);
- info.SetType(typeof(Encoding.DefaultDecoder));
+ throw new PlatformNotSupportedException();
}
#endregion Serialization
diff --git a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
index b27469156d..0eaca3de40 100644
--- a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
@@ -8,7 +8,6 @@ using System.Diagnostics.Contracts;
namespace System.Text
{
- [Serializable]
public sealed class DecoderReplacementFallback : DecoderFallback
{
// Our variables
diff --git a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
index eb3165526b..b007f57efe 100644
--- a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
@@ -15,7 +15,6 @@ using System.Diagnostics.Contracts;
namespace System.Text
{
- [Serializable]
internal sealed class InternalEncoderBestFitFallback : EncoderFallback
{
// Our variables
diff --git a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
index b75847d1e7..192ab78670 100644
--- a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
@@ -8,7 +8,6 @@ using System.Diagnostics.Contracts;
namespace System.Text
{
- [Serializable]
public sealed class EncoderExceptionFallback : EncoderFallback
{
// Construction
@@ -99,7 +98,6 @@ namespace System.Text
}
}
- [Serializable]
public sealed class EncoderFallbackException : ArgumentException
{
private char charUnknown;
@@ -125,10 +123,6 @@ namespace System.Text
HResult = __HResults.COR_E_ARGUMENT;
}
- internal EncoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- }
-
internal EncoderFallbackException(
String message, char charUnknown, int index) : base(message)
{
diff --git a/src/mscorlib/src/System/Text/EncoderFallback.cs b/src/mscorlib/src/System/Text/EncoderFallback.cs
index 410b6f5016..c3b9f47284 100644
--- a/src/mscorlib/src/System/Text/EncoderFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderFallback.cs
@@ -10,7 +10,6 @@ using System.Diagnostics.Contracts;
namespace System.Text
{
- [Serializable]
public abstract class EncoderFallback
{
// disable csharp compiler warning #0414: field assigned unused value
diff --git a/src/mscorlib/src/System/Text/EncoderNLS.cs b/src/mscorlib/src/System/Text/EncoderNLS.cs
index 99a26ca575..8a8c31ee2f 100644
--- a/src/mscorlib/src/System/Text/EncoderNLS.cs
+++ b/src/mscorlib/src/System/Text/EncoderNLS.cs
@@ -21,7 +21,6 @@ namespace System.Text
// of Encoding objects.
//
- [Serializable]
internal class EncoderNLS : Encoder, ISerializable
{
// Need a place for the last left over character, most of our encodings use this
@@ -35,22 +34,10 @@ namespace System.Text
#region Serialization
- // Constructor called by serialization. called during deserialization.
- internal EncoderNLS(SerializationInfo info, StreamingContext context)
- {
- throw new NotSupportedException(
- String.Format(
- System.Globalization.CultureInfo.CurrentCulture,
- SR.NotSupported_TypeCannotDeserialized, this.GetType()));
- }
-
- // ISerializable implementation. called during serialization.
+ // ISerializable implementation.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- SerializeEncoder(info);
- info.AddValue("encoding", this.m_encoding);
- info.AddValue("charLeftOver", this.charLeftOver);
- info.SetType(typeof(Encoding.DefaultEncoder));
+ throw new PlatformNotSupportedException();
}
#endregion Serialization
diff --git a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
index 65b807c1bd..a9ce9c10ef 100644
--- a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
@@ -9,7 +9,6 @@ using System.Diagnostics.Contracts;
namespace System.Text
{
- [Serializable]
public sealed class EncoderReplacementFallback : EncoderFallback
{
// Our variables
diff --git a/src/mscorlib/src/System/Text/Encoding.cs b/src/mscorlib/src/System/Text/Encoding.cs
index 159123495b..88eeb19d24 100644
--- a/src/mscorlib/src/System/Text/Encoding.cs
+++ b/src/mscorlib/src/System/Text/Encoding.cs
@@ -8,7 +8,6 @@ namespace System.Text
using System.Collections;
using System.Collections.Generic;
using System.Runtime;
- using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Globalization;
using System.Security;
@@ -82,7 +81,6 @@ namespace System.Text
// generally executes faster.
//
- [Serializable]
public abstract class Encoding : ICloneable
{
// For netcore we use UTF8 as default encoding since ANSI isn't available
@@ -1409,7 +1407,6 @@ namespace System.Text
decoder.ClearMustFlush();
}
- [Serializable]
internal sealed class DefaultEncoder : Encoder, IObjectReference, ISerializable
{
private Encoding m_encoding;
@@ -1422,60 +1419,16 @@ namespace System.Text
m_encoding = encoding;
m_hasInitializedEncoding = true;
}
-
- // Constructor called by serialization, have to handle deserializing from Everett
- internal DefaultEncoder(SerializationInfo info, StreamingContext context)
- {
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // All we have is our encoding
- m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
-
- try
- {
- this.m_fallback = (EncoderFallback)info.GetValue("m_fallback", typeof(EncoderFallback));
- this.charLeftOver = (Char)info.GetValue("charLeftOver", typeof(Char));
- }
- catch (SerializationException)
- {
- }
- }
-
- // Just get it from GetEncoding
+
public Object GetRealObject(StreamingContext context)
{
- // upon deserialization since the DefaultEncoder implement IObjectReference the
- // serialization code tries to do the fixup. The fixup returns another
- // IObjectReference (the DefaultEncoder) class and hence so on and on.
- // Finally the deserialization logics fails after following maximum references
- // unless we short circuit with the following
- if (m_hasInitializedEncoding)
- {
- return this;
- }
-
- Encoder encoder = m_encoding.GetEncoder();
- if (m_fallback != null)
- encoder.m_fallback = m_fallback;
- if (charLeftOver != (char)0)
- {
- EncoderNLS encoderNls = encoder as EncoderNLS;
- if (encoderNls != null)
- encoderNls.charLeftOver = charLeftOver;
- }
- return encoder;
+ throw new PlatformNotSupportedException();
}
// ISerializable implementation, get data for this object
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- // Any info?
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // All we have is our encoding
- info.AddValue("encoding", m_encoding);
+ throw new PlatformNotSupportedException();
}
// Returns the number of bytes the next call to GetBytes will
@@ -1531,7 +1484,6 @@ namespace System.Text
}
}
- [Serializable]
internal sealed class DefaultDecoder : Decoder, IObjectReference, ISerializable
{
private Encoding m_encoding;
@@ -1544,55 +1496,15 @@ namespace System.Text
m_hasInitializedEncoding = true;
}
- // Constructor called by serialization, have to handle deserializing from Everett
- internal DefaultDecoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // All we have is our encoding
- m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
-
- try
- {
- this.m_fallback = (DecoderFallback)info.GetValue("m_fallback", typeof(DecoderFallback));
- }
- catch (SerializationException)
- {
- m_fallback = null;
- }
- }
-
- // Just get it from GetEncoding
public Object GetRealObject(StreamingContext context)
{
- // upon deserialization since the DefaultEncoder implement IObjectReference the
- // serialization code tries to do the fixup. The fixup returns another
- // IObjectReference (the DefaultEncoder) class and hence so on and on.
- // Finally the deserialization logics fails after following maximum references
- // unless we short circuit with the following
- if (m_hasInitializedEncoding)
- {
- return this;
- }
-
- Decoder decoder = m_encoding.GetDecoder();
- if (m_fallback != null)
- decoder.m_fallback = m_fallback;
-
- return decoder;
+ throw new PlatformNotSupportedException();
}
- // ISerializable implementation, get data for this object
+ // ISerializable implementation
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- // Any info?
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // All we have is our encoding
- info.AddValue("encoding", m_encoding);
+ throw new PlatformNotSupportedException();
}
// Returns the number of characters the next call to GetChars will
diff --git a/src/mscorlib/src/System/Text/Latin1Encoding.cs b/src/mscorlib/src/System/Text/Latin1Encoding.cs
index e456b8533d..3f040b29ad 100644
--- a/src/mscorlib/src/System/Text/Latin1Encoding.cs
+++ b/src/mscorlib/src/System/Text/Latin1Encoding.cs
@@ -18,7 +18,6 @@ namespace System.Text
// Latin1Encoding is a simple override to optimize the GetString version of Latin1Encoding.
// because of the best fit cases we can't do this when encoding the string, only when decoding
//
- [Serializable]
internal class Latin1Encoding : EncodingNLS, ISerializable
{
// Used by Encoding.Latin1 for lazy initialization
@@ -30,30 +29,10 @@ namespace System.Text
{
}
- // Constructor called by serialization.
- // Note: We use the base GetObjectData however
- internal Latin1Encoding(SerializationInfo info, StreamingContext context) :
- base(Encoding.ISO_8859_1)
- {
- // Set up our base, also throws if info was empty
- DeserializeEncoding(info, context);
-
- // Nothing unique to Whidbey for Latin1
- }
-
- // ISerializable implementation, serialize it as a CodePageEncoding
+ // ISerializable implementation
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- // Make sure to get the base stuff too This throws if info is null
- SerializeEncoding(info, context);
- Debug.Assert(info != null, "[Latin1Encoding.GetObjectData] Expected null info to throw");
-
- // In Everett this is a CodePageEncoding, so it needs maxCharSize
- info.AddValue("CodePageEncoding+maxCharSize", 1);
-
- // And extras for Everett's wierdness
- info.AddValue("CodePageEncoding+m_codePage", this.CodePage);
- info.AddValue("CodePageEncoding+dataItem", null);
+ throw new PlatformNotSupportedException();
}
// GetByteCount
diff --git a/src/mscorlib/src/System/Text/UTF7Encoding.cs b/src/mscorlib/src/System/Text/UTF7Encoding.cs
index 372af0da37..0ac3b66889 100644
--- a/src/mscorlib/src/System/Text/UTF7Encoding.cs
+++ b/src/mscorlib/src/System/Text/UTF7Encoding.cs
@@ -13,7 +13,6 @@ using System.Diagnostics.Contracts;
namespace System.Text
{
- [Serializable]
public class UTF7Encoding : Encoding
{
private const String base64Chars =
@@ -832,7 +831,6 @@ namespace System.Text
return charCount;
}
- [Serializable]
// Of all the amazing things... This MUST be Decoder so that our com name
// for System.Text.Decoder doesn't change
private sealed class Decoder : DecoderNLS, ISerializable
@@ -849,32 +847,10 @@ namespace System.Text
// base calls reset
}
- // Constructor called by serialization, have to handle deserializing from Everett
- internal Decoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Get common info
- this.bits = (int)info.GetValue("bits", typeof(int));
- this.bitCount = (int)info.GetValue("bitCount", typeof(int));
- this.firstByte = (bool)info.GetValue("firstByte", typeof(bool));
- this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
- }
-
// ISerializable implementation, get data for this object
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- // Any info?
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Save Whidbey data
- info.AddValue("encoding", this.m_encoding);
- info.AddValue("bits", this.bits);
- info.AddValue("bitCount", this.bitCount);
- info.AddValue("firstByte", this.firstByte);
+ throw new PlatformNotSupportedException();
}
public override void Reset()
@@ -898,7 +874,6 @@ namespace System.Text
}
}
- [Serializable]
// Of all the amazing things... This MUST be Encoder so that our com name
// for System.Text.Encoder doesn't change
private sealed class Encoder : EncoderNLS, ISerializable
@@ -913,30 +888,10 @@ namespace System.Text
// base calls reset
}
- // Constructor called by serialization, have to handle deserializing from Everett
- internal Encoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Get common info
- this.bits = (int)info.GetValue("bits", typeof(int));
- this.bitCount = (int)info.GetValue("bitCount", typeof(int));
- this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
- }
-
- // ISerializable implementation, get data for this object
+ // ISerializable implementation
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- // Any info?
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Save Whidbey data
- info.AddValue("encoding", this.m_encoding);
- info.AddValue("bits", this.bits);
- info.AddValue("bitCount", this.bitCount);
+ throw new PlatformNotSupportedException();
}
public override void Reset()
@@ -959,7 +914,6 @@ namespace System.Text
// Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char
// and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback.
- [Serializable]
private sealed class DecoderUTF7Fallback : DecoderFallback
{
// Construction. Default replacement fallback uses no best fit and ? replacement string
diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Unix.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Unix.cs
new file mode 100644
index 0000000000..b7cdaa801c
--- /dev/null
+++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Unix.cs
@@ -0,0 +1,21 @@
+// 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
+{
+ public sealed partial class ThreadPoolBoundHandle
+ {
+ private static ThreadPoolBoundHandle BindHandleCore(SafeHandle handle)
+ {
+ Debug.Assert(handle != null);
+ Debug.Assert(!handle.IsClosed);
+ Debug.Assert(!handle.IsInvalid);
+
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs
new file mode 100644
index 0000000000..21c1c5f4a4
--- /dev/null
+++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs
@@ -0,0 +1,42 @@
+// 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
+{
+ public sealed partial class ThreadPoolBoundHandle
+ {
+ private static ThreadPoolBoundHandle BindHandleCore(SafeHandle handle)
+ {
+ Debug.Assert(handle != null);
+ Debug.Assert(!handle.IsClosed);
+ Debug.Assert(!handle.IsInvalid);
+
+ try
+ {
+ // ThreadPool.BindHandle will always return true, otherwise, it throws. See the underlying FCall
+ // implementation in ThreadPoolNative::CorBindIoCompletionCallback to see the implementation.
+ bool succeeded = ThreadPool.BindHandle(handle);
+ Debug.Assert(succeeded);
+ }
+ catch (Exception ex)
+ { // BindHandle throws ApplicationException on full CLR and Exception on CoreCLR.
+ // We do not let either of these leak and convert them to ArgumentException to
+ // indicate that the specified handles are invalid.
+
+ if (ex.HResult == System.HResults.E_HANDLE) // Bad handle
+ throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
+
+ if (ex.HResult == System.HResults.E_INVALIDARG) // Handle already bound or sync handle
+ throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle));
+
+ throw;
+ }
+
+ return new ThreadPoolBoundHandle(handle);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs
index d0cc5afbae..a4a3b980cf 100644
--- a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs
+++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs
@@ -83,28 +83,7 @@ namespace System.Threading
if (handle.IsClosed || handle.IsInvalid)
throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
- try
- {
- // ThreadPool.BindHandle will always return true, otherwise, it throws. See the underlying FCall
- // implementation in ThreadPoolNative::CorBindIoCompletionCallback to see the implementation.
- bool succeeded = ThreadPool.BindHandle(handle);
- Debug.Assert(succeeded);
- }
- catch (Exception ex)
- { // BindHandle throws ApplicationException on full CLR and Exception on CoreCLR.
- // We do not let either of these leak and convert them to ArgumentException to
- // indicate that the specified handles are invalid.
-
- if (ex.HResult == System.HResults.E_HANDLE) // Bad handle
- throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
-
- if (ex.HResult == System.HResults.E_INVALIDARG) // Handle already bound or sync handle
- throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle));
-
- throw;
- }
-
- return new ThreadPoolBoundHandle(handle);
+ return BindHandleCore(handle);
}
/// <summary>
diff --git a/src/mscorlib/src/System/Threading/Monitor.cs b/src/mscorlib/src/System/Threading/Monitor.cs
index 3ace3335aa..0df64a5e5c 100644
--- a/src/mscorlib/src/System/Threading/Monitor.cs
+++ b/src/mscorlib/src/System/Threading/Monitor.cs
@@ -17,7 +17,6 @@
using System;
using System.Runtime;
-using System.Runtime.Remoting;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
diff --git a/src/mscorlib/src/System/Threading/PinnableBufferCache.cs b/src/mscorlib/src/System/Threading/PinnableBufferCache.cs
new file mode 100644
index 0000000000..3f7853ce59
--- /dev/null
+++ b/src/mscorlib/src/System/Threading/PinnableBufferCache.cs
@@ -0,0 +1,544 @@
+// 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.
+#define ENABLE
+#define MINBUFFERS
+
+using System;
+using System.Runtime.InteropServices;
+using System.Runtime.ConstrainedExecution;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+using System.Threading;
+using System.Runtime.CompilerServices;
+using System.Diagnostics;
+
+#if PINNABLEBUFFERCACHE_MSCORLIB
+namespace System.Threading
+#else
+namespace System
+#endif
+{
+ internal sealed class PinnableBufferCache
+ {
+ /// <summary>
+ /// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData)
+ /// This is only used in mscorlib.
+ /// </summary>
+ internal PinnableBufferCache(string cacheName, Func<object> factory)
+ {
+ m_NotGen2 = new List<object>(DefaultNumberOfBuffers);
+ m_factory = factory;
+#if ENABLE
+ // Check to see if we should disable the cache.
+ string envVarName = "PinnableBufferCache_" + cacheName + "_Disabled";
+ try
+ {
+ string envVar = Environment.GetEnvironmentVariable(envVarName);
+ if (envVar != null)
+ {
+ PinnableBufferCacheEventSource.Log.DebugMessage("Creating " + cacheName + " PinnableBufferCacheDisabled=" + envVar);
+ int index = envVar.IndexOf(cacheName, StringComparison.OrdinalIgnoreCase);
+ if (0 <= index)
+ {
+ // The cache is disabled because we haven't set the cache name.
+ PinnableBufferCacheEventSource.Log.DebugMessage("Disabling " + cacheName);
+ return;
+ }
+ }
+ }
+ catch
+ {
+ // Ignore failures when reading the environment variable.
+ }
+#endif
+#if MINBUFFERS
+ // Allow the environment to specify a minimum buffer count.
+ string minEnvVarName = "PinnableBufferCache_" + cacheName + "_MinCount";
+ try
+ {
+ string minEnvVar = Environment.GetEnvironmentVariable(minEnvVarName);
+ if (minEnvVar != null)
+ {
+ if (int.TryParse(minEnvVar, out m_minBufferCount))
+ CreateNewBuffers();
+ }
+ }
+ catch
+ {
+ // Ignore failures when reading the environment variable.
+ }
+#endif
+
+ PinnableBufferCacheEventSource.Log.Create(cacheName);
+ m_CacheName = cacheName;
+ }
+
+ /// <summary>
+ /// Get a object from the buffer manager. If no buffers exist, allocate a new one.
+ /// </summary>
+ internal object Allocate()
+ {
+#if ENABLE
+ // Check to see whether or not the cache is disabled.
+ if (m_CacheName == null)
+ return m_factory();
+#endif
+ // Fast path, get it from our Gen2 aged m_FreeList.
+ object returnBuffer;
+ if (!m_FreeList.TryPop(out returnBuffer))
+ Restock(out returnBuffer);
+
+ // Computing free count is expensive enough that we don't want to compute it unless logging is on.
+ if (PinnableBufferCacheEventSource.Log.IsEnabled())
+ {
+ int numAllocCalls = Interlocked.Increment(ref m_numAllocCalls);
+ if (numAllocCalls >= 1024)
+ {
+ lock (this)
+ {
+ int previousNumAllocCalls = Interlocked.Exchange(ref m_numAllocCalls, 0);
+ if (previousNumAllocCalls >= 1024)
+ {
+ int nonGen2Count = 0;
+ foreach (object o in m_FreeList)
+ {
+ if (GC.GetGeneration(o) < GC.MaxGeneration)
+ {
+ nonGen2Count++;
+ }
+ }
+
+ PinnableBufferCacheEventSource.Log.WalkFreeListResult(m_CacheName, m_FreeList.Count, nonGen2Count);
+ }
+ }
+ }
+
+ PinnableBufferCacheEventSource.Log.AllocateBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(returnBuffer), returnBuffer.GetHashCode(), GC.GetGeneration(returnBuffer), m_FreeList.Count);
+ }
+ return returnBuffer;
+ }
+
+ /// <summary>
+ /// Return a buffer back to the buffer manager.
+ /// </summary>
+ internal void Free(object buffer)
+ {
+#if ENABLE
+ // Check to see whether or not the cache is disabled.
+ if (m_CacheName == null)
+ return;
+#endif
+ if (PinnableBufferCacheEventSource.Log.IsEnabled())
+ PinnableBufferCacheEventSource.Log.FreeBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(buffer), buffer.GetHashCode(), m_FreeList.Count);
+
+
+ // After we've done 3 gen1 GCs, assume that all buffers have aged into gen2 on the free path.
+ if ((m_gen1CountAtLastRestock + 3) > GC.CollectionCount(GC.MaxGeneration - 1))
+ {
+ lock (this)
+ {
+ if (GC.GetGeneration(buffer) < GC.MaxGeneration)
+ {
+ // The buffer is not aged, so put it in the non-aged free list.
+ m_moreThanFreeListNeeded = true;
+ PinnableBufferCacheEventSource.Log.FreeBufferStillTooYoung(m_CacheName, m_NotGen2.Count);
+ m_NotGen2.Add(buffer);
+ m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1);
+ return;
+ }
+ }
+ }
+
+ // If we discovered that it is indeed Gen2, great, put it in the Gen2 list.
+ m_FreeList.Push(buffer);
+ }
+
+ #region Private
+
+ /// <summary>
+ /// Called when we don't have any buffers in our free list to give out.
+ /// </summary>
+ /// <returns></returns>
+ private void Restock(out object returnBuffer)
+ {
+ lock (this)
+ {
+ // Try again after getting the lock as another thread could have just filled the free list. If we don't check
+ // then we unnecessarily grab a new set of buffers because we think we are out.
+ if (m_FreeList.TryPop(out returnBuffer))
+ return;
+
+ // Lazy init, Ask that TrimFreeListIfNeeded be called on every Gen 2 GC.
+ if (m_restockSize == 0)
+ Gen2GcCallback.Register(Gen2GcCallbackFunc, this);
+
+ // Indicate to the trimming policy that the free list is insufficent.
+ m_moreThanFreeListNeeded = true;
+ PinnableBufferCacheEventSource.Log.AllocateBufferFreeListEmpty(m_CacheName, m_NotGen2.Count);
+
+ // Get more buffers if needed.
+ if (m_NotGen2.Count == 0)
+ CreateNewBuffers();
+
+ // We have no buffers in the aged freelist, so get one from the newer list. Try to pick the best one.
+ // Debug.Assert(m_NotGen2.Count != 0);
+ int idx = m_NotGen2.Count - 1;
+ if (GC.GetGeneration(m_NotGen2[idx]) < GC.MaxGeneration && GC.GetGeneration(m_NotGen2[0]) == GC.MaxGeneration)
+ idx = 0;
+ returnBuffer = m_NotGen2[idx];
+ m_NotGen2.RemoveAt(idx);
+
+ // Remember any sub-optimial buffer so we don't put it on the free list when it gets freed.
+ if (PinnableBufferCacheEventSource.Log.IsEnabled() && GC.GetGeneration(returnBuffer) < GC.MaxGeneration)
+ {
+ PinnableBufferCacheEventSource.Log.AllocateBufferFromNotGen2(m_CacheName, m_NotGen2.Count);
+ }
+
+ // If we have a Gen1 collection, then everything on m_NotGen2 should have aged. Move them to the m_Free list.
+ if (!AgePendingBuffers())
+ {
+ // Before we could age at set of buffers, we have handed out half of them.
+ // This implies we should be proactive about allocating more (since we will trim them if we over-allocate).
+ if (m_NotGen2.Count == m_restockSize / 2)
+ {
+ PinnableBufferCacheEventSource.Log.DebugMessage("Proactively adding more buffers to aging pool");
+ CreateNewBuffers();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// See if we can promote the buffers to the free list. Returns true if sucessful.
+ /// </summary>
+ private bool AgePendingBuffers()
+ {
+ if (m_gen1CountAtLastRestock < GC.CollectionCount(GC.MaxGeneration - 1))
+ {
+ // Allocate a temp list of buffers that are not actually in gen2, and swap it in once
+ // we're done scanning all buffers.
+ int promotedCount = 0;
+ List<object> notInGen2 = new List<object>();
+ PinnableBufferCacheEventSource.Log.AllocateBufferAged(m_CacheName, m_NotGen2.Count);
+ for (int i = 0; i < m_NotGen2.Count; i++)
+ {
+ // We actually check every object to ensure that we aren't putting non-aged buffers into the free list.
+ object currentBuffer = m_NotGen2[i];
+ if (GC.GetGeneration(currentBuffer) >= GC.MaxGeneration)
+ {
+ m_FreeList.Push(currentBuffer);
+ promotedCount++;
+ }
+ else
+ {
+ notInGen2.Add(currentBuffer);
+ }
+ }
+ PinnableBufferCacheEventSource.Log.AgePendingBuffersResults(m_CacheName, promotedCount, notInGen2.Count);
+ m_NotGen2 = notInGen2;
+
+ return true;
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// Generates some buffers to age into Gen2.
+ /// </summary>
+ private void CreateNewBuffers()
+ {
+ // We choose a very modest number of buffers initially because for the client case. This is often enough.
+ if (m_restockSize == 0)
+ m_restockSize = 4;
+ else if (m_restockSize < DefaultNumberOfBuffers)
+ m_restockSize = DefaultNumberOfBuffers;
+ else if (m_restockSize < 256)
+ m_restockSize = m_restockSize * 2; // Grow quickly at small sizes
+ else if (m_restockSize < 4096)
+ m_restockSize = m_restockSize * 3 / 2; // Less agressively at large ones
+ else
+ m_restockSize = 4096; // Cap how agressive we are
+
+ // Ensure we hit our minimums
+ if (m_minBufferCount > m_buffersUnderManagement)
+ m_restockSize = Math.Max(m_restockSize, m_minBufferCount - m_buffersUnderManagement);
+
+ PinnableBufferCacheEventSource.Log.AllocateBufferCreatingNewBuffers(m_CacheName, m_buffersUnderManagement, m_restockSize);
+ for (int i = 0; i < m_restockSize; i++)
+ {
+ // Make a new buffer.
+ object newBuffer = m_factory();
+
+ // Create space between the objects. We do this because otherwise it forms a single plug (group of objects)
+ // and the GC pins the entire plug making them NOT move to Gen1 and Gen2. by putting space between them
+ // we ensure that object get a chance to move independently (even if some are pinned).
+ var dummyObject = new object();
+ m_NotGen2.Add(newBuffer);
+ }
+ m_buffersUnderManagement += m_restockSize;
+ m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1);
+ }
+
+ /// <summary>
+ /// This is the static function that is called from the gen2 GC callback.
+ /// The input object is the cache itself.
+ /// NOTE: The reason that we make this functionstatic and take the cache as a parameter is that
+ /// otherwise, we root the cache to the Gen2GcCallback object, and leak the cache even when
+ /// the application no longer needs it.
+ /// </summary>
+ private static bool Gen2GcCallbackFunc(object targetObj)
+ {
+ return ((PinnableBufferCache)(targetObj)).TrimFreeListIfNeeded();
+ }
+
+ /// <summary>
+ /// This is called on every gen2 GC to see if we need to trim the free list.
+ /// NOTE: DO NOT CALL THIS DIRECTLY FROM THE GEN2GCCALLBACK. INSTEAD CALL IT VIA A STATIC FUNCTION (SEE ABOVE).
+ /// If you register a non-static function as a callback, then this object will be leaked.
+ /// </summary>
+ private bool TrimFreeListIfNeeded()
+ {
+ int curMSec = Environment.TickCount;
+ int deltaMSec = curMSec - m_msecNoUseBeyondFreeListSinceThisTime;
+ PinnableBufferCacheEventSource.Log.TrimCheck(m_CacheName, m_buffersUnderManagement, m_moreThanFreeListNeeded, deltaMSec);
+
+ // If we needed more than just the set of aged buffers since the last time we were called,
+ // we obviously should not be trimming any memory, so do nothing except reset the flag
+ if (m_moreThanFreeListNeeded)
+ {
+ m_moreThanFreeListNeeded = false;
+ m_trimmingExperimentInProgress = false;
+ m_msecNoUseBeyondFreeListSinceThisTime = curMSec;
+ return true;
+ }
+
+ // We require a minimum amount of clock time to pass (10 seconds) before we trim. Ideally this time
+ // is larger than the typical buffer hold time.
+ if (0 <= deltaMSec && deltaMSec < 10000)
+ return true;
+
+ // If we got here we have spend the last few second without needing to lengthen the free list. Thus
+ // we have 'enough' buffers, but maybe we have too many.
+ // See if we can trim
+ lock (this)
+ {
+ // Hit a race, try again later.
+ if (m_moreThanFreeListNeeded)
+ {
+ m_moreThanFreeListNeeded = false;
+ m_trimmingExperimentInProgress = false;
+ m_msecNoUseBeyondFreeListSinceThisTime = curMSec;
+ return true;
+ }
+
+ var freeCount = m_FreeList.Count; // This is expensive to fetch, do it once.
+
+ // If there is something in m_NotGen2 it was not used for the last few seconds, it is trimable.
+ if (m_NotGen2.Count > 0)
+ {
+ // If we are not performing an experiment and we have stuff that is waiting to go into the
+ // free list but has not made it there, it could be becasue the 'slow path' of restocking
+ // has not happened, so force this (which should flush the list) and start over.
+ if (!m_trimmingExperimentInProgress)
+ {
+ PinnableBufferCacheEventSource.Log.TrimFlush(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count);
+ AgePendingBuffers();
+ m_trimmingExperimentInProgress = true;
+ return true;
+ }
+
+ PinnableBufferCacheEventSource.Log.TrimFree(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count);
+ m_buffersUnderManagement -= m_NotGen2.Count;
+
+ // Possibly revise the restocking down. We don't want to grow agressively if we are trimming.
+ var newRestockSize = m_buffersUnderManagement / 4;
+ if (newRestockSize < m_restockSize)
+ m_restockSize = Math.Max(newRestockSize, DefaultNumberOfBuffers);
+
+ m_NotGen2.Clear();
+ m_trimmingExperimentInProgress = false;
+ return true;
+ }
+
+ // Set up an experiment where we use 25% less buffers in our free list. We put them in
+ // m_NotGen2, and if they are needed they will be put back in the free list again.
+ var trimSize = freeCount / 4 + 1;
+
+ // We are OK with a 15% overhead, do nothing in that case.
+ if (freeCount * 15 <= m_buffersUnderManagement || m_buffersUnderManagement - trimSize <= m_minBufferCount)
+ {
+ PinnableBufferCacheEventSource.Log.TrimFreeSizeOK(m_CacheName, m_buffersUnderManagement, freeCount);
+ return true;
+ }
+
+ // Move buffers from the free list back to the non-aged list. If we don't use them by next time, then we'll consider trimming them.
+ PinnableBufferCacheEventSource.Log.TrimExperiment(m_CacheName, m_buffersUnderManagement, freeCount, trimSize);
+ object buffer;
+ for (int i = 0; i < trimSize; i++)
+ {
+ if (m_FreeList.TryPop(out buffer))
+ m_NotGen2.Add(buffer);
+ }
+ m_msecNoUseBeyondFreeListSinceThisTime = curMSec;
+ m_trimmingExperimentInProgress = true;
+ }
+
+ // Indicate that we want to be called back on the next Gen 2 GC.
+ return true;
+ }
+
+ private const int DefaultNumberOfBuffers = 16;
+ private string m_CacheName;
+ private Func<object> m_factory;
+
+ /// <summary>
+ /// Contains 'good' buffers to reuse. They are guarenteed to be Gen 2 ENFORCED!
+ /// </summary>
+ private ConcurrentStack<object> m_FreeList = new ConcurrentStack<object>();
+ /// <summary>
+ /// Contains buffers that are not gen 2 and thus we do not wish to give out unless we have to.
+ /// To implement trimming we sometimes put aged buffers in here as a place to 'park' them
+ /// before true deletion.
+ /// </summary>
+ private List<object> m_NotGen2;
+ /// <summary>
+ /// What whas the gen 1 count the last time re restocked? If it is now greater, then
+ /// we know that all objects are in Gen 2 so we don't have to check. Should be updated
+ /// every time something gets added to the m_NotGen2 list.
+ /// </summary>
+ private int m_gen1CountAtLastRestock;
+
+ /// <summary>
+ /// Used to ensure we have a minimum time between trimmings.
+ /// </summary>
+ private int m_msecNoUseBeyondFreeListSinceThisTime;
+ /// <summary>
+ /// To trim, we remove things from the free list (which is Gen 2) and see if we 'hit bottom'
+ /// This flag indicates that we hit bottom (we really needed a bigger free list).
+ /// </summary>
+ private bool m_moreThanFreeListNeeded;
+ /// <summary>
+ /// The total number of buffers that this cache has ever allocated.
+ /// Used in trimming heuristics.
+ /// </summary>
+ private int m_buffersUnderManagement;
+ /// <summary>
+ /// The number of buffers we added the last time we restocked.
+ /// </summary>
+ private int m_restockSize;
+ /// <summary>
+ /// Did we put some buffers into m_NotGen2 to see if we can trim?
+ /// </summary>
+ private bool m_trimmingExperimentInProgress;
+ /// <summary>
+ /// A forced minimum number of buffers.
+ /// </summary>
+ private int m_minBufferCount;
+ /// <summary>
+ /// The number of calls to Allocate.
+ /// </summary>
+ private int m_numAllocCalls;
+
+ #endregion
+ }
+
+ /// <summary>
+ /// Schedules a callback roughly every gen 2 GC (you may see a Gen 0 an Gen 1 but only once)
+ /// (We can fix this by capturing the Gen 2 count at startup and testing, but I mostly don't care)
+ /// </summary>
+ internal sealed class Gen2GcCallback : CriticalFinalizerObject
+ {
+ public Gen2GcCallback()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// Schedule 'callback' to be called in the next GC. If the callback returns true it is
+ /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop.
+ ///
+ /// NOTE: This callback will be kept alive until either the callback function returns false,
+ /// or the target object dies.
+ /// </summary>
+ public static void Register(Func<object, bool> callback, object targetObj)
+ {
+ // Create a unreachable object that remembers the callback function and target object.
+ Gen2GcCallback gcCallback = new Gen2GcCallback();
+ gcCallback.Setup(callback, targetObj);
+ }
+
+ #region Private
+
+ private Func<object, bool> m_callback;
+ private GCHandle m_weakTargetObj;
+
+ private void Setup(Func<object, bool> callback, object targetObj)
+ {
+ m_callback = callback;
+ m_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak);
+ }
+
+ ~Gen2GcCallback()
+ {
+ // Check to see if the target object is still alive.
+ object targetObj = m_weakTargetObj.Target;
+ if (targetObj == null)
+ {
+ // The target object is dead, so this callback object is no longer needed.
+ m_weakTargetObj.Free();
+ return;
+ }
+
+ // Execute the callback method.
+ try
+ {
+ if (!m_callback(targetObj))
+ {
+ // If the callback returns false, this callback object is no longer needed.
+ return;
+ }
+ }
+ catch
+ {
+ // Ensure that we still get a chance to resurrect this object, even if the callback throws an exception.
+ }
+
+ // Resurrect ourselves by re-registering for finalization.
+ if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload())
+ {
+ GC.ReRegisterForFinalize(this);
+ }
+ }
+
+ #endregion
+ }
+
+ internal sealed class PinnableBufferCacheEventSource
+ {
+ public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource();
+
+ public bool IsEnabled() { return false; }
+ public void DebugMessage(string message) { }
+ public void Create(string cacheName) { }
+ public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { }
+ public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { }
+ public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { }
+ public void AllocateBufferAged(string cacheName, int agedCount) { }
+ public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { }
+ public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { }
+ public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { }
+ public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { }
+ public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { }
+ public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { }
+ public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { }
+ public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { }
+ public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { }
+ public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { }
+
+ static internal ulong AddressOf(object obj)
+ {
+ return 0;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs
index 0a9248cba8..07d126179c 100644
--- a/src/mscorlib/src/System/Threading/Tasks/Task.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs
@@ -6254,7 +6254,6 @@ namespace System.Threading.Tasks
// NOTE: These options are a subset of TaskContinuationsOptions, thus before adding a flag check it is
// not already in use.
[Flags]
- [Serializable]
public enum TaskCreationOptions
{
/// <summary>
@@ -6306,7 +6305,6 @@ namespace System.Threading.Tasks
/// Task creation flags which are only used internally.
/// </summary>
[Flags]
- [Serializable]
internal enum InternalTaskOptions
{
/// <summary> Specifies "No internal task options" </summary>
@@ -6338,7 +6336,6 @@ namespace System.Threading.Tasks
/// Specifies flags that control optional behavior for the creation and execution of continuation tasks.
/// </summary>
[Flags]
- [Serializable]
public enum TaskContinuationOptions
{
/// <summary>
diff --git a/src/mscorlib/src/System/Threading/Thread.cs b/src/mscorlib/src/System/Threading/Thread.cs
index 70a5d06f7a..fab6c9e187 100644
--- a/src/mscorlib/src/System/Threading/Thread.cs
+++ b/src/mscorlib/src/System/Threading/Thread.cs
@@ -555,7 +555,6 @@ 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
- [Serializable]
internal enum StackCrawlMark
{
LookForMe = 0,
diff --git a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
index 9122df0d3e..fb72110fdc 100644
--- a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
@@ -19,7 +19,6 @@ using System.Runtime.Serialization;
namespace System.Threading
{
- [Serializable]
public class ThreadInterruptedException : SystemException
{
public ThreadInterruptedException()
@@ -42,6 +41,7 @@ namespace System.Threading
protected ThreadInterruptedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/src/System/Threading/Timer.cs b/src/mscorlib/src/System/Threading/Timer.cs
index 960f815d64..a5c7945864 100644
--- a/src/mscorlib/src/System/Threading/Timer.cs
+++ b/src/mscorlib/src/System/Threading/Timer.cs
@@ -265,7 +265,19 @@ namespace System.Threading
if (timer.m_period != Timeout.UnsignedInfinite)
{
timer.m_startTicks = nowTicks;
- timer.m_dueTime = timer.m_period;
+ uint elapsedForNextDueTime = elapsed - timer.m_dueTime;
+ if (elapsedForNextDueTime < timer.m_period)
+ {
+ // Discount the extra amount of time that has elapsed since the previous firing time to
+ // prevent timer ticks from drifting
+ timer.m_dueTime = timer.m_period - elapsedForNextDueTime;
+ }
+ else
+ {
+ // Enough time has elapsed to fire the timer yet again. The timer is not able to keep up
+ // with the short period, have it fire 1 ms from now to avoid spinning without a delay.
+ timer.m_dueTime = 1;
+ }
//
// This is a repeating timer; schedule it to run again.
diff --git a/src/mscorlib/src/System/Threading/WaitHandle.cs b/src/mscorlib/src/System/Threading/WaitHandle.cs
index f3412d264f..da4856ee96 100644
--- a/src/mscorlib/src/System/Threading/WaitHandle.cs
+++ b/src/mscorlib/src/System/Threading/WaitHandle.cs
@@ -15,7 +15,6 @@
namespace System.Threading
{
using System.Threading;
- using System.Runtime.Remoting;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
diff --git a/src/mscorlib/src/System/TypeLoadException.cs b/src/mscorlib/src/System/TypeLoadException.cs
index 85e1da5920..5e748a6c58 100644
--- a/src/mscorlib/src/System/TypeLoadException.cs
+++ b/src/mscorlib/src/System/TypeLoadException.cs
@@ -13,7 +13,6 @@
using System;
using System.Globalization;
-using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
@@ -23,7 +22,6 @@ using System.Diagnostics.Contracts;
namespace System
{
- [Serializable]
public class TypeLoadException : SystemException, ISerializable
{
public TypeLoadException()
@@ -106,33 +104,16 @@ namespace System
protected TypeLoadException(SerializationInfo info, StreamingContext context) : base(info, context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- ClassName = info.GetString("TypeLoadClassName");
- AssemblyName = info.GetString("TypeLoadAssemblyName");
- MessageArg = info.GetString("TypeLoadMessageArg");
- ResourceId = info.GetInt32("TypeLoadResourceID");
+ throw new PlatformNotSupportedException();
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetTypeLoadExceptionMessage(int resourceId, StringHandleOnStack retString);
- //We can rely on the serialization mechanism on Exception to handle most of our needs, but
- //we need to add a few fields of our own.
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
base.GetObjectData(info, context);
- info.AddValue("TypeLoadClassName", ClassName, typeof(String));
- info.AddValue("TypeLoadAssemblyName", AssemblyName, typeof(String));
- info.AddValue("TypeLoadMessageArg", MessageArg, typeof(String));
- info.AddValue("TypeLoadResourceID", ResourceId);
}
// If ClassName != null, GetMessage will construct on the fly using it
diff --git a/src/mscorlib/src/System/UInt16.cs b/src/mscorlib/src/System/UInt16.cs
index e4a6837ae2..c7be2e9a1f 100644
--- a/src/mscorlib/src/System/UInt16.cs
+++ b/src/mscorlib/src/System/UInt16.cs
@@ -24,7 +24,7 @@ namespace System
public struct UInt16 : IComparable, IFormattable, IConvertible
, IComparable<UInt16>, IEquatable<UInt16>
{
- private ushort m_value;
+ private ushort m_value; // Do not rename (binary serialization)
public const ushort MaxValue = (ushort)0xFFFF;
public const ushort MinValue = 0;
diff --git a/src/mscorlib/src/System/UInt32.cs b/src/mscorlib/src/System/UInt32.cs
index 7c27efef39..2731047e06 100644
--- a/src/mscorlib/src/System/UInt32.cs
+++ b/src/mscorlib/src/System/UInt32.cs
@@ -26,7 +26,7 @@ namespace System
public struct UInt32 : IComparable, IFormattable, IConvertible
, IComparable<UInt32>, IEquatable<UInt32>
{
- private uint m_value;
+ private uint m_value; // Do not rename (binary serialization)
public const uint MaxValue = (uint)0xffffffff;
public const uint MinValue = 0U;
diff --git a/src/mscorlib/src/System/UInt64.cs b/src/mscorlib/src/System/UInt64.cs
index 0b79b6a7d8..a54bb69ba4 100644
--- a/src/mscorlib/src/System/UInt64.cs
+++ b/src/mscorlib/src/System/UInt64.cs
@@ -24,7 +24,7 @@ namespace System
public struct UInt64 : IComparable, IFormattable, IConvertible
, IComparable<UInt64>, IEquatable<UInt64>
{
- private ulong m_value;
+ private ulong m_value; // Do not rename (binary serialization)
public const ulong MaxValue = (ulong)0xffffffffffffffffL;
public const ulong MinValue = 0x0;
diff --git a/src/mscorlib/src/System/UIntPtr.cs b/src/mscorlib/src/System/UIntPtr.cs
index 09b7e51e89..08e494297b 100644
--- a/src/mscorlib/src/System/UIntPtr.cs
+++ b/src/mscorlib/src/System/UIntPtr.cs
@@ -23,7 +23,7 @@ namespace System
[CLSCompliant(false)]
public struct UIntPtr : IEquatable<UIntPtr>, ISerializable
{
- unsafe private void* m_value;
+ unsafe private void* _value;
public static readonly UIntPtr Zero;
@@ -31,16 +31,16 @@ namespace System
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(uint value)
{
- m_value = (void*)value;
+ _value = (void*)value;
}
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if BIT64
- m_value = (void*)value;
+ _value = (void*)value;
#else // 32
- m_value = (void*)checked((uint)value);
+ _value = (void*)checked((uint)value);
#endif
}
@@ -48,7 +48,7 @@ namespace System
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(void* value)
{
- m_value = value;
+ _value = value;
}
private unsafe UIntPtr(SerializationInfo info, StreamingContext context)
@@ -60,7 +60,7 @@ namespace System
throw new ArgumentException(SR.Serialization_InvalidPtrValue);
}
- m_value = (void*)l;
+ _value = (void*)l;
}
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
@@ -70,30 +70,30 @@ namespace System
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
- info.AddValue("value", (ulong)m_value);
+ info.AddValue("value", (ulong)_value);
}
public unsafe override bool Equals(Object obj)
{
if (obj is UIntPtr)
{
- return (m_value == ((UIntPtr)obj).m_value);
+ return (_value == ((UIntPtr)obj)._value);
}
return false;
}
unsafe bool IEquatable<UIntPtr>.Equals(UIntPtr other)
{
- return m_value == other.m_value;
+ return _value == other._value;
}
public unsafe override int GetHashCode()
{
#if BIT64
- ulong l = (ulong)m_value;
+ ulong l = (ulong)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else // 32
- return unchecked((int)m_value);
+ return unchecked((int)_value);
#endif
}
@@ -101,16 +101,16 @@ namespace System
public unsafe uint ToUInt32()
{
#if BIT64
- return checked((uint)m_value);
+ return checked((uint)_value);
#else // 32
- return (uint)m_value;
+ return (uint)_value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
public unsafe ulong ToUInt64()
{
- return (ulong)m_value;
+ return (ulong)_value;
}
public unsafe override String ToString()
@@ -118,9 +118,9 @@ namespace System
Contract.Ensures(Contract.Result<String>() != null);
#if BIT64
- return ((ulong)m_value).ToString(CultureInfo.InvariantCulture);
+ return ((ulong)_value).ToString(CultureInfo.InvariantCulture);
#else // 32
- return ((uint)m_value).ToString(CultureInfo.InvariantCulture);
+ return ((uint)_value).ToString(CultureInfo.InvariantCulture);
#endif
}
@@ -140,16 +140,16 @@ namespace System
public unsafe static explicit operator uint(UIntPtr value)
{
#if BIT64
- return checked((uint)value.m_value);
+ return checked((uint)value._value);
#else // 32
- return (uint)value.m_value;
+ return (uint)value._value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator ulong(UIntPtr value)
{
- return (ulong)value.m_value;
+ return (ulong)value._value;
}
[CLSCompliant(false)]
@@ -163,21 +163,21 @@ namespace System
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
{
- return value.m_value;
+ return value._value;
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator ==(UIntPtr value1, UIntPtr value2)
{
- return value1.m_value == value2.m_value;
+ return value1._value == value2._value;
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator !=(UIntPtr value1, UIntPtr value2)
{
- return value1.m_value != value2.m_value;
+ return value1._value != value2._value;
}
[System.Runtime.Versioning.NonVersionable]
@@ -229,7 +229,7 @@ namespace System
[System.Runtime.Versioning.NonVersionable]
public unsafe void* ToPointer()
{
- return m_value;
+ return _value;
}
}
}
diff --git a/src/mscorlib/src/System/Variant.cs b/src/mscorlib/src/System/Variant.cs
index cae5bdade4..b468ab2f98 100644
--- a/src/mscorlib/src/System/Variant.cs
+++ b/src/mscorlib/src/System/Variant.cs
@@ -23,7 +23,6 @@ using System.Diagnostics.Contracts;
namespace System
{
- [Serializable]
[StructLayout(LayoutKind.Sequential)]
internal struct Variant
{
diff --git a/src/mscorlib/src/System/__HResults.cs b/src/mscorlib/src/System/__HResults.cs
index e4183f637a..0592d814ef 100644
--- a/src/mscorlib/src/System/__HResults.cs
+++ b/src/mscorlib/src/System/__HResults.cs
@@ -44,6 +44,7 @@ namespace System
internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216);
internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503);
internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B);
+ internal const int COR_E_BADEXEFORMAT = unchecked((int)0x800700C1);
internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013);
internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015);
internal const int COR_E_COMEMULATE = unchecked((int)0x80131535);