summaryrefslogtreecommitdiff
path: root/src/mscorlib/shared/System
diff options
context:
space:
mode:
Diffstat (limited to 'src/mscorlib/shared/System')
-rw-r--r--src/mscorlib/shared/System/ApplicationException.cs6
-rw-r--r--src/mscorlib/shared/System/ArgumentException.cs4
-rw-r--r--src/mscorlib/shared/System/ArgumentNullException.cs6
-rw-r--r--src/mscorlib/shared/System/ArgumentOutOfRangeException.cs97
-rw-r--r--src/mscorlib/shared/System/ArithmeticException.cs6
-rw-r--r--src/mscorlib/shared/System/ArrayTypeMismatchException.cs6
-rw-r--r--src/mscorlib/shared/System/AsyncCallback.cs1
-rw-r--r--src/mscorlib/shared/System/AttributeTargets.cs1
-rw-r--r--src/mscorlib/shared/System/AttributeUsageAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/BadImageFormatException.cs124
-rw-r--r--src/mscorlib/shared/System/CLSCompliantAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Char.cs2
-rw-r--r--src/mscorlib/shared/System/CharEnumerator.cs1
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs6
-rw-r--r--src/mscorlib/shared/System/CurrentSystemTimeZone.cs1
-rw-r--r--src/mscorlib/shared/System/DBNull.cs10
-rw-r--r--src/mscorlib/shared/System/DataMisalignedException.cs3
-rw-r--r--src/mscorlib/shared/System/DateTimeKind.cs1
-rw-r--r--src/mscorlib/shared/System/DayOfWeek.cs1
-rw-r--r--src/mscorlib/shared/System/DefaultBinder.cs2
-rw-r--r--src/mscorlib/shared/System/Diagnostics/ConditionalAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Debug.Unix.cs95
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs135
-rwxr-xr-x[-rw-r--r--]src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs172
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventSourceException.cs4
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/IEventProvider.cs42
-rw-r--r--src/mscorlib/shared/System/DivideByZeroException.cs6
-rw-r--r--src/mscorlib/shared/System/DllNotFoundException.cs44
-rw-r--r--src/mscorlib/shared/System/DuplicateWaitObjectException.cs9
-rw-r--r--src/mscorlib/shared/System/EntryPointNotFoundException.cs6
-rw-r--r--src/mscorlib/shared/System/EventArgs.cs1
-rw-r--r--src/mscorlib/shared/System/EventHandler.cs2
-rw-r--r--src/mscorlib/shared/System/ExecutionEngineException.cs3
-rw-r--r--src/mscorlib/shared/System/FieldAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/FlagsAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/FormatException.cs6
-rw-r--r--src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs348
-rw-r--r--src/mscorlib/shared/System/Globalization/CalendarWeekRule.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/CultureData.Unix.cs431
-rw-r--r--src/mscorlib/shared/System/Globalization/CultureNotFoundException.cs6
-rw-r--r--src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/DaylightTime.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/GregorianCalendarTypes.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/HebrewCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/HijriCalendar.Unix.cs15
-rw-r--r--src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs96
-rw-r--r--src/mscorlib/shared/System/Globalization/HijriCalendar.WinRT.cs16
-rw-r--r--src/mscorlib/shared/System/Globalization/HijriCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/IdnMapping.Unix.cs142
-rw-r--r--src/mscorlib/shared/System/Globalization/JapaneseCalendar.Unix.cs96
-rw-r--r--src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs209
-rw-r--r--src/mscorlib/shared/System/Globalization/JapaneseCalendar.WinRT.cs62
-rw-r--r--src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/JulianCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/KoreanCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs899
-rw-r--r--src/mscorlib/shared/System/Globalization/PersianCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/SortKey.cs202
-rw-r--r--src/mscorlib/shared/System/Globalization/SortVersion.cs20
-rw-r--r--src/mscorlib/shared/System/Globalization/StringInfo.cs373
-rw-r--r--src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs1
-rw-r--r--src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs2
-rw-r--r--src/mscorlib/shared/System/IO/EncodingCache.cs13
-rw-r--r--src/mscorlib/shared/System/IO/EndOfStreamException.cs2
-rw-r--r--src/mscorlib/shared/System/IO/FileAccess.cs1
-rw-r--r--src/mscorlib/shared/System/IO/FileLoadException.cs11
-rw-r--r--src/mscorlib/shared/System/IO/FileNotFoundException.cs11
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.Win32.cs13
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.WinRT.cs20
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.Windows.cs8
-rw-r--r--src/mscorlib/shared/System/IO/Path.Unix.cs9
-rw-r--r--src/mscorlib/shared/System/IO/Path.Windows.cs6
-rw-r--r--src/mscorlib/shared/System/IO/Path.cs24
-rw-r--r--src/mscorlib/shared/System/IO/PathInternal.Unix.cs5
-rw-r--r--src/mscorlib/shared/System/IO/PathInternal.Windows.cs5
-rw-r--r--src/mscorlib/shared/System/IO/PathTooLongException.cs2
-rw-r--r--src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs64
-rw-r--r--src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs763
-rw-r--r--src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs210
-rw-r--r--src/mscorlib/shared/System/IndexOutOfRangeException.cs3
-rw-r--r--src/mscorlib/shared/System/InsufficientExecutionStackException.cs3
-rw-r--r--src/mscorlib/shared/System/InvalidCastException.cs6
-rw-r--r--src/mscorlib/shared/System/InvalidOperationException.cs6
-rw-r--r--src/mscorlib/shared/System/InvalidProgramException.cs3
-rw-r--r--src/mscorlib/shared/System/InvalidTimeZoneException.cs6
-rw-r--r--src/mscorlib/shared/System/Lazy.cs15
-rw-r--r--src/mscorlib/shared/System/MarshalByRefObject.cs1
-rw-r--r--src/mscorlib/shared/System/MemberAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/MethodAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/MissingMethodException.cs2
-rw-r--r--src/mscorlib/shared/System/MulticastNotSupportedException.cs3
-rw-r--r--src/mscorlib/shared/System/NotFiniteNumberException.cs4
-rw-r--r--src/mscorlib/shared/System/NotImplementedException.cs6
-rw-r--r--src/mscorlib/shared/System/NotSupportedException.cs6
-rw-r--r--src/mscorlib/shared/System/NullReferenceException.cs6
-rw-r--r--src/mscorlib/shared/System/ObjectDisposedException.cs4
-rw-r--r--src/mscorlib/shared/System/ObsoleteAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/OperationCanceledException.cs73
-rw-r--r--src/mscorlib/shared/System/OverflowException.cs6
-rw-r--r--src/mscorlib/shared/System/PlatformNotSupportedException.cs6
-rw-r--r--src/mscorlib/shared/System/Random.cs1
-rw-r--r--src/mscorlib/shared/System/RankException.cs6
-rw-r--r--src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs6
-rw-r--r--src/mscorlib/shared/System/Reflection/Assembly.cs5
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyNameFormatter.cs156
-rw-r--r--src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs2
-rw-r--r--src/mscorlib/shared/System/Reflection/DefaultMemberAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs2
-rw-r--r--src/mscorlib/shared/System/Reflection/MemberInfoSerializationHolder.cs315
-rw-r--r--src/mscorlib/shared/System/Reflection/Missing.cs6
-rw-r--r--src/mscorlib/shared/System/Reflection/Module.cs5
-rw-r--r--src/mscorlib/shared/System/Reflection/ParameterInfo.cs41
-rw-r--r--src/mscorlib/shared/System/Reflection/ParameterModifier.cs1
-rw-r--r--src/mscorlib/shared/System/Reflection/Pointer.cs12
-rw-r--r--src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs10
-rw-r--r--src/mscorlib/shared/System/Reflection/StrongNameKeyPair.cs16
-rw-r--r--src/mscorlib/shared/System/Reflection/TargetException.cs2
-rw-r--r--src/mscorlib/shared/System/Reflection/TargetInvocationException.cs6
-rw-r--r--src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs6
-rw-r--r--src/mscorlib/shared/System/Reflection/TypeDelegator.cs2
-rw-r--r--src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs2
-rw-r--r--src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs2
-rw-r--r--src/mscorlib/shared/System/Resources/ResourceFallbackManager.cs87
-rw-r--r--src/mscorlib/shared/System/Resources/RuntimeResourceSet.cs436
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/IsByRefLikeAttribute.cs21
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/LoadHint.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/MethodCodeType.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/ConstrainedExecution/Cer.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/ConstrainedExecution/Consistency.cs1
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs2
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs2
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/StreamingContext.cs1
-rw-r--r--src/mscorlib/shared/System/Security/CryptographicException.cs2
-rw-r--r--src/mscorlib/shared/System/Security/SafeBSTRHandle.cs5
-rw-r--r--src/mscorlib/shared/System/Security/SecureString.Unix.cs46
-rw-r--r--src/mscorlib/shared/System/Security/SecureString.Windows.cs13
-rw-r--r--src/mscorlib/shared/System/Security/SecurityException.cs2
-rw-r--r--src/mscorlib/shared/System/Security/VerificationException.cs2
-rw-r--r--src/mscorlib/shared/System/StackOverflowException.cs3
-rw-r--r--src/mscorlib/shared/System/StringComparison.cs1
-rw-r--r--src/mscorlib/shared/System/SystemException.cs6
-rw-r--r--src/mscorlib/shared/System/Text/ASCIIEncoding.cs2
-rw-r--r--src/mscorlib/shared/System/Text/Decoder.cs1
-rw-r--r--src/mscorlib/shared/System/Text/Encoder.cs1
-rw-r--r--src/mscorlib/shared/System/Text/EncodingInfo.cs1
-rw-r--r--src/mscorlib/shared/System/Text/EncodingNLS.cs1
-rw-r--r--src/mscorlib/shared/System/Text/UTF32Encoding.cs2
-rw-r--r--src/mscorlib/shared/System/Text/UTF8Encoding.cs79
-rw-r--r--src/mscorlib/shared/System/Text/UnicodeEncoding.cs41
-rw-r--r--src/mscorlib/shared/System/ThreadStaticAttribute.cs1
-rw-r--r--src/mscorlib/shared/System/Threading/AbandonedMutexException.cs2
-rw-r--r--src/mscorlib/shared/System/Threading/ExecutionContext.cs11
-rw-r--r--src/mscorlib/shared/System/Threading/LockRecursionException.cs6
-rw-r--r--src/mscorlib/shared/System/Threading/SemaphoreFullException.cs2
-rw-r--r--src/mscorlib/shared/System/Threading/SynchronizationLockException.cs2
-rw-r--r--src/mscorlib/shared/System/Threading/Tasks/TaskCanceledException.cs2
-rw-r--r--src/mscorlib/shared/System/Threading/Tasks/TaskSchedulerException.cs2
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadAbortException.cs6
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadStartException.cs6
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadStateException.cs2
-rw-r--r--src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs2
-rw-r--r--src/mscorlib/shared/System/TimeZone.cs1
-rw-r--r--src/mscorlib/shared/System/TimeZoneNotFoundException.cs6
-rw-r--r--src/mscorlib/shared/System/TimeoutException.cs6
-rw-r--r--src/mscorlib/shared/System/Type.cs1
-rw-r--r--src/mscorlib/shared/System/TypeAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/TypeCode.cs1
-rw-r--r--src/mscorlib/shared/System/TypeInitializationException.cs8
-rw-r--r--src/mscorlib/shared/System/TypeUnloadedException.cs7
-rw-r--r--src/mscorlib/shared/System/UnauthorizedAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/UnhandledExceptionEventArgs.cs1
-rw-r--r--src/mscorlib/shared/System/UnhandledExceptionEventHandler.cs1
-rw-r--r--src/mscorlib/shared/System/UnitySerializationHolder.cs329
-rw-r--r--src/mscorlib/shared/System/Void.cs1
196 files changed, 5655 insertions, 1231 deletions
diff --git a/src/mscorlib/shared/System/ApplicationException.cs b/src/mscorlib/shared/System/ApplicationException.cs
index 900feb5..cb98902 100644
--- a/src/mscorlib/shared/System/ApplicationException.cs
+++ b/src/mscorlib/shared/System/ApplicationException.cs
@@ -23,7 +23,6 @@ namespace System
// ApplicationException extends but adds no new functionality to
// RecoverableException.
//
- [Serializable]
public class ApplicationException : Exception
{
// Creates a new ApplicationException with its message string set to
@@ -51,6 +50,9 @@ namespace System
HResult = __HResults.COR_E_APPLICATION;
}
- protected ApplicationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected ApplicationException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/ArgumentException.cs b/src/mscorlib/shared/System/ArgumentException.cs
index 96afbe1..de2d775 100644
--- a/src/mscorlib/shared/System/ArgumentException.cs
+++ b/src/mscorlib/shared/System/ArgumentException.cs
@@ -20,7 +20,6 @@ namespace System
// the contract of the method. Ideally it should give a meaningful error
// message describing what was wrong and which parameter is incorrect.
//
- [Serializable]
public class ArgumentException : SystemException
{
private String _paramName;
@@ -65,13 +64,12 @@ namespace System
protected ArgumentException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
- _paramName = info.GetString("ParamName");
+ throw new PlatformNotSupportedException();
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
- info.AddValue("ParamName", _paramName, typeof(String));
}
public override String Message
diff --git a/src/mscorlib/shared/System/ArgumentNullException.cs b/src/mscorlib/shared/System/ArgumentNullException.cs
index 3a86223..74b39fe 100644
--- a/src/mscorlib/shared/System/ArgumentNullException.cs
+++ b/src/mscorlib/shared/System/ArgumentNullException.cs
@@ -18,7 +18,6 @@ namespace System
// The ArgumentException is thrown when an argument
// is null when it shouldn't be.
//
- [Serializable]
public class ArgumentNullException : ArgumentException
{
// Creates a new ArgumentNullException with its message
@@ -48,6 +47,9 @@ namespace System
HResult = __HResults.E_POINTER;
}
- protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/ArgumentOutOfRangeException.cs b/src/mscorlib/shared/System/ArgumentOutOfRangeException.cs
new file mode 100644
index 0000000..4721a50
--- /dev/null
+++ b/src/mscorlib/shared/System/ArgumentOutOfRangeException.cs
@@ -0,0 +1,97 @@
+// 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.Globalization;
+using System.Runtime.Serialization;
+
+namespace System
+{
+ // The ArgumentOutOfRangeException is thrown when an argument
+ // is outside the legal range for that argument.
+ public class ArgumentOutOfRangeException : ArgumentException
+ {
+ private Object _actualValue;
+
+ // Creates a new ArgumentOutOfRangeException with its message
+ // string set to a default message explaining an argument was out of range.
+ public ArgumentOutOfRangeException()
+ : base(SR.Arg_ArgumentOutOfRangeException)
+ {
+ HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
+ }
+
+ public ArgumentOutOfRangeException(String paramName)
+ : base(SR.Arg_ArgumentOutOfRangeException, 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)
+ {
+ _actualValue = actualValue;
+ HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
+ }
+
+ protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
+
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ base.GetObjectData(info, context);
+ }
+
+ public override String Message
+ {
+ get
+ {
+ String s = base.Message;
+ if (_actualValue != null)
+ {
+ String valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, _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 _actualValue; }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/ArithmeticException.cs b/src/mscorlib/shared/System/ArithmeticException.cs
index 081ba45..2c8abe5 100644
--- a/src/mscorlib/shared/System/ArithmeticException.cs
+++ b/src/mscorlib/shared/System/ArithmeticException.cs
@@ -18,7 +18,6 @@ namespace System
// The ArithmeticException is thrown when overflow or underflow
// occurs.
//
- [Serializable]
public class ArithmeticException : SystemException
{
// Creates a new ArithmeticException with its message string set to
@@ -46,6 +45,9 @@ namespace System
HResult = __HResults.COR_E_ARITHMETIC;
}
- protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/ArrayTypeMismatchException.cs b/src/mscorlib/shared/System/ArrayTypeMismatchException.cs
index 3e941fd..d06a450 100644
--- a/src/mscorlib/shared/System/ArrayTypeMismatchException.cs
+++ b/src/mscorlib/shared/System/ArrayTypeMismatchException.cs
@@ -18,7 +18,6 @@ namespace System
// The ArrayMismatchException is thrown when an attempt to store
// an object of the wrong type within an array occurs.
//
- [Serializable]
public class ArrayTypeMismatchException : SystemException
{
// Creates a new ArrayMismatchException with its message string set to
@@ -46,6 +45,9 @@ namespace System
HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
}
- protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/AsyncCallback.cs b/src/mscorlib/shared/System/AsyncCallback.cs
index 5c49535..036d44a 100644
--- a/src/mscorlib/shared/System/AsyncCallback.cs
+++ b/src/mscorlib/shared/System/AsyncCallback.cs
@@ -12,6 +12,5 @@
namespace System
{
- [Serializable]
public delegate void AsyncCallback(IAsyncResult ar);
}
diff --git a/src/mscorlib/shared/System/AttributeTargets.cs b/src/mscorlib/shared/System/AttributeTargets.cs
index fdfa4ab..c33d19e 100644
--- a/src/mscorlib/shared/System/AttributeTargets.cs
+++ b/src/mscorlib/shared/System/AttributeTargets.cs
@@ -10,7 +10,6 @@ namespace System
// Enum used to indicate all the elements of the
// VOS it is valid to attach this element to.
[Flags]
- [Serializable]
public enum AttributeTargets
{
Assembly = 0x0001,
diff --git a/src/mscorlib/shared/System/AttributeUsageAttribute.cs b/src/mscorlib/shared/System/AttributeUsageAttribute.cs
index 6f9aeb2..219dc43 100644
--- a/src/mscorlib/shared/System/AttributeUsageAttribute.cs
+++ b/src/mscorlib/shared/System/AttributeUsageAttribute.cs
@@ -16,7 +16,6 @@ using System.Reflection;
namespace System
{
/* By default, attributes are inherited and multiple attributes are not allowed */
- [Serializable]
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public sealed class AttributeUsageAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/BadImageFormatException.cs b/src/mscorlib/shared/System/BadImageFormatException.cs
new file mode 100644
index 0000000..6bed5e9
--- /dev/null
+++ b/src/mscorlib/shared/System/BadImageFormatException.cs
@@ -0,0 +1,124 @@
+// 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.
+**
+**
+===========================================================*/
+
+using System.Globalization;
+using System.IO;
+using System.Runtime.Serialization;
+
+namespace System
+{
+ public partial 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;
+ }
+
+ protected BadImageFormatException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
+
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ base.GetObjectData(info, context);
+ }
+
+ public override String Message
+ {
+ get
+ {
+ SetMessageField();
+ return _message;
+ }
+ }
+
+ private void SetMessageField()
+ {
+ if (_message == null)
+ {
+ if ((_fileName == null) &&
+ (HResult == __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().ToString() + ": " + 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;
+
+ if (_fusionLog != null)
+ {
+ if (s == null)
+ s = " ";
+ s += Environment.NewLine;
+ s += Environment.NewLine;
+ s += _fusionLog;
+ }
+
+ return s;
+ }
+
+ public String FusionLog
+ {
+ get { return _fusionLog; }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/CLSCompliantAttribute.cs b/src/mscorlib/shared/System/CLSCompliantAttribute.cs
index e03600d..d895b5a 100644
--- a/src/mscorlib/shared/System/CLSCompliantAttribute.cs
+++ b/src/mscorlib/shared/System/CLSCompliantAttribute.cs
@@ -13,7 +13,6 @@
namespace System
{
- [Serializable]
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public sealed class CLSCompliantAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Char.cs b/src/mscorlib/shared/System/Char.cs
index 2b3133a..3fad7a4 100644
--- a/src/mscorlib/shared/System/Char.cs
+++ b/src/mscorlib/shared/System/Char.cs
@@ -26,7 +26,7 @@ namespace System
//
// Member Variables
//
- internal char m_value;
+ private char m_value; // Do not rename (binary serialization)
//
// Public Constants
diff --git a/src/mscorlib/shared/System/CharEnumerator.cs b/src/mscorlib/shared/System/CharEnumerator.cs
index 4dbd5cd..ea9915a 100644
--- a/src/mscorlib/shared/System/CharEnumerator.cs
+++ b/src/mscorlib/shared/System/CharEnumerator.cs
@@ -17,7 +17,6 @@ using System.Collections.Generic;
namespace System
{
- [Serializable]
public sealed class CharEnumerator : IEnumerator, IEnumerator<char>, IDisposable, ICloneable
{
private String _str;
diff --git a/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs b/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs
index 1fca773..cdd6faf 100644
--- a/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs
+++ b/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs
@@ -7,7 +7,6 @@ using System.Runtime.Serialization;
namespace System.Collections.Generic
{
- [Serializable]
public class KeyNotFoundException : SystemException
{
public KeyNotFoundException()
@@ -28,6 +27,9 @@ namespace System.Collections.Generic
HResult = __HResults.COR_E_KEYNOTFOUND;
}
- protected KeyNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected KeyNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/CurrentSystemTimeZone.cs b/src/mscorlib/shared/System/CurrentSystemTimeZone.cs
index 2d84839..3f17d6f 100644
--- a/src/mscorlib/shared/System/CurrentSystemTimeZone.cs
+++ b/src/mscorlib/shared/System/CurrentSystemTimeZone.cs
@@ -28,7 +28,6 @@ using System.Runtime.Versioning;
namespace System
{
[Obsolete("System.CurrentSystemTimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo.Local instead.")]
- [Serializable]
internal partial class CurrentSystemTimeZone : TimeZone
{
// Standard offset in ticks to the Universal time if
diff --git a/src/mscorlib/shared/System/DBNull.cs b/src/mscorlib/shared/System/DBNull.cs
index 486eb72..4f4d64b 100644
--- a/src/mscorlib/shared/System/DBNull.cs
+++ b/src/mscorlib/shared/System/DBNull.cs
@@ -6,23 +6,17 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public sealed class DBNull : ISerializable, IConvertible
{
private DBNull()
{
}
-
- private DBNull(SerializationInfo info, StreamingContext context)
- {
- throw new NotSupportedException(SR.NotSupported_DBNullSerial);
- }
-
+
public static readonly DBNull Value = new DBNull();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.NullUnity, null, null);
+ throw new PlatformNotSupportedException();
}
public override string ToString()
diff --git a/src/mscorlib/shared/System/DataMisalignedException.cs b/src/mscorlib/shared/System/DataMisalignedException.cs
index b1991a0..ff5b29f 100644
--- a/src/mscorlib/shared/System/DataMisalignedException.cs
+++ b/src/mscorlib/shared/System/DataMisalignedException.cs
@@ -13,7 +13,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public sealed class DataMisalignedException : SystemException
{
public DataMisalignedException()
@@ -33,7 +32,5 @@ namespace System
{
HResult = __HResults.COR_E_DATAMISALIGNED;
}
-
- internal DataMisalignedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/shared/System/DateTimeKind.cs b/src/mscorlib/shared/System/DateTimeKind.cs
index 6b5e690..33c9bd9 100644
--- a/src/mscorlib/shared/System/DateTimeKind.cs
+++ b/src/mscorlib/shared/System/DateTimeKind.cs
@@ -7,7 +7,6 @@ namespace System
// This enum is used to indentify DateTime instances in cases when they are known to be in local time,
// UTC time or if this information has not been specified or is not applicable.
- [Serializable]
public enum DateTimeKind
{
Unspecified = 0,
diff --git a/src/mscorlib/shared/System/DayOfWeek.cs b/src/mscorlib/shared/System/DayOfWeek.cs
index 5d84257..f67d10e 100644
--- a/src/mscorlib/shared/System/DayOfWeek.cs
+++ b/src/mscorlib/shared/System/DayOfWeek.cs
@@ -13,7 +13,6 @@
namespace System
{
- [Serializable]
public enum DayOfWeek
{
Sunday = 0,
diff --git a/src/mscorlib/shared/System/DefaultBinder.cs b/src/mscorlib/shared/System/DefaultBinder.cs
index 3b46d5f..9adf702 100644
--- a/src/mscorlib/shared/System/DefaultBinder.cs
+++ b/src/mscorlib/shared/System/DefaultBinder.cs
@@ -8,8 +8,6 @@ using CultureInfo = System.Globalization.CultureInfo;
namespace System
{
- //Marked serializable even though it has no state.
- [Serializable]
#if CORECLR
internal
#else
diff --git a/src/mscorlib/shared/System/Diagnostics/ConditionalAttribute.cs b/src/mscorlib/shared/System/Diagnostics/ConditionalAttribute.cs
index d5bca6e..416625b 100644
--- a/src/mscorlib/shared/System/Diagnostics/ConditionalAttribute.cs
+++ b/src/mscorlib/shared/System/Diagnostics/ConditionalAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Diagnostics
{
- [Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public sealed class ConditionalAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Diagnostics/Debug.Unix.cs b/src/mscorlib/shared/System/Diagnostics/Debug.Unix.cs
new file mode 100644
index 0000000..495f2f7
--- /dev/null
+++ b/src/mscorlib/shared/System/Diagnostics/Debug.Unix.cs
@@ -0,0 +1,95 @@
+// 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/shared/System/Diagnostics/Tracing/EventProvider.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs
index e18574c..5292551 100644
--- a/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs
@@ -54,6 +54,7 @@ namespace System.Diagnostics.Tracing
// subclasses of EventProvider use when creating efficient (but unsafe) version of
// EventWrite. We do make it a nested type because we really don't expect anyone to use
// it except subclasses (and then only rarely).
+ [StructLayout(LayoutKind.Sequential)]
public struct EventData
{
internal unsafe ulong Ptr;
@@ -78,6 +79,7 @@ namespace System.Diagnostics.Tracing
private static bool m_setInformationMissing;
+ internal IEventProvider m_eventProvider; // The interface that implements the specific logging mechanism functions.
UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function
private long m_regHandle; // Trace Registration Handle
private byte m_level; // Tracing Level
@@ -119,6 +121,13 @@ namespace System.Diagnostics.Tracing
// EventSource has special logic to do this, no one else should be calling EventProvider.
internal EventProvider()
{
+#if PLATFORM_WINDOWS
+ m_eventProvider = new EtwEventProvider();
+#elif FEATURE_PERFTRACING
+ m_eventProvider = new EventPipeEventProvider();
+#else
+ m_eventProvider = new NoOpEventProvider();
+#endif
}
/// <summary>
@@ -429,7 +438,7 @@ namespace System.Diagnostics.Tracing
// However the framework version of EventSource DOES have ES_SESSION_INFO defined and thus
// does not have this issue.
-#if ES_SESSION_INFO || !ES_BUILD_STANDALONE
+#if (PLATFORM_WINDOWS && (ES_SESSION_INFO || !ES_BUILD_STANDALONE))
int buffSize = 256; // An initial guess that probably works most of the time.
byte* buffer;
for (; ; )
@@ -469,7 +478,7 @@ namespace System.Diagnostics.Tracing
providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset];
}
#else
-#if !ES_BUILD_PCL && !FEATURE_PAL // TODO command arguments don't work on PCL builds...
+#if !ES_BUILD_PCL && PLATFORM_WINDOWS // TODO command arguments don't work on PCL builds...
// This code is only used in the Nuget Package Version of EventSource. because
// the code above is using APIs baned from UWP apps.
//
@@ -553,7 +562,7 @@ namespace System.Diagnostics.Tracing
dataStart = 0;
if (filterData == null)
{
-#if (!ES_BUILD_PCL && !ES_BUILD_PN && !FEATURE_PAL)
+#if (!ES_BUILD_PCL && !ES_BUILD_PN && PLATFORM_WINDOWS)
string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey;
@@ -928,7 +937,7 @@ namespace System.Diagnostics.Tracing
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
- internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload)
+ internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr eventHandle, Guid* activityID, Guid* childActivityID, params object[] eventPayload)
{
int status = 0;
@@ -1056,7 +1065,7 @@ namespace System.Diagnostics.Tracing
userDataPtr[refObjPosition[7]].Ptr = (ulong)v7;
}
- status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData);
+ status = m_eventProvider.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, eventHandle, activityID, childActivityID, argCount, userData);
}
}
else
@@ -1082,7 +1091,7 @@ namespace System.Diagnostics.Tracing
}
}
- status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData);
+ status = m_eventProvider.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, eventHandle, activityID, childActivityID, argCount, userData);
for (int i = 0; i < refObjIndex; ++i)
{
@@ -1124,7 +1133,7 @@ namespace System.Diagnostics.Tracing
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
- internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data)
+ internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr eventHandle, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data)
{
if (childActivityID != null)
{
@@ -1135,7 +1144,7 @@ namespace System.Diagnostics.Tracing
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop);
}
- int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, dataCount, (EventData*)data);
+ int status = m_eventProvider.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, eventHandle, activityID, childActivityID, dataCount, (EventData*)data);
if (status != 0)
{
@@ -1155,9 +1164,10 @@ namespace System.Diagnostics.Tracing
{
int status;
- status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(
+ status = m_eventProvider.EventWriteTransferWrapper(
m_regHandle,
ref eventDescriptor,
+ IntPtr.Zero,
activityID,
relatedActivityID,
dataCount,
@@ -1178,12 +1188,12 @@ namespace System.Diagnostics.Tracing
{
m_providerId = providerId;
m_etwCallback = enableCallback;
- return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
+ return m_eventProvider.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
}
private uint EventUnregister(long registrationHandle)
{
- return UnsafeNativeMethods.ManifestEtw.EventUnregister(registrationHandle);
+ return m_eventProvider.EventUnregister(registrationHandle);
}
static int[] nibblebits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
@@ -1203,5 +1213,108 @@ namespace System.Diagnostics.Tracing
return idx;
}
}
+
+#if PLATFORM_WINDOWS
+
+ // A wrapper around the ETW-specific API calls.
+ internal sealed class EtwEventProvider : IEventProvider
+ {
+ // Register an event provider.
+ unsafe uint IEventProvider.EventRegister(
+ ref Guid providerId,
+ UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback,
+ void* callbackContext,
+ ref long registrationHandle)
+ {
+ return UnsafeNativeMethods.ManifestEtw.EventRegister(
+ ref providerId,
+ enableCallback,
+ callbackContext,
+ ref registrationHandle);
+ }
+
+ // Unregister an event provider.
+ uint IEventProvider.EventUnregister(long registrationHandle)
+ {
+ return UnsafeNativeMethods.ManifestEtw.EventUnregister(registrationHandle);
+ }
+
+ // Write an event.
+ unsafe int IEventProvider.EventWriteTransferWrapper(
+ long registrationHandle,
+ ref EventDescriptor eventDescriptor,
+ IntPtr eventHandle,
+ Guid* activityId,
+ Guid* relatedActivityId,
+ int userDataCount,
+ EventProvider.EventData* userData)
+ {
+ return UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(
+ registrationHandle,
+ ref eventDescriptor,
+ activityId,
+ relatedActivityId,
+ userDataCount,
+ userData);
+ }
+
+ // Get or set the per-thread activity ID.
+ int IEventProvider.EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.ActivityControl ControlCode, ref Guid ActivityId)
+ {
+ return UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
+ ControlCode,
+ ref ActivityId);
+ }
+
+ // Define an EventPipeEvent handle.
+ unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength)
+ {
+ throw new System.NotSupportedException();
+ }
+ }
+
+#elif !FEATURE_PERFTRACING
+
+ internal sealed class NoOpEventProvider : IEventProvider
+ {
+ unsafe uint IEventProvider.EventRegister(
+ ref Guid providerId,
+ UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback,
+ void* callbackContext,
+ ref long registrationHandle)
+ {
+ return 0;
+ }
+
+ uint IEventProvider.EventUnregister(long registrationHandle)
+ {
+ return 0;
+ }
+
+ unsafe int IEventProvider.EventWriteTransferWrapper(
+ long registrationHandle,
+ ref EventDescriptor eventDescriptor,
+ IntPtr eventHandle,
+ Guid* activityId,
+ Guid* relatedActivityId,
+ int userDataCount,
+ EventProvider.EventData* userData)
+ {
+ return 0;
+ }
+
+ 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)
+ {
+ throw new System.NotSupportedException();
+ }
+ }
+
+#endif
}
diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs
index cf4901d..3349c06 100644..100755
--- a/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs
@@ -4,16 +4,10 @@
// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
-#if PLATFORM_WINDOWS
-
-#define FEATURE_MANAGED_ETW
-
-#if !ES_BUILD_STANDALONE && !CORECLR && !ES_BUILD_PN
+#if PLATFORM_WINDOWS && !ES_BUILD_STANDALONE && !CORECLR && !ES_BUILD_PN
#define FEATURE_ACTIVITYSAMPLING
#endif // !ES_BUILD_STANDALONE
-#endif // PLATFORM_WINDOWS
-
#if ES_BUILD_STANDALONE
#define FEATURE_MANAGED_ETW_CHANNELS
// #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
@@ -692,6 +686,106 @@ namespace System.Diagnostics.Tracing
Initialize(eventSourceGuid, eventSourceName, traits);
}
+#if FEATURE_PERFTRACING
+ // Generate the serialized blobs that describe events for all strongly typed events (that is events that define strongly
+ // typed event methods. Dynamically defined events (that use Write) hare defined on the fly and are handled elsewhere.
+ private unsafe void DefineEventPipeEvents()
+ {
+ Debug.Assert(m_eventData != null);
+ Debug.Assert(m_provider != null);
+ int cnt = m_eventData.Length;
+ for (int i = 0; i < cnt; i++)
+ {
+ uint eventID = (uint)m_eventData[i].Descriptor.EventId;
+ if (eventID == 0)
+ continue;
+
+ string eventName = m_eventData[i].Name;
+ Int64 keywords = m_eventData[i].Descriptor.Keywords;
+ uint eventVersion = m_eventData[i].Descriptor.Version;
+ uint level = m_eventData[i].Descriptor.Level;
+
+ // evnetID : 4 bytes
+ // eventName : (eventName.Length + 1) * 2 bytes
+ // keywords : 8 bytes
+ // eventVersion : 4 bytes
+ // level : 4 bytes
+ // parameterCount : 4 bytes
+ uint metadataLength = 24 + ((uint)eventName.Length + 1) * 2;
+
+ // Increase the metadataLength for the types of all parameters.
+ metadataLength += (uint)m_eventData[i].Parameters.Length * 4;
+
+ // Increase the metadataLength for the names of all parameters.
+ foreach (var parameter in m_eventData[i].Parameters)
+ {
+ string parameterName = parameter.Name;
+ metadataLength = metadataLength + ((uint)parameterName.Length + 1) * 2;
+ }
+
+ byte[] metadata = new byte[metadataLength];
+
+ // Write metadata: evnetID, eventName, keywords, eventVersion, level, parameterCount, param1 type, param1 name...
+ fixed (byte *pMetadata = metadata)
+ {
+ uint offset = 0;
+ WriteToBuffer(pMetadata, metadataLength, ref offset, eventID);
+ fixed(char *pEventName = eventName)
+ {
+ WriteToBuffer(pMetadata, metadataLength, ref offset, (byte *)pEventName, ((uint)eventName.Length + 1) * 2);
+ }
+ WriteToBuffer(pMetadata, metadataLength, ref offset, keywords);
+ WriteToBuffer(pMetadata, metadataLength, ref offset, eventVersion);
+ WriteToBuffer(pMetadata, metadataLength, ref offset, level);
+ WriteToBuffer(pMetadata, metadataLength, ref offset, (uint)m_eventData[i].Parameters.Length);
+ foreach (var parameter in m_eventData[i].Parameters)
+ {
+ // Write parameter type.
+ WriteToBuffer(pMetadata, metadataLength, ref offset, (uint)Type.GetTypeCode(parameter.ParameterType));
+
+ // Write parameter name.
+ string parameterName = parameter.Name;
+ fixed (char *pParameterName = parameterName)
+ {
+ WriteToBuffer(pMetadata, metadataLength, ref offset, (byte *)pParameterName, ((uint)parameterName.Length + 1) * 2);
+ }
+ }
+ Debug.Assert(metadataLength == offset);
+ IntPtr eventHandle = m_provider.m_eventProvider.DefineEventHandle(eventID, eventName, keywords, eventVersion, level, pMetadata, metadataLength);
+ m_eventData[i].EventHandle = eventHandle;
+ }
+ }
+ }
+
+ // 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;
+ }
+
+ // Copy uint value to buffer.
+ private static unsafe void WriteToBuffer(byte *buffer, uint bufferLength, ref uint offset, uint value)
+ {
+ Debug.Assert(bufferLength >= (offset + 4));
+ *(uint *)(buffer + offset) = value;
+ offset += 4;
+ }
+
+ // Copy long value to buffer.
+ private static unsafe void WriteToBuffer(byte *buffer, uint bufferLength, ref uint offset, long value)
+ {
+ Debug.Assert(bufferLength >= (offset + 8));
+ *(long *)(buffer + offset) = value;
+ offset += 8;
+ }
+#endif
+
internal virtual void GetMetadata(out Guid eventSourceGuid, out string eventSourceName, out EventMetadata[] eventData, out byte[] manifestBytes)
{
//
@@ -1185,7 +1279,7 @@ namespace System.Diagnostics.Tracing
// by default the Descriptor.Keyword will have the perEventSourceSessionId bit
// mask set to 0x0f so, when all ETW sessions want the event we don't need to
// synthesize a new one
- if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data))
+ if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, m_eventData[eventId].EventHandle, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data))
ThrowEventSourceException(m_eventData[eventId].Name);
}
else
@@ -1205,7 +1299,7 @@ namespace System.Diagnostics.Tracing
m_eventData[eventId].Descriptor.Task,
unchecked((long)etwSessions.ToEventKeywords() | origKwd));
- if (!m_provider.WriteEvent(ref desc, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data))
+ if (!m_provider.WriteEvent(ref desc, m_eventData[eventId].EventHandle, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data))
ThrowEventSourceException(m_eventData[eventId].Name);
}
}
@@ -1235,7 +1329,7 @@ namespace System.Diagnostics.Tracing
#else
if (!SelfDescribingEvents)
{
- if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data))
+ if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, m_eventData[eventId].EventHandle, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data))
ThrowEventSourceException(m_eventData[eventId].Name);
}
else
@@ -1328,6 +1422,7 @@ namespace System.Diagnostics.Tracing
if (disposing)
{
#if FEATURE_MANAGED_ETW
+#if !FEATURE_PERFTRACING
// Send the manifest one more time to ensure circular buffers have a chance to get to this information
// even in scenarios with a high volume of ETW events.
if (m_eventSourceEnabled)
@@ -1340,6 +1435,7 @@ namespace System.Diagnostics.Tracing
{ } // If it fails, simply give up.
m_eventSourceEnabled = false;
}
+#endif
if (m_provider != null)
{
m_provider.Dispose();
@@ -1474,6 +1570,7 @@ namespace System.Diagnostics.Tracing
// Set m_provider, which allows this.
m_provider = provider;
+#if PLATFORM_WINDOWS
#if (!ES_BUILD_STANDALONE && !ES_BUILD_PN)
// API available on OS >= Win 8 and patched Win 7.
// Disable only for FrameworkEventSource to avoid recursion inside exception handling.
@@ -1492,8 +1589,8 @@ namespace System.Diagnostics.Tracing
metadataHandle.Free();
}
+#endif // PLATFORM_WINDOWS
#endif // FEATURE_MANAGED_ETW
-
Debug.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted.
// We are logically completely initialized at this point.
m_completelyInited = true;
@@ -1945,7 +2042,7 @@ namespace System.Diagnostics.Tracing
// by default the Descriptor.Keyword will have the perEventSourceSessionId bit
// mask set to 0x0f so, when all ETW sessions want the event we don't need to
// synthesize a new one
- if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, pActivityId, childActivityID, args))
+ if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, m_eventData[eventId].EventHandle, pActivityId, childActivityID, args))
ThrowEventSourceException(m_eventData[eventId].Name);
}
else
@@ -1962,7 +2059,7 @@ namespace System.Diagnostics.Tracing
m_eventData[eventId].Descriptor.Task,
unchecked((long)etwSessions.ToEventKeywords() | origKwd));
- if (!m_provider.WriteEvent(ref desc, pActivityId, childActivityID, args))
+ if (!m_provider.WriteEvent(ref desc, m_eventData[eventId].EventHandle, pActivityId, childActivityID, args))
ThrowEventSourceException(m_eventData[eventId].Name);
}
}
@@ -1992,7 +2089,7 @@ namespace System.Diagnostics.Tracing
#else
if (!SelfDescribingEvents)
{
- if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, pActivityId, childActivityID, args))
+ if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, m_eventData[eventId].EventHandle, pActivityId, childActivityID, args))
ThrowEventSourceException(m_eventData[eventId].Name);
}
else
@@ -2102,32 +2199,26 @@ namespace System.Diagnostics.Tracing
#endif //!ES_BUILD_PCL
}
- private int GetParamLenghtIncludingByteArray(ParameterInfo[] parameters)
+ unsafe private void WriteToAllListeners(int eventId, Guid* childActivityID, int eventDataCount, EventSource.EventData* data)
{
- int sum = 0;
- foreach (ParameterInfo info in parameters)
+ // We represent a byte[] as a integer denoting the length and then a blob of bytes in the data pointer. This causes a spurious
+ // warning because eventDataCount is off by one for the byte[] case since a byte[] has 2 items associated it. So we want to check
+ // that the number of parameters is correct against the byte[] case, but also we the args array would be one too long if
+ // we just used the modifiedParamCount here -- so we need both.
+ int paramCount = GetParameterCount(m_eventData[eventId]);
+ int modifiedParamCount = 0;
+ for (int i = 0; i < paramCount; i++)
{
- if (info.ParameterType == typeof(byte[]))
+ Type parameterType = GetDataType(m_eventData[eventId], i);
+ if (parameterType == typeof(byte[]))
{
- sum += 2;
+ modifiedParamCount += 2;
}
else
{
- sum++;
+ modifiedParamCount++;
}
}
-
- return sum;
- }
-
- unsafe private void WriteToAllListeners(int eventId, Guid* childActivityID, int eventDataCount, EventSource.EventData* data)
- {
- // We represent a byte[] as a integer denoting the length and then a blob of bytes in the data pointer. This causes a spurious
- // warning because eventDataCount is off by one for the byte[] case since a byte[] has 2 items associated it. So we want to check
- // that the number of parameters is correct against the byte[] case, but also we the args array would be one too long if
- // we just used the modifiedParamCount here -- so we need both.
- int paramCount = m_eventData[eventId].Parameters.Length;
- int modifiedParamCount = GetParamLenghtIncludingByteArray(m_eventData[eventId].Parameters);
if (eventDataCount != modifiedParamCount)
{
ReportOutOfBandMessage(Resources.GetResourceString("EventSource_EventParametersMismatch", eventId, eventDataCount, paramCount), true);
@@ -2200,7 +2291,7 @@ namespace System.Diagnostics.Tracing
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
private unsafe void WriteEventString(EventLevel level, long keywords, string msgString)
{
-#if FEATURE_MANAGED_ETW
+#if FEATURE_MANAGED_ETW && !FEATURE_PERFTRACING
if (m_provider != null)
{
string eventName = "EventSourceMessage";
@@ -2236,7 +2327,7 @@ namespace System.Diagnostics.Tracing
data.Ptr = (ulong)msgStringPtr;
data.Size = (uint)(2 * (msgString.Length + 1));
data.Reserved = 0;
- m_provider.WriteEvent(ref descr, null, null, 1, (IntPtr)((void*)&data));
+ m_provider.WriteEvent(ref descr, IntPtr.Zero, null, null, 1, (IntPtr)((void*)&data));
}
}
}
@@ -2521,6 +2612,7 @@ namespace System.Diagnostics.Tracing
partial struct EventMetadata
{
public EventDescriptor Descriptor;
+ public IntPtr EventHandle; // EventPipeEvent handle.
public EventTags Tags;
public bool EnabledForAnyListener; // true if any dispatcher has this event turned on
public bool EnabledForETW; // is this event on for the OS ETW data dispatcher?
@@ -2683,11 +2775,13 @@ namespace System.Diagnostics.Tracing
{
// eventSourceDispatcher == null means this is the ETW manifest
+#if !FEATURE_PERFTRACING
// Note that we unconditionally send the manifest whenever we are enabled, even if
// we were already enabled. This is because there may be multiple sessions active
// and we can't know that all the sessions have seen the manifest.
if (!SelfDescribingEvents)
SendManifest(m_rawManifest);
+#endif
}
#if FEATURE_ACTIVITYSAMPLING
@@ -2811,12 +2905,14 @@ namespace System.Diagnostics.Tracing
}
else
{
+#if !FEATURE_PERFTRACING
if (commandArgs.Command == EventCommand.SendManifest)
{
// TODO: should we generate the manifest here if we hadn't already?
if (m_rawManifest != null)
SendManifest(m_rawManifest);
}
+#endif
// These are not used for non-update commands and thus should always be 'default' values
// Debug.Assert(enable == true);
@@ -3036,6 +3132,7 @@ namespace System.Diagnostics.Tracing
{
// GetMetadata failed, so we have to set it via reflection.
Debug.Assert(m_rawManifest == null);
+
m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this);
Debug.Assert(m_eventData != null);
@@ -3069,6 +3166,10 @@ namespace System.Diagnostics.Tracing
dispatcher.m_EventEnabled = new bool[m_eventData.Length];
dispatcher = dispatcher.m_Next;
}
+#if FEATURE_PERFTRACING
+ // Initialize the EventPipe event handles.
+ DefineEventPipeEvents();
+#endif
}
if (s_currentPid == 0)
{
@@ -3123,7 +3224,7 @@ namespace System.Diagnostics.Tracing
dataDescrs[1].Size = (uint)Math.Min(dataLeft, chunkSize);
if (m_provider != null)
{
- if (!m_provider.WriteEvent(ref manifestDescr, null, null, 2, (IntPtr)dataDescrs))
+ if (!m_provider.WriteEvent(ref manifestDescr, IntPtr.Zero, null, null, 2, (IntPtr)dataDescrs))
{
// Turns out that if users set the BufferSize to something less than 64K then WriteEvent
// can fail. If we get this failure on the first chunk try again with something smaller
@@ -3690,6 +3791,7 @@ namespace System.Diagnostics.Tracing
eventData[eventAttribute.EventId].Message = eventAttribute.Message;
eventData[eventAttribute.EventId].ActivityOptions = eventAttribute.ActivityOptions;
eventData[eventAttribute.EventId].HasRelatedActivityID = hasRelatedActivityID;
+ eventData[eventAttribute.EventId].EventHandle = IntPtr.Zero;
}
// Helper used by code:CreateManifestAndDescriptors that trims the m_eventData array to the correct
diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/EventSourceException.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/EventSourceException.cs
index 88b8da9..73e32aa 100644
--- a/src/mscorlib/shared/System/Diagnostics/Tracing/EventSourceException.cs
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/EventSourceException.cs
@@ -18,9 +18,9 @@ namespace System.Diagnostics.Tracing
/// <summary>
/// Exception that is thrown when an error occurs during EventSource operation.
/// </summary>
-#if !ES_BUILD_PCL
+#if !CORECLR && !ES_BUILD_PN && !ES_BUILD_PCL && !CORERT
[Serializable]
-#endif
+#endif // !CORECLR && !ES_BUILD_PN && !ES_BUILD_PCL && !CORERT
public class EventSourceException : Exception
{
/// <summary>
diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/IEventProvider.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/IEventProvider.cs
new file mode 100644
index 0000000..71a2fe4
--- /dev/null
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/IEventProvider.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 Microsoft.Win32;
+
+#if ES_BUILD_STANDALONE
+namespace Microsoft.Diagnostics.Tracing
+#else
+namespace System.Diagnostics.Tracing
+#endif
+{
+ // Represents the interface between EventProvider and an external logging mechanism.
+ internal interface IEventProvider
+ {
+ // Register an event provider.
+ unsafe uint EventRegister(
+ ref Guid providerId,
+ UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback,
+ void* callbackContext,
+ ref long registrationHandle);
+
+ // Unregister an event provider.
+ uint EventUnregister(long registrationHandle);
+
+ // Write an event.
+ unsafe int EventWriteTransferWrapper(
+ long registrationHandle,
+ ref EventDescriptor eventDescriptor,
+ IntPtr eventHandle,
+ Guid* activityId,
+ Guid* relatedActivityId,
+ int userDataCount,
+ EventProvider.EventData* userData);
+
+ // Get or set the per-thread activity ID.
+ int EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.ActivityControl ControlCode, ref Guid ActivityId);
+
+ // Define an EventPipeEvent handle.
+ unsafe IntPtr DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength);
+ }
+}
diff --git a/src/mscorlib/shared/System/DivideByZeroException.cs b/src/mscorlib/shared/System/DivideByZeroException.cs
index 4abd43a..0fad2f8 100644
--- a/src/mscorlib/shared/System/DivideByZeroException.cs
+++ b/src/mscorlib/shared/System/DivideByZeroException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class DivideByZeroException : ArithmeticException
{
public DivideByZeroException()
@@ -36,6 +35,9 @@ namespace System
HResult = __HResults.COR_E_DIVIDEBYZERO;
}
- protected DivideByZeroException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected DivideByZeroException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/DllNotFoundException.cs b/src/mscorlib/shared/System/DllNotFoundException.cs
new file mode 100644
index 0000000..8c69e45
--- /dev/null
+++ b/src/mscorlib/shared/System/DllNotFoundException.cs
@@ -0,0 +1,44 @@
+// 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.
+
+/*=============================================================================
+**
+** Class: DllNotFoundException
+**
+**
+** Purpose: The exception class for some failed P/Invoke calls.
+**
+**
+=============================================================================*/
+
+using System.Runtime.Serialization;
+
+namespace System
+{
+ 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)
+ {
+ throw new PlatformNotSupportedException();
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/DuplicateWaitObjectException.cs b/src/mscorlib/shared/System/DuplicateWaitObjectException.cs
index da29e2a..7eadead 100644
--- a/src/mscorlib/shared/System/DuplicateWaitObjectException.cs
+++ b/src/mscorlib/shared/System/DuplicateWaitObjectException.cs
@@ -18,7 +18,6 @@ namespace System
// The DuplicateWaitObjectException is thrown when an object
// appears more than once in the list of objects to WaitAll or WaitAny.
//
- [Serializable]
public class DuplicateWaitObjectException : ArgumentException
{
private static volatile String s_duplicateWaitObjectMessage = null;
@@ -58,8 +57,10 @@ namespace System
{
HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
}
-
- // This constructor is required for serialization
- protected DuplicateWaitObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+
+ protected DuplicateWaitObjectException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/EntryPointNotFoundException.cs b/src/mscorlib/shared/System/EntryPointNotFoundException.cs
index 835d334..0b881ce 100644
--- a/src/mscorlib/shared/System/EntryPointNotFoundException.cs
+++ b/src/mscorlib/shared/System/EntryPointNotFoundException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class EntryPointNotFoundException : TypeLoadException
{
public EntryPointNotFoundException()
@@ -37,6 +36,9 @@ namespace System
HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
}
- protected EntryPointNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected EntryPointNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/EventArgs.cs b/src/mscorlib/shared/System/EventArgs.cs
index c035661..be12af2 100644
--- a/src/mscorlib/shared/System/EventArgs.cs
+++ b/src/mscorlib/shared/System/EventArgs.cs
@@ -7,7 +7,6 @@ using System;
namespace System
{
// The base class for all event classes.
- [Serializable]
public class EventArgs
{
public static readonly EventArgs Empty = new EventArgs();
diff --git a/src/mscorlib/shared/System/EventHandler.cs b/src/mscorlib/shared/System/EventHandler.cs
index e6923cf..3d1cbfe 100644
--- a/src/mscorlib/shared/System/EventHandler.cs
+++ b/src/mscorlib/shared/System/EventHandler.cs
@@ -6,9 +6,7 @@ using System;
namespace System
{
- [Serializable]
public delegate void EventHandler(Object sender, EventArgs e);
- [Serializable]
public delegate void EventHandler<TEventArgs>(Object sender, TEventArgs e); // Removed TEventArgs constraint post-.NET 4
}
diff --git a/src/mscorlib/shared/System/ExecutionEngineException.cs b/src/mscorlib/shared/System/ExecutionEngineException.cs
index bebfd49..b89f6d9 100644
--- a/src/mscorlib/shared/System/ExecutionEngineException.cs
+++ b/src/mscorlib/shared/System/ExecutionEngineException.cs
@@ -21,7 +21,6 @@ using System.Runtime.Serialization;
namespace System
{
[Obsolete("This type previously indicated an unspecified fatal error in the runtime. The runtime no longer raises this exception so this type is obsolete.")]
- [Serializable]
public sealed class ExecutionEngineException : SystemException
{
public ExecutionEngineException()
@@ -41,7 +40,5 @@ namespace System
{
HResult = __HResults.COR_E_EXECUTIONENGINE;
}
-
- internal ExecutionEngineException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/shared/System/FieldAccessException.cs b/src/mscorlib/shared/System/FieldAccessException.cs
index ac62c0f..b56d749 100644
--- a/src/mscorlib/shared/System/FieldAccessException.cs
+++ b/src/mscorlib/shared/System/FieldAccessException.cs
@@ -13,7 +13,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class FieldAccessException : MemberAccessException
{
public FieldAccessException()
@@ -34,6 +33,9 @@ namespace System
HResult = __HResults.COR_E_FIELDACCESS;
}
- protected FieldAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected FieldAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/FlagsAttribute.cs b/src/mscorlib/shared/System/FlagsAttribute.cs
index 5f8c108..4f3ab36 100644
--- a/src/mscorlib/shared/System/FlagsAttribute.cs
+++ b/src/mscorlib/shared/System/FlagsAttribute.cs
@@ -11,7 +11,6 @@ namespace System
// should be treated as a bitfield (or set of flags).
// An IDE may use this information to provide a richer
// development experience.
- [Serializable]
[AttributeUsage(AttributeTargets.Enum, Inherited = false)]
public class FlagsAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/FormatException.cs b/src/mscorlib/shared/System/FormatException.cs
index c5758e1..9baaac2 100644
--- a/src/mscorlib/shared/System/FormatException.cs
+++ b/src/mscorlib/shared/System/FormatException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class FormatException : SystemException
{
public FormatException()
@@ -36,6 +35,9 @@ namespace System
HResult = __HResults.COR_E_FORMAT;
}
- protected FormatException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected FormatException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs b/src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs
new file mode 100644
index 0000000..a2ceeb1
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs
@@ -0,0 +1,348 @@
+// 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)
+ {
+ try
+ {
+ 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);
+ }
+ catch (Exception e)
+ {
+ Debug.Assert(false, e.ToString());
+ // we ignore the managed exceptions here because EnumCalendarInfoCallback will get called from the native code.
+ // If we don't ignore the exception here that can cause the runtime to fail fast.
+ }
+ }
+
+ 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/shared/System/Globalization/CalendarWeekRule.cs b/src/mscorlib/shared/System/Globalization/CalendarWeekRule.cs
index b381b5c..f683ed0 100644
--- a/src/mscorlib/shared/System/Globalization/CalendarWeekRule.cs
+++ b/src/mscorlib/shared/System/Globalization/CalendarWeekRule.cs
@@ -4,7 +4,6 @@
namespace System.Globalization
{
- [Serializable]
public enum CalendarWeekRule
{
FirstDay = 0, // Week 1 begins on the first day of the year
diff --git a/src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs
index 404add0..e09011a 100644
--- a/src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs
@@ -14,7 +14,6 @@ namespace System.Globalization
** ChineseLunisolar 1901/01/01 2100/12/29
*/
- [Serializable]
public class ChineseLunisolarCalendar : EastAsianLunisolarCalendar
{
//
diff --git a/src/mscorlib/shared/System/Globalization/CultureData.Unix.cs b/src/mscorlib/shared/System/Globalization/CultureData.Unix.cs
new file mode 100644
index 0000000..4f685de
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/CultureData.Unix.cs
@@ -0,0 +1,431 @@
+// 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/shared/System/Globalization/CultureNotFoundException.cs b/src/mscorlib/shared/System/Globalization/CultureNotFoundException.cs
index 929f4bb..dde1a8b 100644
--- a/src/mscorlib/shared/System/Globalization/CultureNotFoundException.cs
+++ b/src/mscorlib/shared/System/Globalization/CultureNotFoundException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Globalization
{
- [Serializable]
public class CultureNotFoundException : ArgumentException
{
private string _invalidCultureName; // unrecognized culture name
@@ -59,15 +58,12 @@ namespace System.Globalization
protected CultureNotFoundException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
- _invalidCultureId = (int?)info.GetValue("InvalidCultureId", typeof(int?));
- _invalidCultureName = (string)info.GetValue("InvalidCultureName", typeof(string));
+ throw new PlatformNotSupportedException();
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
- info.AddValue("InvalidCultureId", _invalidCultureId, typeof(int?));
- info.AddValue("InvalidCultureName", _invalidCultureName, typeof(string));
}
public virtual Nullable<int> InvalidCultureId
diff --git a/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs b/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs
index d3f1ea9..5d3239e 100644
--- a/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs
+++ b/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs
@@ -49,7 +49,6 @@ namespace System.Globalization
}
- [Serializable]
public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable
{
// cache for the invariant culture.
diff --git a/src/mscorlib/shared/System/Globalization/DaylightTime.cs b/src/mscorlib/shared/System/Globalization/DaylightTime.cs
index b3c70e1..10f074d 100644
--- a/src/mscorlib/shared/System/Globalization/DaylightTime.cs
+++ b/src/mscorlib/shared/System/Globalization/DaylightTime.cs
@@ -5,7 +5,6 @@
namespace System.Globalization
{
// This class represents a starting/ending time for a period of daylight saving time.
- [Serializable]
public class DaylightTime
{
private readonly DateTime _start;
diff --git a/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs
index d06b13c..0697b60 100644
--- a/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs
@@ -6,7 +6,6 @@ using System.Diagnostics.Contracts;
namespace System.Globalization
{
- [Serializable]
public abstract class EastAsianLunisolarCalendar : Calendar
{
internal const int LeapMonth = 0;
diff --git a/src/mscorlib/shared/System/Globalization/GregorianCalendarTypes.cs b/src/mscorlib/shared/System/Globalization/GregorianCalendarTypes.cs
index 1b61e52..46f13b0 100644
--- a/src/mscorlib/shared/System/Globalization/GregorianCalendarTypes.cs
+++ b/src/mscorlib/shared/System/Globalization/GregorianCalendarTypes.cs
@@ -6,7 +6,6 @@ namespace System.Globalization
{
// Note: The values of the members of this enum must match the coresponding values
// in the CalendarId enum (since we cast between GregorianCalendarTypes and CalendarId).
- [Serializable]
public enum GregorianCalendarTypes
{
Localized = CalendarId.GREGORIAN,
diff --git a/src/mscorlib/shared/System/Globalization/HebrewCalendar.cs b/src/mscorlib/shared/System/Globalization/HebrewCalendar.cs
index b4f54f8..6ba4f08 100644
--- a/src/mscorlib/shared/System/Globalization/HebrewCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/HebrewCalendar.cs
@@ -62,7 +62,6 @@ namespace System.Globalization
// Gregorian to Hebrew Lunar from 1583 to 2239.
- [Serializable]
public class HebrewCalendar : Calendar
{
public static readonly int HebrewEra = 1;
diff --git a/src/mscorlib/shared/System/Globalization/HijriCalendar.Unix.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.Unix.cs
new file mode 100644
index 0000000..a6e8f73
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.Unix.cs
@@ -0,0 +1,15 @@
+// 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/shared/System/Globalization/HijriCalendar.Win32.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs
new file mode 100644
index 0000000..869b809
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs
@@ -0,0 +1,96 @@
+// 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/shared/System/Globalization/HijriCalendar.WinRT.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.WinRT.cs
new file mode 100644
index 0000000..fb91c27
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.WinRT.cs
@@ -0,0 +1,16 @@
+// 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/shared/System/Globalization/HijriCalendar.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.cs
index cafde5f..125248a 100644
--- a/src/mscorlib/shared/System/Globalization/HijriCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.cs
@@ -42,7 +42,6 @@ namespace System.Globalization
** Hijri 0001/01/01 9666/04/03
*/
- [Serializable]
public partial class HijriCalendar : Calendar
{
public static readonly int HijriEra = 1;
diff --git a/src/mscorlib/shared/System/Globalization/IdnMapping.Unix.cs b/src/mscorlib/shared/System/Globalization/IdnMapping.Unix.cs
new file mode 100644
index 0000000..2bbda0d
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/IdnMapping.Unix.cs
@@ -0,0 +1,142 @@
+// 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[0])
+ {
+ 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[0])
+ {
+ 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/shared/System/Globalization/JapaneseCalendar.Unix.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Unix.cs
new file mode 100644
index 0000000..51ff809
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Unix.cs
@@ -0,0 +1,96 @@
+// 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/shared/System/Globalization/JapaneseCalendar.Win32.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs
new file mode 100644
index 0000000..a83c4fa
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs
@@ -0,0 +1,209 @@
+// 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/shared/System/Globalization/JapaneseCalendar.WinRT.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.WinRT.cs
new file mode 100644
index 0000000..6a9df97
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.WinRT.cs
@@ -0,0 +1,62 @@
+// 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/shared/System/Globalization/JapaneseCalendar.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs
index 4655e08..0db1e65 100644
--- a/src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs
@@ -36,7 +36,6 @@ namespace System.Globalization
============================================================================*/
- [Serializable]
public partial class JapaneseCalendar : Calendar
{
internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8);
diff --git a/src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs
index 95e87f8..a90c4e8 100644
--- a/src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs
@@ -14,7 +14,6 @@ namespace System.Globalization
** JapaneseLunisolar 1960/01/01 2049/12/29
*/
- [Serializable]
public class JapaneseLunisolarCalendar : EastAsianLunisolarCalendar
{
//
diff --git a/src/mscorlib/shared/System/Globalization/JulianCalendar.cs b/src/mscorlib/shared/System/Globalization/JulianCalendar.cs
index f4678c1..8d94290 100644
--- a/src/mscorlib/shared/System/Globalization/JulianCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/JulianCalendar.cs
@@ -17,7 +17,6 @@ namespace System.Globalization
//* Gregorian 0001/01/01 9999/12/31
//* Julia 0001/01/03 9999/10/19
- [Serializable]
public class JulianCalendar : Calendar
{
public static readonly int JulianEra = 1;
diff --git a/src/mscorlib/shared/System/Globalization/KoreanCalendar.cs b/src/mscorlib/shared/System/Globalization/KoreanCalendar.cs
index b962b1c..ef7495f 100644
--- a/src/mscorlib/shared/System/Globalization/KoreanCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/KoreanCalendar.cs
@@ -23,7 +23,6 @@ namespace System.Globalization
============================================================================*/
- [Serializable]
public class KoreanCalendar : Calendar
{
//
diff --git a/src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs
index d4c7163..8364532 100644
--- a/src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs
@@ -14,7 +14,6 @@ namespace System.Globalization
** KoreanLunisolar 918/01/01 2050/13/29
*/
- [Serializable]
public class KoreanLunisolarCalendar : EastAsianLunisolarCalendar
{
//
diff --git a/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs b/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs
new file mode 100644
index 0000000..9fea694
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs
@@ -0,0 +1,899 @@
+// 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.
+ //
+
+ 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, nameof(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(nameof(PercentGroupSizes),
+ SR.ArgumentNull_Obj);
+ }
+ Contract.EndContractBlock();
+ VerifyWritable();
+ Int32[] inputSizes = (Int32[])value.Clone();
+ CheckGroupSize(nameof(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/shared/System/Globalization/PersianCalendar.cs b/src/mscorlib/shared/System/Globalization/PersianCalendar.cs
index 445bbd6..78a081e 100644
--- a/src/mscorlib/shared/System/Globalization/PersianCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/PersianCalendar.cs
@@ -19,7 +19,6 @@ namespace System.Globalization
** Persian 0001/01/01 9378/10/13
*/
- [Serializable]
public class PersianCalendar : Calendar
{
public static readonly int PersianEra = 1;
diff --git a/src/mscorlib/shared/System/Globalization/SortKey.cs b/src/mscorlib/shared/System/Globalization/SortKey.cs
new file mode 100644
index 0000000..d65e097
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/SortKey.cs
@@ -0,0 +1,202 @@
+// 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.
+//
+//
+////////////////////////////////////////////////////////////////////////////
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System.Globalization
+{
+ 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;
+
+ 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/shared/System/Globalization/SortVersion.cs b/src/mscorlib/shared/System/Globalization/SortVersion.cs
index a7aef6d..94c04d7 100644
--- a/src/mscorlib/shared/System/Globalization/SortVersion.cs
+++ b/src/mscorlib/shared/System/Globalization/SortVersion.cs
@@ -7,14 +7,14 @@ namespace System.Globalization
[Serializable]
public sealed class SortVersion : IEquatable<SortVersion>
{
- private int _nlsVersion;
- private Guid _sortId;
+ private int m_NlsVersion; // Do not rename (binary serialization)
+ private Guid m_SortId; // Do not rename (binary serialization)
public int FullVersion
{
get
{
- return _nlsVersion;
+ return m_NlsVersion;
}
}
@@ -22,19 +22,19 @@ namespace System.Globalization
{
get
{
- return _sortId;
+ return m_SortId;
}
}
public SortVersion(int fullVersion, Guid sortId)
{
- _sortId = sortId;
- _nlsVersion = fullVersion;
+ m_SortId = sortId;
+ m_NlsVersion = fullVersion;
}
internal SortVersion(int nlsVersion, int effectiveId, Guid customVersion)
{
- _nlsVersion = nlsVersion;
+ m_NlsVersion = nlsVersion;
if (customVersion == Guid.Empty)
{
@@ -45,7 +45,7 @@ namespace System.Globalization
customVersion = new Guid(0, 0, 0, 0, 0, 0, 0, b1, b2, b3, b4);
}
- _sortId = customVersion;
+ m_SortId = customVersion;
}
public override bool Equals(object obj)
@@ -66,12 +66,12 @@ namespace System.Globalization
return false;
}
- return _nlsVersion == other._nlsVersion && _sortId == other._sortId;
+ return m_NlsVersion == other.m_NlsVersion && m_SortId == other.m_SortId;
}
public override int GetHashCode()
{
- return _nlsVersion * 7 | _sortId.GetHashCode();
+ return m_NlsVersion * 7 | m_SortId.GetHashCode();
}
public static bool operator ==(SortVersion left, SortVersion right)
diff --git a/src/mscorlib/shared/System/Globalization/StringInfo.cs b/src/mscorlib/shared/System/Globalization/StringInfo.cs
new file mode 100644
index 0000000..87d1b9f
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/StringInfo.cs
@@ -0,0 +1,373 @@
+// 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
+{
+ 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(nameof(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/shared/System/Globalization/TaiwanCalendar.cs b/src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs
index 2e735e0..ec41881 100644
--- a/src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs
@@ -21,7 +21,6 @@ namespace System.Globalization
** Taiwan 01/01/01 8088/12/31
============================================================================*/
- [Serializable]
public class TaiwanCalendar : Calendar
{
//
diff --git a/src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs
index 8ba1f27..1e2ec62 100644
--- a/src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs
@@ -15,7 +15,6 @@ namespace System.Globalization
** TaiwanLunisolar 1912/01/01 2050/13/29
*/
- [Serializable]
public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar
{
// Since
diff --git a/src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs b/src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs
index 9e6e304..e1646bf 100644
--- a/src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs
@@ -20,7 +20,6 @@ namespace System.Globalization
** Thai 0544/01/01 10542/12/31
============================================================================*/
- [Serializable]
public class ThaiBuddhistCalendar : Calendar
{
// Initialize our era info.
diff --git a/src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs b/src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs
index b7ba6d0..c03ac23 100644
--- a/src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs
@@ -15,7 +15,6 @@ namespace System.Globalization
** UmAlQura 1318/01/01 1500/12/30
*/
- [Serializable]
public partial class UmAlQuraCalendar : Calendar
{
internal const int MinCalendarYear = 1318;
diff --git a/src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs b/src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs
index 786c210..de09760 100644
--- a/src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs
+++ b/src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs
@@ -12,7 +12,6 @@ namespace System.IO
* the Win32 errorcode-as-HRESULT ERROR_PATH_NOT_FOUND (0x80070003)
* and STG_E_PATHNOTFOUND (0x80030003).
*/
- [Serializable]
public class DirectoryNotFoundException : IOException
{
public DirectoryNotFoundException()
@@ -36,6 +35,7 @@ namespace System.IO
protected DirectoryNotFoundException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/IO/EncodingCache.cs b/src/mscorlib/shared/System/IO/EncodingCache.cs
new file mode 100644
index 0000000..53379bc
--- /dev/null
+++ b/src/mscorlib/shared/System/IO/EncodingCache.cs
@@ -0,0 +1,13 @@
+// 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/shared/System/IO/EndOfStreamException.cs b/src/mscorlib/shared/System/IO/EndOfStreamException.cs
index 7c4b2b7..68e1b2c 100644
--- a/src/mscorlib/shared/System/IO/EndOfStreamException.cs
+++ b/src/mscorlib/shared/System/IO/EndOfStreamException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.IO
{
- [Serializable]
public class EndOfStreamException : IOException
{
public EndOfStreamException()
@@ -30,6 +29,7 @@ namespace System.IO
protected EndOfStreamException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/IO/FileAccess.cs b/src/mscorlib/shared/System/IO/FileAccess.cs
index c6e583b..1b70bae 100644
--- a/src/mscorlib/shared/System/IO/FileAccess.cs
+++ b/src/mscorlib/shared/System/IO/FileAccess.cs
@@ -9,7 +9,6 @@ namespace System.IO
// Contains constants for specifying the access you want for a file.
// You can have Read, Write or ReadWrite access.
//
- [Serializable]
[Flags]
public enum FileAccess
{
diff --git a/src/mscorlib/shared/System/IO/FileLoadException.cs b/src/mscorlib/shared/System/IO/FileLoadException.cs
index b5e197c..6fdf2d5 100644
--- a/src/mscorlib/shared/System/IO/FileLoadException.cs
+++ b/src/mscorlib/shared/System/IO/FileLoadException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.IO
{
- [Serializable]
public partial class FileLoadException : IOException
{
public FileLoadException()
@@ -83,20 +82,12 @@ namespace System.IO
protected FileLoadException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
- // Base class constructor will check info != null.
-
- FileName = info.GetString("FileLoad_FileName");
- FusionLog = info.GetString("FileLoad_FusionLog");
+ throw new PlatformNotSupportedException();
}
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("FileLoad_FileName", FileName, typeof(string));
- info.AddValue("FileLoad_FusionLog", FusionLog, typeof(string));
}
}
}
diff --git a/src/mscorlib/shared/System/IO/FileNotFoundException.cs b/src/mscorlib/shared/System/IO/FileNotFoundException.cs
index 5d86b8f..374c976 100644
--- a/src/mscorlib/shared/System/IO/FileNotFoundException.cs
+++ b/src/mscorlib/shared/System/IO/FileNotFoundException.cs
@@ -7,7 +7,6 @@ using System.Runtime.Serialization;
namespace System.IO
{
// Thrown when trying to access a file that doesn't exist on disk.
- [Serializable]
public partial class FileNotFoundException : IOException
{
public FileNotFoundException()
@@ -94,20 +93,12 @@ namespace System.IO
protected FileNotFoundException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
- // Base class constructor will check info != null.
-
- FileName = info.GetString("FileNotFound_FileName");
- FusionLog = info.GetString("FileNotFound_FusionLog");
+ throw new PlatformNotSupportedException();
}
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("FileNotFound_FileName", FileName, typeof(string));
- info.AddValue("FileNotFound_FusionLog", FusionLog, typeof(string));
}
}
}
diff --git a/src/mscorlib/shared/System/IO/FileStream.Win32.cs b/src/mscorlib/shared/System/IO/FileStream.Win32.cs
index 0045ebe..61cd007 100644
--- a/src/mscorlib/shared/System/IO/FileStream.Win32.cs
+++ b/src/mscorlib/shared/System/IO/FileStream.Win32.cs
@@ -2,13 +2,8 @@
// 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.Buffers;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
-using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
namespace System.IO
{
@@ -38,7 +33,8 @@ namespace System.IO
flagsAndAttributes |= (Interop.Kernel32.SecurityOptions.SECURITY_SQOS_PRESENT | Interop.Kernel32.SecurityOptions.SECURITY_ANONYMOUS);
// Don't pop up a dialog for reading from an empty floppy drive
- uint oldMode = Interop.Kernel32.SetErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS);
+ uint oldMode;
+ bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
SafeFileHandle fileHandle = Interop.Kernel32.CreateFile(_path, fAccess, share, ref secAttrs, mode, flagsAndAttributes, IntPtr.Zero);
@@ -70,7 +66,8 @@ namespace System.IO
}
finally
{
- Interop.Kernel32.SetErrorMode(oldMode);
+ if (success)
+ Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
}
}
diff --git a/src/mscorlib/shared/System/IO/FileStream.WinRT.cs b/src/mscorlib/shared/System/IO/FileStream.WinRT.cs
index 062b160..b9a9f8a 100644
--- a/src/mscorlib/shared/System/IO/FileStream.WinRT.cs
+++ b/src/mscorlib/shared/System/IO/FileStream.WinRT.cs
@@ -51,28 +51,10 @@ namespace System.IO
if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && _path.Length == PathInternal.GetRootLength(_path))
errorCode = Interop.Errors.ERROR_ACCESS_DENIED;
- throw Win32Marshal.GetExceptionForWin32Error(errorCode, $"{_path} {options} {fAccess} {share} {mode}");
+ throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path);
}
return fileHandle;
}
-
-#if PROJECTN
- // TODO: These internal methods should be removed once we start consuming updated CoreFX builds
- public static FileStream InternalOpen(string path, int bufferSize = 4096, bool useAsync = true)
- {
- return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync);
- }
-
- public static FileStream InternalCreate(string path, int bufferSize = 4096, bool useAsync = true)
- {
- return new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize, useAsync);
- }
-
- public static FileStream InternalAppend(string path, int bufferSize = 4096, bool useAsync = true)
- {
- return new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read, bufferSize, useAsync);
- }
-#endif
}
}
diff --git a/src/mscorlib/shared/System/IO/FileStream.Windows.cs b/src/mscorlib/shared/System/IO/FileStream.Windows.cs
index 7c09ae1..c036ee6 100644
--- a/src/mscorlib/shared/System/IO/FileStream.Windows.cs
+++ b/src/mscorlib/shared/System/IO/FileStream.Windows.cs
@@ -1599,7 +1599,7 @@ namespace System.IO
{
var awaitable = (AsyncCopyToAwaitable)ThreadPoolBoundHandle.GetNativeOverlappedState(pOVERLAP);
- Debug.Assert(awaitable._continuation != s_sentinel, "Sentinel must not have already been set as the continuation");
+ Debug.Assert(!ReferenceEquals(awaitable._continuation, s_sentinel), "Sentinel must not have already been set as the continuation");
awaitable._errorCode = errorCode;
awaitable._numBytes = numBytes;
@@ -1617,15 +1617,15 @@ namespace System.IO
}
public AsyncCopyToAwaitable GetAwaiter() => this;
- public bool IsCompleted => _continuation == s_sentinel;
+ public bool IsCompleted => ReferenceEquals(_continuation, s_sentinel);
public void GetResult() { }
public void OnCompleted(Action continuation) => UnsafeOnCompleted(continuation);
public void UnsafeOnCompleted(Action continuation)
{
- if (_continuation == s_sentinel ||
+ if (ReferenceEquals(_continuation, s_sentinel) ||
Interlocked.CompareExchange(ref _continuation, continuation, null) != null)
{
- Debug.Assert(_continuation == s_sentinel, $"Expected continuation set to s_sentinel, got ${_continuation}");
+ Debug.Assert(ReferenceEquals(_continuation, s_sentinel), $"Expected continuation set to s_sentinel, got ${_continuation}");
Task.Run(continuation);
}
}
diff --git a/src/mscorlib/shared/System/IO/Path.Unix.cs b/src/mscorlib/shared/System/IO/Path.Unix.cs
index 500c60a..68c5f70 100644
--- a/src/mscorlib/shared/System/IO/Path.Unix.cs
+++ b/src/mscorlib/shared/System/IO/Path.Unix.cs
@@ -23,7 +23,7 @@ namespace System.IO
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
- throw new ArgumentException(SR.Arg_PathIllegal);
+ throw new ArgumentException(SR.Arg_PathIllegal, nameof(path));
PathInternal.CheckInvalidPathChars(path);
@@ -193,10 +193,15 @@ namespace System.IO
return path.Length > 0 && path[0] == PathInternal.DirectorySeparatorChar;
}
+ // The resulting string is null if path is null. If the path is empty or
+ // only contains whitespace characters an ArgumentException gets thrown.
public static string GetPathRoot(string path)
{
if (path == null) return null;
- return IsPathRooted(path) ? PathInternal.DirectorySeparatorCharAsString : String.Empty;
+ if (string.IsNullOrWhiteSpace(path))
+ throw new ArgumentException(SR.Arg_PathIllegal, nameof(path));
+
+ return IsPathRooted(path) ? PathInternal.DirectorySeparatorCharAsString : String.Empty;
}
/// <summary>Gets whether the system is case-sensitive.</summary>
diff --git a/src/mscorlib/shared/System/IO/Path.Windows.cs b/src/mscorlib/shared/System/IO/Path.Windows.cs
index d6f0c62..1e573cd 100644
--- a/src/mscorlib/shared/System/IO/Path.Windows.cs
+++ b/src/mscorlib/shared/System/IO/Path.Windows.cs
@@ -136,10 +136,14 @@ namespace System.IO
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
- // The resulting string is null if path is null.
+ // The resulting string is null if path is null. If the path is empty or
+ // only contains whitespace characters an ArgumentException gets thrown.
public static string GetPathRoot(string path)
{
if (path == null) return null;
+ if (string.IsNullOrWhiteSpace(path))
+ throw new ArgumentException(SR.Arg_PathIllegal, nameof(path));
+
PathInternal.CheckInvalidPathChars(path);
// Need to return the normalized directory separator
diff --git a/src/mscorlib/shared/System/IO/Path.cs b/src/mscorlib/shared/System/IO/Path.cs
index b3a8783..9feb287 100644
--- a/src/mscorlib/shared/System/IO/Path.cs
+++ b/src/mscorlib/shared/System/IO/Path.cs
@@ -76,19 +76,23 @@ namespace System.IO
// "\\server\share").
public static string GetDirectoryName(string path)
{
- if (path != null)
+ if (string.IsNullOrWhiteSpace(path))
{
- PathInternal.CheckInvalidPathChars(path);
- path = PathInternal.NormalizeDirectorySeparators(path);
- int root = PathInternal.GetRootLength(path);
+ if (path == null) return null;
+ throw new ArgumentException(SR.Arg_PathIllegal, nameof(path));
+ }
- int i = path.Length;
- if (i > root)
- {
- while (i > root && !PathInternal.IsDirectorySeparator(path[--i])) ;
- return path.Substring(0, i);
- }
+ PathInternal.CheckInvalidPathChars(path);
+ path = PathInternal.NormalizeDirectorySeparators(path);
+ int root = PathInternal.GetRootLength(path);
+
+ int i = path.Length;
+ if (i > root)
+ {
+ while (i > root && !PathInternal.IsDirectorySeparator(path[--i])) ;
+ return path.Substring(0, i);
}
+
return null;
}
diff --git a/src/mscorlib/shared/System/IO/PathInternal.Unix.cs b/src/mscorlib/shared/System/IO/PathInternal.Unix.cs
index 08dc1d0..ac9c4e7 100644
--- a/src/mscorlib/shared/System/IO/PathInternal.Unix.cs
+++ b/src/mscorlib/shared/System/IO/PathInternal.Unix.cs
@@ -100,5 +100,10 @@ namespace System.IO
// As long as the path is rooted in Unix it doesn't use the current directory and therefore is fully qualified.
return !Path.IsPathRooted(path);
}
+
+ internal static string TrimEndingDirectorySeparator(string path) =>
+ path.Length > 1 && IsDirectorySeparator(path[path.Length - 1]) ? // exclude root "/"
+ path.Substring(0, path.Length - 1) :
+ path;
}
}
diff --git a/src/mscorlib/shared/System/IO/PathInternal.Windows.cs b/src/mscorlib/shared/System/IO/PathInternal.Windows.cs
index ee0dd54..ee2d29c 100644
--- a/src/mscorlib/shared/System/IO/PathInternal.Windows.cs
+++ b/src/mscorlib/shared/System/IO/PathInternal.Windows.cs
@@ -438,5 +438,10 @@ namespace System.IO
{
return IsDirectorySeparator(ch) || VolumeSeparatorChar == ch;
}
+
+ internal static string TrimEndingDirectorySeparator(string path) =>
+ EndsInDirectorySeparator(path) ?
+ path.Substring(0, path.Length - 1) :
+ path;
}
}
diff --git a/src/mscorlib/shared/System/IO/PathTooLongException.cs b/src/mscorlib/shared/System/IO/PathTooLongException.cs
index 613af05..64c8e6c 100644
--- a/src/mscorlib/shared/System/IO/PathTooLongException.cs
+++ b/src/mscorlib/shared/System/IO/PathTooLongException.cs
@@ -8,7 +8,6 @@ using System.Runtime.Serialization;
namespace System.IO
{
- [Serializable]
public class PathTooLongException : IOException
{
public PathTooLongException()
@@ -32,6 +31,7 @@ namespace System.IO
protected PathTooLongException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs
new file mode 100644
index 0000000..c8e720b
--- /dev/null
+++ b/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs
@@ -0,0 +1,64 @@
+// 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;
+
+ 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 = GCHandle.Alloc(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 (_pinningHandle.IsAllocated)
+ {
+ _pinningHandle.Free();
+ }
+
+ base.Dispose(disposing);
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs
new file mode 100644
index 0000000..b78f50f
--- /dev/null
+++ b/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs
@@ -0,0 +1,763 @@
+// 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.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Threading;
+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.
+ *
+ */
+
+ /// <summary>
+ /// Stream over a memory pointer or over a SafeBuffer
+ /// </summary>
+ public class UnmanagedMemoryStream : Stream
+ {
+ private SafeBuffer _buffer;
+ private unsafe byte* _mem;
+ private long _length;
+ private long _capacity;
+ private long _position;
+ private long _offset;
+ private FileAccess _access;
+ private bool _isOpen;
+ private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
+
+ /// <summary>
+ /// Creates a closed stream.
+ /// </summary>
+ // Needed for subclasses that need to map a file, etc.
+ protected UnmanagedMemoryStream()
+ {
+ unsafe
+ {
+ _mem = null;
+ }
+ _isOpen = false;
+ }
+
+ /// <summary>
+ /// Creates a stream over a SafeBuffer.
+ /// </summary>
+ /// <param name="buffer"></param>
+ /// <param name="offset"></param>
+ /// <param name="length"></param>
+ public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length)
+ {
+ Initialize(buffer, offset, length, FileAccess.Read);
+ }
+
+ /// <summary>
+ /// Creates a stream over a SafeBuffer.
+ /// </summary>
+ public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access)
+ {
+ Initialize(buffer, offset, length, access);
+ }
+
+ /// <summary>
+ /// Subclasses must call this method (or the other overload) to properly initialize all instance fields.
+ /// </summary>
+ /// <param name="buffer"></param>
+ /// <param name="offset"></param>
+ /// <param name="length"></param>
+ /// <param name="access"></param>
+ 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;
+ }
+
+ /// <summary>
+ /// Creates a stream over a byte*.
+ /// </summary>
+ [CLSCompliant(false)]
+ public unsafe UnmanagedMemoryStream(byte* pointer, long length)
+ {
+ Initialize(pointer, length, length, FileAccess.Read);
+ }
+
+ /// <summary>
+ /// Creates a stream over a byte*.
+ /// </summary>
+ [CLSCompliant(false)]
+ public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
+ {
+ Initialize(pointer, length, capacity, access);
+ }
+
+ /// <summary>
+ /// Subclasses must call this method (or the other overload) to properly initialize all instance fields.
+ /// </summary>
+ [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;
+ }
+
+ /// <summary>
+ /// Returns true if the stream can be read; otherwise returns false.
+ /// </summary>
+ public override bool CanRead
+ {
+ [Pure]
+ get { return _isOpen && (_access & FileAccess.Read) != 0; }
+ }
+
+ /// <summary>
+ /// Returns true if the stream can seek; otherwise returns false.
+ /// </summary>
+ public override bool CanSeek
+ {
+ [Pure]
+ get { return _isOpen; }
+ }
+
+ /// <summary>
+ /// Returns true if the stream can be written to; otherwise returns false.
+ /// </summary>
+ public override bool CanWrite
+ {
+ [Pure]
+ get { return _isOpen && (_access & FileAccess.Write) != 0; }
+ }
+
+ /// <summary>
+ /// Closes the stream. The stream's memory needs to be dealt with separately.
+ /// </summary>
+ /// <param name="disposing"></param>
+ 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);
+ }
+
+ /// <summary>
+ /// Since it's a memory stream, this method does nothing.
+ /// </summary>
+ public override void Flush()
+ {
+ if (!_isOpen) throw Error.GetStreamIsClosed();
+ }
+
+ /// <summary>
+ /// Since it's a memory stream, this method does nothing specific.
+ /// </summary>
+ /// <param name="cancellationToken"></param>
+ /// <returns></returns>
+ 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);
+ }
+ }
+
+ /// <summary>
+ /// Number of bytes in the stream.
+ /// </summary>
+ public override long Length
+ {
+ get
+ {
+ if (!_isOpen) throw Error.GetStreamIsClosed();
+ return Interlocked.Read(ref _length);
+ }
+ }
+
+ /// <summary>
+ /// Number of bytes that can be written to the stream.
+ /// </summary>
+ public long Capacity
+ {
+ get
+ {
+ if (!_isOpen) throw Error.GetStreamIsClosed();
+ return _capacity;
+ }
+ }
+
+ /// <summary>
+ /// ReadByte will read byte at the Position in the stream
+ /// </summary>
+ public override long Position
+ {
+ get
+ {
+ if (!CanSeek) throw Error.GetStreamIsClosed();
+ Contract.EndContractBlock();
+ return Interlocked.Read(ref _position);
+ }
+ set
+ {
+ if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
+ if (!CanSeek) throw Error.GetStreamIsClosed();
+ Contract.EndContractBlock();
+
+ Interlocked.Exchange(ref _position, value);
+ }
+ }
+
+ /// <summary>
+ /// Pointer to memory at the current Position in the stream.
+ /// </summary>
+ [CLSCompliant(false)]
+ public unsafe byte* PositionPointer
+ {
+ get
+ {
+ if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
+ if (!_isOpen) throw Error.GetStreamIsClosed();
+
+ // 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;
+ return ptr;
+ }
+ set
+ {
+ if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
+ if (!_isOpen) throw Error.GetStreamIsClosed();
+
+ if (value < _mem)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ long newPosition = (long)value - (long)_mem;
+ if (newPosition < 0)
+ throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
+
+ Interlocked.Exchange(ref _position, newPosition);
+ }
+ }
+
+ /// <summary>
+ /// Reads bytes from stream and puts them into the buffer
+ /// </summary>
+ /// <param name="buffer">Buffer to read the bytes to.</param>
+ /// <param name="offset">Starting index in the buffer.</param>
+ /// <param name="count">Maximum number of bytes to read.</param>
+ /// <returns>Number of bytes actually read.</returns>
+ public override int Read(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) throw Error.GetStreamIsClosed();
+ if (!CanRead) throw Error.GetReadNotSupported();
+
+ // 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;
+ }
+
+ /// <summary>
+ /// Reads bytes from stream and puts them into the buffer
+ /// </summary>
+ /// <param name="buffer">Buffer to read the bytes to.</param>
+ /// <param name="offset">Starting index in the buffer.</param>
+ /// <param name="count">Maximum number of bytes to read.</param>
+ /// <param name="cancellationToken">Token that can be used to cancel this operation.</param>
+ /// <returns>Task that can be used to access the number of bytes actually read.</returns>
+ 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);
+ }
+ }
+
+ /// <summary>
+ /// Returns the byte at the stream current Position and advances the Position.
+ /// </summary>
+ /// <returns></returns>
+ public override int ReadByte()
+ {
+ if (!_isOpen) throw Error.GetStreamIsClosed();
+ if (!CanRead) throw Error.GetReadNotSupported();
+
+ 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;
+ }
+
+ /// <summary>
+ /// Advanced the Position to specific location in the stream.
+ /// </summary>
+ /// <param name="offset">Offset from the loc parameter.</param>
+ /// <param name="loc">Origin for the offset parameter.</param>
+ /// <returns></returns>
+ public override long Seek(long offset, SeekOrigin loc)
+ {
+ if (!_isOpen) throw Error.GetStreamIsClosed();
+ 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;
+ }
+
+ /// <summary>
+ /// Sets the Length of the stream.
+ /// </summary>
+ /// <param name="value"></param>
+ public override void SetLength(long value)
+ {
+ if (value < 0)
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
+ Contract.EndContractBlock();
+ if (_buffer != null)
+ throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
+ if (!_isOpen) throw Error.GetStreamIsClosed();
+ if (!CanWrite) throw Error.GetWriteNotSupported();
+
+ 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);
+ }
+ }
+
+ /// <summary>
+ /// Writes buffer into the stream
+ /// </summary>
+ /// <param name="buffer">Buffer that will be written.</param>
+ /// <param name="offset">Starting index in the buffer.</param>
+ /// <param name="count">Number of bytes to write.</param>
+ 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) throw Error.GetStreamIsClosed();
+ if (!CanWrite) throw Error.GetWriteNotSupported();
+
+ 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;
+ }
+
+ /// <summary>
+ /// Writes buffer into the stream. The operation completes synchronously.
+ /// </summary>
+ /// <param name="buffer">Buffer that will be written.</param>
+ /// <param name="offset">Starting index in the buffer.</param>
+ /// <param name="count">Number of bytes to write.</param>
+ /// <param name="cancellationToken">Token that can be used to cancel the operation.</param>
+ /// <returns>Task that can be awaited </returns>
+ 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(ex);
+ }
+ }
+
+ /// <summary>
+ /// Writes a byte to the stream and advances the current Position.
+ /// </summary>
+ /// <param name="value"></param>
+ public override void WriteByte(byte value)
+ {
+ if (!_isOpen) throw Error.GetStreamIsClosed();
+ if (!CanWrite) throw Error.GetWriteNotSupported();
+
+ 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/shared/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs
new file mode 100644
index 0000000..d547e77
--- /dev/null
+++ b/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs
@@ -0,0 +1,210 @@
+// 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
+ {
+ get { return _unmanagedStream.CanRead; }
+ }
+
+ public override bool CanSeek
+ {
+ get { return _unmanagedStream.CanSeek; }
+ }
+
+ public override bool CanWrite
+ {
+ get { return _unmanagedStream.CanWrite; }
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ try
+ {
+ if (disposing)
+ _unmanagedStream.Dispose();
+ }
+ 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(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()
+ {
+ byte[] buffer = new byte[_unmanagedStream.Length];
+ _unmanagedStream.Read(buffer, 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();
+
+ 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/shared/System/IndexOutOfRangeException.cs b/src/mscorlib/shared/System/IndexOutOfRangeException.cs
index 4969c2b..d5b24b3 100644
--- a/src/mscorlib/shared/System/IndexOutOfRangeException.cs
+++ b/src/mscorlib/shared/System/IndexOutOfRangeException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public sealed class IndexOutOfRangeException : SystemException
{
public IndexOutOfRangeException()
@@ -35,7 +34,5 @@ namespace System
{
HResult = __HResults.COR_E_INDEXOUTOFRANGE;
}
-
- internal IndexOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/shared/System/InsufficientExecutionStackException.cs b/src/mscorlib/shared/System/InsufficientExecutionStackException.cs
index b9a4a12..41df3ae 100644
--- a/src/mscorlib/shared/System/InsufficientExecutionStackException.cs
+++ b/src/mscorlib/shared/System/InsufficientExecutionStackException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public sealed class InsufficientExecutionStackException : SystemException
{
public InsufficientExecutionStackException()
@@ -26,7 +25,5 @@ namespace System
{
HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
}
-
- internal InsufficientExecutionStackException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/shared/System/InvalidCastException.cs b/src/mscorlib/shared/System/InvalidCastException.cs
index 01d92b2..cf359ac 100644
--- a/src/mscorlib/shared/System/InvalidCastException.cs
+++ b/src/mscorlib/shared/System/InvalidCastException.cs
@@ -12,7 +12,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class InvalidCastException : SystemException
{
public InvalidCastException()
@@ -39,6 +38,9 @@ namespace System
HResult = errorCode;
}
- protected InvalidCastException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected InvalidCastException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/InvalidOperationException.cs b/src/mscorlib/shared/System/InvalidOperationException.cs
index 24a08c8..ad743e0 100644
--- a/src/mscorlib/shared/System/InvalidOperationException.cs
+++ b/src/mscorlib/shared/System/InvalidOperationException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class InvalidOperationException : SystemException
{
public InvalidOperationException()
@@ -37,6 +36,9 @@ namespace System
HResult = __HResults.COR_E_INVALIDOPERATION;
}
- protected InvalidOperationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected InvalidOperationException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/InvalidProgramException.cs b/src/mscorlib/shared/System/InvalidProgramException.cs
index 401b3a0..47e7325 100644
--- a/src/mscorlib/shared/System/InvalidProgramException.cs
+++ b/src/mscorlib/shared/System/InvalidProgramException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public sealed class InvalidProgramException : SystemException
{
public InvalidProgramException()
@@ -35,7 +34,5 @@ namespace System
{
HResult = __HResults.COR_E_INVALIDPROGRAM;
}
-
- internal InvalidProgramException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/shared/System/InvalidTimeZoneException.cs b/src/mscorlib/shared/System/InvalidTimeZoneException.cs
index 8f0751c..8b300f4 100644
--- a/src/mscorlib/shared/System/InvalidTimeZoneException.cs
+++ b/src/mscorlib/shared/System/InvalidTimeZoneException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class InvalidTimeZoneException : Exception
{
public InvalidTimeZoneException()
@@ -23,6 +22,9 @@ namespace System
{
}
- protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/Lazy.cs b/src/mscorlib/shared/System/Lazy.cs
index 55f915b..5d68714 100644
--- a/src/mscorlib/shared/System/Lazy.cs
+++ b/src/mscorlib/shared/System/Lazy.cs
@@ -182,7 +182,6 @@ namespace System
/// using parameters to the type's constructors.
/// </para>
/// </remarks>
- [Serializable]
[DebuggerTypeProxy(typeof(System_LazyDebugView<>))]
[DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")]
public class Lazy<T>
@@ -202,7 +201,7 @@ namespace System
private Func<T> _factory;
// _value eventually stores the lazily created value. It is valid when _state = null.
- private T _value;
+ private T m_value; // Do not rename (binary serialization)
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that
@@ -226,7 +225,7 @@ namespace System
/// </remarks>
public Lazy(T value)
{
- _value = value;
+ m_value = value;
}
/// <summary>
@@ -312,7 +311,7 @@ namespace System
private void ViaConstructor()
{
- _value = CreateViaDefaultConstructor();
+ m_value = CreateViaDefaultConstructor();
_state = null; // volatile write, must occur after setting _value
}
@@ -325,7 +324,7 @@ namespace System
throw new InvalidOperationException(SR.Lazy_Value_RecursiveCallsToValue);
_factory = null;
- _value = factory();
+ m_value = factory();
_state = null; // volatile write, must occur after setting _value
}
catch (Exception exception)
@@ -361,7 +360,7 @@ namespace System
if (previous == publicationOnly)
{
_factory = null;
- _value = possibleValue;
+ m_value = possibleValue;
_state = null; // volatile write, must occur after setting _value
}
}
@@ -469,7 +468,7 @@ namespace System
{
return default(T);
}
- return _value;
+ return m_value;
}
}
@@ -516,7 +515,7 @@ namespace System
/// from initialization delegate.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
- public T Value => _state == null ? _value : CreateValue();
+ public T Value => _state == null ? m_value : CreateValue();
}
/// <summary>A debugger view of the Lazy&lt;T&gt; to surface additional debugging properties and
diff --git a/src/mscorlib/shared/System/MarshalByRefObject.cs b/src/mscorlib/shared/System/MarshalByRefObject.cs
index 1f1739b..390b7283 100644
--- a/src/mscorlib/shared/System/MarshalByRefObject.cs
+++ b/src/mscorlib/shared/System/MarshalByRefObject.cs
@@ -4,7 +4,6 @@
namespace System
{
- [Serializable]
public abstract class MarshalByRefObject
{
protected MarshalByRefObject()
diff --git a/src/mscorlib/shared/System/MemberAccessException.cs b/src/mscorlib/shared/System/MemberAccessException.cs
index 54eee67..abca952 100644
--- a/src/mscorlib/shared/System/MemberAccessException.cs
+++ b/src/mscorlib/shared/System/MemberAccessException.cs
@@ -15,7 +15,6 @@ namespace System
// The MemberAccessException is thrown when trying to access a class
// member fails.
//
- [Serializable]
public class MemberAccessException : SystemException
{
// Creates a new MemberAccessException with its message string set to
@@ -43,6 +42,9 @@ namespace System
HResult = __HResults.COR_E_MEMBERACCESS;
}
- protected MemberAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected MemberAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/MethodAccessException.cs b/src/mscorlib/shared/System/MethodAccessException.cs
index 2ecbd14..2c9c998 100644
--- a/src/mscorlib/shared/System/MethodAccessException.cs
+++ b/src/mscorlib/shared/System/MethodAccessException.cs
@@ -13,7 +13,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class MethodAccessException : MemberAccessException
{
public MethodAccessException()
@@ -34,6 +33,9 @@ namespace System
HResult = __HResults.COR_E_METHODACCESS;
}
- protected MethodAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected MethodAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/MissingMethodException.cs b/src/mscorlib/shared/System/MissingMethodException.cs
index 07d4289..967f434 100644
--- a/src/mscorlib/shared/System/MissingMethodException.cs
+++ b/src/mscorlib/shared/System/MissingMethodException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class MissingMethodException : MissingMemberException
{
public MissingMethodException()
@@ -45,6 +44,7 @@ namespace System
protected MissingMethodException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
public override string Message
diff --git a/src/mscorlib/shared/System/MulticastNotSupportedException.cs b/src/mscorlib/shared/System/MulticastNotSupportedException.cs
index 4fcaa98..493671e 100644
--- a/src/mscorlib/shared/System/MulticastNotSupportedException.cs
+++ b/src/mscorlib/shared/System/MulticastNotSupportedException.cs
@@ -11,7 +11,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public sealed class MulticastNotSupportedException : SystemException
{
public MulticastNotSupportedException()
@@ -31,7 +30,5 @@ namespace System
{
HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
}
-
- internal MulticastNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/shared/System/NotFiniteNumberException.cs b/src/mscorlib/shared/System/NotFiniteNumberException.cs
index 5bc8df1..99882b9 100644
--- a/src/mscorlib/shared/System/NotFiniteNumberException.cs
+++ b/src/mscorlib/shared/System/NotFiniteNumberException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class NotFiniteNumberException : ArithmeticException
{
private double _offendingNumber;
@@ -54,13 +53,12 @@ namespace System
protected NotFiniteNumberException(SerializationInfo info, StreamingContext context) : base(info, context)
{
- _offendingNumber = info.GetInt32("OffendingNumber");
+ throw new PlatformNotSupportedException();
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
- info.AddValue("OffendingNumber", _offendingNumber, typeof(Int32));
}
public double OffendingNumber
diff --git a/src/mscorlib/shared/System/NotImplementedException.cs b/src/mscorlib/shared/System/NotImplementedException.cs
index 4d141ea..ae62527 100644
--- a/src/mscorlib/shared/System/NotImplementedException.cs
+++ b/src/mscorlib/shared/System/NotImplementedException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class NotImplementedException : SystemException
{
public NotImplementedException()
@@ -35,6 +34,9 @@ namespace System
HResult = __HResults.E_NOTIMPL;
}
- protected NotImplementedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected NotImplementedException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/NotSupportedException.cs b/src/mscorlib/shared/System/NotSupportedException.cs
index 21b2d54..8532e5a 100644
--- a/src/mscorlib/shared/System/NotSupportedException.cs
+++ b/src/mscorlib/shared/System/NotSupportedException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class NotSupportedException : SystemException
{
public NotSupportedException()
@@ -36,6 +35,9 @@ namespace System
HResult = __HResults.COR_E_NOTSUPPORTED;
}
- protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/NullReferenceException.cs b/src/mscorlib/shared/System/NullReferenceException.cs
index 0aa5c61..f689345 100644
--- a/src/mscorlib/shared/System/NullReferenceException.cs
+++ b/src/mscorlib/shared/System/NullReferenceException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class NullReferenceException : SystemException
{
public NullReferenceException()
@@ -36,6 +35,9 @@ namespace System
HResult = __HResults.COR_E_NULLREFERENCE;
}
- protected NullReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected NullReferenceException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/ObjectDisposedException.cs b/src/mscorlib/shared/System/ObjectDisposedException.cs
index abb7c89..6e8e6b2 100644
--- a/src/mscorlib/shared/System/ObjectDisposedException.cs
+++ b/src/mscorlib/shared/System/ObjectDisposedException.cs
@@ -11,7 +11,6 @@ namespace System
/// <para> The exception that is thrown when accessing an object that was
/// disposed.</para>
/// </devdoc>
- [Serializable]
public class ObjectDisposedException : InvalidOperationException
{
private String _objectName;
@@ -42,13 +41,12 @@ namespace System
protected ObjectDisposedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
- _objectName = info.GetString("ObjectName");
+ throw new PlatformNotSupportedException();
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
- info.AddValue("ObjectName", ObjectName, typeof(String));
}
/// <devdoc>
diff --git a/src/mscorlib/shared/System/ObsoleteAttribute.cs b/src/mscorlib/shared/System/ObsoleteAttribute.cs
index f183685..a63db13 100644
--- a/src/mscorlib/shared/System/ObsoleteAttribute.cs
+++ b/src/mscorlib/shared/System/ObsoleteAttribute.cs
@@ -21,7 +21,6 @@ namespace System
// error. (this would be used if the actual implementation of the obsolete
// method's implementation had changed).
//
- [Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum |
AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate
, Inherited = false)]
diff --git a/src/mscorlib/shared/System/OperationCanceledException.cs b/src/mscorlib/shared/System/OperationCanceledException.cs
new file mode 100644
index 0000000..2c76548
--- /dev/null
+++ b/src/mscorlib/shared/System/OperationCanceledException.cs
@@ -0,0 +1,73 @@
+// 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
+{
+ 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)
+ {
+ throw new PlatformNotSupportedException();
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/OverflowException.cs b/src/mscorlib/shared/System/OverflowException.cs
index e28c688..4052e41 100644
--- a/src/mscorlib/shared/System/OverflowException.cs
+++ b/src/mscorlib/shared/System/OverflowException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class OverflowException : ArithmeticException
{
public OverflowException()
@@ -36,6 +35,9 @@ namespace System
HResult = __HResults.COR_E_OVERFLOW;
}
- protected OverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected OverflowException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/PlatformNotSupportedException.cs b/src/mscorlib/shared/System/PlatformNotSupportedException.cs
index d2370b3..f679ac9 100644
--- a/src/mscorlib/shared/System/PlatformNotSupportedException.cs
+++ b/src/mscorlib/shared/System/PlatformNotSupportedException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class PlatformNotSupportedException : NotSupportedException
{
public PlatformNotSupportedException()
@@ -36,6 +35,9 @@ namespace System
HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
}
- protected PlatformNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected PlatformNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/Random.cs b/src/mscorlib/shared/System/Random.cs
index a66a9ea..4affed8 100644
--- a/src/mscorlib/shared/System/Random.cs
+++ b/src/mscorlib/shared/System/Random.cs
@@ -18,7 +18,6 @@ using System.Diagnostics.Contracts;
namespace System
{
- [Serializable]
public class Random
{
//
diff --git a/src/mscorlib/shared/System/RankException.cs b/src/mscorlib/shared/System/RankException.cs
index 612d0f0..15759ea 100644
--- a/src/mscorlib/shared/System/RankException.cs
+++ b/src/mscorlib/shared/System/RankException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class RankException : SystemException
{
public RankException()
@@ -37,6 +36,9 @@ namespace System
HResult = __HResults.COR_E_RANK;
}
- protected RankException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected RankException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs b/src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs
index 459a19c..a0075bb 100644
--- a/src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs
+++ b/src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
public sealed class AmbiguousMatchException : SystemException
{
public AmbiguousMatchException()
@@ -26,10 +25,5 @@ namespace System.Reflection
{
HResult = __HResults.COR_E_AMBIGUOUSMATCH;
}
-
- internal AmbiguousMatchException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
}
}
diff --git a/src/mscorlib/shared/System/Reflection/Assembly.cs b/src/mscorlib/shared/System/Reflection/Assembly.cs
index d35ffc7..b965c9f 100644
--- a/src/mscorlib/shared/System/Reflection/Assembly.cs
+++ b/src/mscorlib/shared/System/Reflection/Assembly.cs
@@ -125,7 +125,10 @@ namespace System.Reflection
public virtual FileStream[] GetFiles() => GetFiles(getResourceModules: false);
public virtual FileStream[] GetFiles(bool getResourceModules) { throw NotImplemented.ByDesign; }
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw NotImplemented.ByDesign; }
+ public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ throw new PlatformNotSupportedException();
+ }
public override string ToString()
{
diff --git a/src/mscorlib/shared/System/Reflection/AssemblyNameFormatter.cs b/src/mscorlib/shared/System/Reflection/AssemblyNameFormatter.cs
new file mode 100644
index 0000000..7c4a980
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/AssemblyNameFormatter.cs
@@ -0,0 +1,156 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.IO;
+using System.Text;
+using System.Globalization;
+using System.Collections.Generic;
+
+namespace System.Reflection
+{
+ internal static class AssemblyNameFormatter
+ {
+ public static string ComputeDisplayName(string name, Version version, string cultureName, byte[] pkt, AssemblyNameFlags flags, AssemblyContentType contentType)
+ {
+ const int PUBLIC_KEY_TOKEN_LEN = 8;
+
+ if (name == string.Empty)
+ throw new FileLoadException();
+
+ StringBuilder sb = new StringBuilder();
+ if (name != null)
+ {
+ sb.AppendQuoted(name);
+ }
+
+ if (version != null)
+ {
+ Version canonicalizedVersion = version.CanonicalizeVersion();
+ if (canonicalizedVersion.Major != ushort.MaxValue)
+ {
+ sb.Append(", Version=");
+ sb.Append(canonicalizedVersion.Major);
+
+ if (canonicalizedVersion.Minor != ushort.MaxValue)
+ {
+ sb.Append('.');
+ sb.Append(canonicalizedVersion.Minor);
+
+ if (canonicalizedVersion.Build != ushort.MaxValue)
+ {
+ sb.Append('.');
+ sb.Append(canonicalizedVersion.Build);
+
+ if (canonicalizedVersion.Revision != ushort.MaxValue)
+ {
+ sb.Append('.');
+ sb.Append(canonicalizedVersion.Revision);
+ }
+ }
+ }
+ }
+ }
+
+ if (cultureName != null)
+ {
+ if (cultureName == string.Empty)
+ cultureName = "neutral";
+ sb.Append(", Culture=");
+ sb.AppendQuoted(cultureName);
+ }
+
+ if (pkt != null)
+ {
+ if (pkt.Length > PUBLIC_KEY_TOKEN_LEN)
+ throw new ArgumentException();
+
+ sb.Append(", PublicKeyToken=");
+ if (pkt.Length == 0)
+ sb.Append("null");
+ else
+ {
+ foreach (byte b in pkt)
+ {
+ sb.Append(b.ToString("x2", CultureInfo.InvariantCulture));
+ }
+ }
+ }
+
+ if (0 != (flags & AssemblyNameFlags.Retargetable))
+ sb.Append(", Retargetable=Yes");
+
+ if (contentType == AssemblyContentType.WindowsRuntime)
+ sb.Append(", ContentType=WindowsRuntime");
+
+ // NOTE: By design (desktop compat) AssemblyName.FullName and ToString() do not include ProcessorArchitecture.
+
+ return sb.ToString();
+ }
+
+ private static void AppendQuoted(this StringBuilder sb, string s)
+ {
+ bool needsQuoting = false;
+ const char quoteChar = '\"';
+
+ //@todo: App-compat: You can use double or single quotes to quote a name, and Fusion (or rather the IdentityAuthority) picks one
+ // by some algorithm. Rather than guess at it, I'll just use double-quote consistently.
+ if (s != s.Trim() || s.Contains("\"") || s.Contains("\'"))
+ needsQuoting = true;
+
+ if (needsQuoting)
+ sb.Append(quoteChar);
+
+ for (int i = 0; i < s.Length; i++)
+ {
+ bool addedEscape = false;
+ foreach (KeyValuePair<char, string> kv in EscapeSequences)
+ {
+ string escapeReplacement = kv.Value;
+ if (!(s[i] == escapeReplacement[0]))
+ continue;
+ if ((s.Length - i) < escapeReplacement.Length)
+ continue;
+ string prefix = s.Substring(i, escapeReplacement.Length);
+ if (prefix == escapeReplacement)
+ {
+ sb.Append('\\');
+ sb.Append(kv.Key);
+ addedEscape = true;
+ }
+ }
+
+ if (!addedEscape)
+ sb.Append(s[i]);
+ }
+
+ if (needsQuoting)
+ sb.Append(quoteChar);
+ }
+
+ private static Version CanonicalizeVersion(this Version version)
+ {
+ ushort major = (ushort)version.Major;
+ ushort minor = (ushort)version.Minor;
+ ushort build = (ushort)version.Build;
+ ushort revision = (ushort)version.Revision;
+
+ if (major == version.Major && minor == version.Minor && build == version.Build && revision == version.Revision)
+ return version;
+
+ return new Version(major, minor, build, revision);
+ }
+
+ public static KeyValuePair<char, string>[] EscapeSequences =
+ {
+ new KeyValuePair<char, string>('\\', "\\"),
+ new KeyValuePair<char, string>(',', ","),
+ new KeyValuePair<char, string>('=', "="),
+ new KeyValuePair<char, string>('\'', "'"),
+ new KeyValuePair<char, string>('\"', "\""),
+ new KeyValuePair<char, string>('n', Environment.NewLine),
+ new KeyValuePair<char, string>('t', "\t"),
+ };
+ }
+}
+
diff --git a/src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs b/src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs
index 6e11540..13766ae 100644
--- a/src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs
+++ b/src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
public class CustomAttributeFormatException : FormatException
{
public CustomAttributeFormatException()
@@ -28,6 +27,7 @@ namespace System.Reflection
protected CustomAttributeFormatException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Reflection/DefaultMemberAttribute.cs b/src/mscorlib/shared/System/Reflection/DefaultMemberAttribute.cs
index 3511433..585fdb0 100644
--- a/src/mscorlib/shared/System/Reflection/DefaultMemberAttribute.cs
+++ b/src/mscorlib/shared/System/Reflection/DefaultMemberAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Reflection
{
- [Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)]
public sealed class DefaultMemberAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs b/src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs
index e3f882c..07880a7 100644
--- a/src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs
+++ b/src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
public class InvalidFilterCriteriaException : ApplicationException
{
public InvalidFilterCriteriaException()
@@ -28,6 +27,7 @@ namespace System.Reflection
protected InvalidFilterCriteriaException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Reflection/MemberInfoSerializationHolder.cs b/src/mscorlib/shared/System/Reflection/MemberInfoSerializationHolder.cs
deleted file mode 100644
index dfc5666..0000000
--- a/src/mscorlib/shared/System/Reflection/MemberInfoSerializationHolder.cs
+++ /dev/null
@@ -1,315 +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.Serialization;
-using System.Globalization;
-using System.Diagnostics.Contracts;
-
-namespace System.Reflection
-{
- [Serializable]
-#if CORECLR
- internal
-#else
- public // On CoreRT, this must be public because of the Reflection.Core/CoreLib divide and the need to whitelist past the ReflectionBlock.
-#endif
- class MemberInfoSerializationHolder : ISerializable, IObjectReference
- {
- #region Staitc Public Members
- public static void GetSerializationInfo(SerializationInfo info, FieldInfo f)
- {
- // Compat: Serializing ToString() since the full framework does it but the deserialization logic makes no use of it.
- GetSerializationInfo(info, f.Name, f.ReflectedType, f.ToString(), MemberTypes.Field);
- }
-
- public static void GetSerializationInfo(SerializationInfo info, EventInfo e)
- {
- GetSerializationInfo(info, e.Name, e.ReflectedType, null, MemberTypes.Event);
- }
-
- public static void GetSerializationInfo(SerializationInfo info, ConstructorInfo c)
- {
- GetSerializationInfo(info, c.Name, c.ReflectedType, c.ToString(), c.SerializationToString(), MemberTypes.Constructor, genericArguments: null);
- }
-
- public static void GetSerializationInfo(SerializationInfo info, MethodInfo m)
- {
- Type[] genericArguments = m.IsConstructedGenericMethod ? m.GetGenericArguments() : null;
- GetSerializationInfo(info, m.Name, m.ReflectedType, m.ToString(), m.SerializationToString(), MemberTypes.Method, genericArguments);
- }
-
- public static void GetSerializationInfo(SerializationInfo info, PropertyInfo p)
- {
- GetSerializationInfo(info, p.Name, p.ReflectedType, p.ToString(), p.SerializationToString(), MemberTypes.Property, genericArguments: null);
- }
- #endregion
-
- #region Private Static Members
- private static void GetSerializationInfo(SerializationInfo info, string name, Type reflectedClass, string signature, MemberTypes type)
- {
- GetSerializationInfo(info, name, reflectedClass, signature, null, type, null);
- }
-
- private static void GetSerializationInfo(
- SerializationInfo info,
- string name,
- Type reflectedClass,
- string signature,
- string signature2,
- MemberTypes type,
- Type[] genericArguments)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- string assemblyName = reflectedClass.Module.Assembly.FullName;
- string typeName = reflectedClass.FullName;
-
- info.SetType(typeof(MemberInfoSerializationHolder));
- info.AddValue("Name", name, typeof(string));
- info.AddValue("AssemblyName", assemblyName, typeof(string));
- info.AddValue("ClassName", typeName, typeof(string));
- info.AddValue("Signature", signature, typeof(string));
- info.AddValue("Signature2", signature2, typeof(string));
- info.AddValue("MemberType", (int)type);
- info.AddValue("GenericArguments", genericArguments, typeof(Type[]));
- }
- #endregion
-
- #region Private Data Members
- private readonly string _memberName;
- private readonly Type _reflectedType;
- // _signature stores the ToString() representation of the member which is sometimes ambiguous.
- // Mulitple overloads of the same methods or properties can identical ToString().
- // _signature2 stores the SerializationToString() representation which should be unique for each member.
- // It is only written and used by post 4.0 CLR versions.
- private readonly string _signature;
- private readonly string _signature2;
- private readonly MemberTypes _memberType;
- private readonly SerializationInfo _info;
- #endregion
-
- #region Constructor
- // Needs to be public so it can be whitelisted in Reflection.
- public MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- string assemblyName = info.GetString("AssemblyName");
- string typeName = info.GetString("ClassName");
-
- if (assemblyName == null || typeName == null)
- throw new SerializationException(SR.Serialization_InsufficientState);
-
- Assembly assem = Assembly.Load(assemblyName);
- _reflectedType = assem.GetType(typeName, true, false);
- _memberName = info.GetString("Name");
- _signature = info.GetString("Signature");
- // Only v4.0 and later generates and consumes Signature2
- _signature2 = (string)info.GetValueNoThrow("Signature2", typeof(string));
- _memberType = (MemberTypes)info.GetInt32("MemberType");
- _info = info;
- }
- #endregion
-
- #region ISerializable
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- throw new NotSupportedException();
- }
- #endregion
-
- #region IObjectReference
- public virtual object GetRealObject(StreamingContext context)
- {
- if (_memberName == null || _reflectedType == null || _memberType == 0)
- throw new SerializationException(SR.Serialization_InsufficientState);
-
- BindingFlags bindingFlags =
- BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
- BindingFlags.Static | BindingFlags.OptionalParamBinding;
-
- switch (_memberType)
- {
- #region case MemberTypes.Field:
- case MemberTypes.Field:
- {
- FieldInfo[] fields = _reflectedType.GetMember(_memberName, MemberTypes.Field, bindingFlags) as FieldInfo[];
-
- if (fields.Length == 0)
- throw new SerializationException(SR.Format(SR.Serialization_UnknownMember, _memberName));
-
- return fields[0];
- }
- #endregion
-
- #region case MemberTypes.Event:
- case MemberTypes.Event:
- {
- EventInfo[] events = _reflectedType.GetMember(_memberName, MemberTypes.Event, bindingFlags) as EventInfo[];
-
- if (events.Length == 0)
- throw new SerializationException(SR.Format(SR.Serialization_UnknownMember, _memberName));
-
- return events[0];
- }
- #endregion
-
- #region case MemberTypes.Property:
- case MemberTypes.Property:
- {
- PropertyInfo[] properties = _reflectedType.GetMember(_memberName, MemberTypes.Property, bindingFlags) as PropertyInfo[];
-
- if (properties.Length == 0)
- throw new SerializationException(SR.Format(SR.Serialization_UnknownMember, _memberName));
-
- if (properties.Length == 1)
- return properties[0];
-
- if (properties.Length > 1)
- {
- for (int i = 0; i < properties.Length; i++)
- {
- if (_signature2 != null)
- {
- if (properties[i].SerializationToString().Equals(_signature2))
- return properties[i];
- }
- else
- {
- if ((properties[i]).ToString().Equals(_signature))
- return properties[i];
- }
- }
- }
-
- throw new SerializationException(SR.Format(SR.Serialization_UnknownMember, _memberName));
- }
- #endregion
-
- #region case MemberTypes.Constructor:
- case MemberTypes.Constructor:
- {
- if (_signature == null)
- throw new SerializationException(SR.Serialization_NullSignature);
-
- ConstructorInfo[] constructors = _reflectedType.GetMember(_memberName, MemberTypes.Constructor, bindingFlags) as ConstructorInfo[];
-
- if (constructors.Length == 1)
- return constructors[0];
-
- if (constructors.Length > 1)
- {
- for (int i = 0; i < constructors.Length; i++)
- {
- if (_signature2 != null)
- {
- if (constructors[i].SerializationToString().Equals(_signature2))
- return constructors[i];
- }
- else
- {
- if (constructors[i].ToString().Equals(_signature))
- return constructors[i];
- }
- }
- }
-
- throw new SerializationException(SR.Format(SR.Serialization_UnknownMember, _memberName));
- }
- #endregion
-
- #region case MemberTypes.Method:
- case MemberTypes.Method:
- {
- MethodInfo methodInfo = null;
-
- if (_signature == null)
- throw new SerializationException(SR.Serialization_NullSignature);
-
- Type[] genericArguments = _info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[];
-
- MethodInfo[] methods = _reflectedType.GetMember(_memberName, MemberTypes.Method, bindingFlags) as MethodInfo[];
-
- if (methods.Length == 1)
- methodInfo = methods[0];
-
- else if (methods.Length > 1)
- {
- for (int i = 0; i < methods.Length; i++)
- {
- if (_signature2 != null)
- {
- if (methods[i].SerializationToString().Equals(_signature2))
- {
- methodInfo = methods[i];
- break;
- }
- }
- else
- {
- if (methods[i].ToString().Equals(_signature))
- {
- methodInfo = methods[i];
- break;
- }
- }
-
- // Handle generic methods specially since the signature match above probably won't work (the candidate
- // method info hasn't been instantiated). If our target method is generic as well we can skip this.
- if (genericArguments != null && methods[i].IsGenericMethod)
- {
- if (methods[i].GetGenericArguments().Length == genericArguments.Length)
- {
- MethodInfo candidateMethod = methods[i].MakeGenericMethod(genericArguments);
-
- if (_signature2 != null)
- {
- if (candidateMethod.SerializationToString().Equals(_signature2))
- {
- methodInfo = candidateMethod;
- break;
- }
- }
- else
- {
- if (candidateMethod.ToString().Equals(_signature))
- {
- methodInfo = candidateMethod;
- break;
- }
- }
- }
- }
- }
- }
-
- if (methodInfo == null)
- throw new SerializationException(SR.Format(SR.Serialization_UnknownMember, _memberName));
-
- if (!methodInfo.IsGenericMethodDefinition)
- return methodInfo;
-
- if (genericArguments == null)
- return methodInfo;
-
- if (genericArguments[0] == null)
- return null;
-
- return methodInfo.MakeGenericMethod(genericArguments);
- }
- #endregion
-
- default:
- throw new ArgumentException(SR.Serialization_MemberTypeNotRecognized);
- }
- }
- #endregion
- }
-}
-
diff --git a/src/mscorlib/shared/System/Reflection/Missing.cs b/src/mscorlib/shared/System/Reflection/Missing.cs
index fa32d43..46ab32f 100644
--- a/src/mscorlib/shared/System/Reflection/Missing.cs
+++ b/src/mscorlib/shared/System/Reflection/Missing.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
public sealed class Missing : ISerializable
{
public static readonly Missing Value = new Missing();
@@ -15,10 +14,7 @@ namespace System.Reflection
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- throw new ArgumentNullException(nameof(info));
-
- UnitySerializationHolder.GetUnitySerializationInfo(info, this);
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Reflection/Module.cs b/src/mscorlib/shared/System/Reflection/Module.cs
index 56f83c4..7822e9f 100644
--- a/src/mscorlib/shared/System/Reflection/Module.cs
+++ b/src/mscorlib/shared/System/Reflection/Module.cs
@@ -110,7 +110,10 @@ namespace System.Reflection
public Type ResolveType(int metadataToken) => ResolveType(metadataToken, null, null);
public virtual Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { throw NotImplemented.ByDesign; }
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw NotImplemented.ByDesign; }
+ public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ throw new PlatformNotSupportedException();
+ }
public override bool Equals(object o) => base.Equals(o);
public override int GetHashCode() => base.GetHashCode();
diff --git a/src/mscorlib/shared/System/Reflection/ParameterInfo.cs b/src/mscorlib/shared/System/Reflection/ParameterInfo.cs
index 94bfffa..fd130e5 100644
--- a/src/mscorlib/shared/System/Reflection/ParameterInfo.cs
+++ b/src/mscorlib/shared/System/Reflection/ParameterInfo.cs
@@ -54,46 +54,7 @@ namespace System.Reflection
public object GetRealObject(StreamingContext context)
{
- // Once all the serializable fields have come in we can set up the real
- // instance based on just two of them (MemberImpl and PositionImpl).
-
- if (MemberImpl == null)
- throw new SerializationException(SR.Serialization_InsufficientState);
-
- ParameterInfo[] args = null;
-
- switch (MemberImpl.MemberType)
- {
- case MemberTypes.Constructor:
- case MemberTypes.Method:
- if (PositionImpl == -1)
- {
- if (MemberImpl.MemberType == MemberTypes.Method)
- return ((MethodInfo)MemberImpl).ReturnParameter;
- else
- throw new SerializationException(SR.Serialization_BadParameterInfo);
- }
- else
- {
- args = ((MethodBase)MemberImpl).GetParametersNoCopy();
-
- if (args != null && PositionImpl < args.Length)
- return args[PositionImpl];
- else
- throw new SerializationException(SR.Serialization_BadParameterInfo);
- }
-
- case MemberTypes.Property:
- args = ((PropertyInfo)MemberImpl).GetIndexParameters();
-
- if (args != null && PositionImpl > -1 && PositionImpl < args.Length)
- return args[PositionImpl];
- else
- throw new SerializationException(SR.Serialization_BadParameterInfo);
-
- default:
- throw new SerializationException(SR.Serialization_NoParameterInfo);
- }
+ throw new PlatformNotSupportedException();
}
public override string ToString() => ParameterType.FormatTypeName() + " " + Name;
diff --git a/src/mscorlib/shared/System/Reflection/ParameterModifier.cs b/src/mscorlib/shared/System/Reflection/ParameterModifier.cs
index 18d6cf6..640fee2 100644
--- a/src/mscorlib/shared/System/Reflection/ParameterModifier.cs
+++ b/src/mscorlib/shared/System/Reflection/ParameterModifier.cs
@@ -4,7 +4,6 @@
namespace System.Reflection
{
- [Serializable]
public struct ParameterModifier
{
private readonly bool[] _byRef;
diff --git a/src/mscorlib/shared/System/Reflection/Pointer.cs b/src/mscorlib/shared/System/Reflection/Pointer.cs
index 13a5eff..55376c6 100644
--- a/src/mscorlib/shared/System/Reflection/Pointer.cs
+++ b/src/mscorlib/shared/System/Reflection/Pointer.cs
@@ -7,7 +7,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
[CLSCompliant(false)]
public sealed unsafe class Pointer : ISerializable
{
@@ -22,14 +21,6 @@ namespace System.Reflection
_ptrType = ptrType;
}
- private Pointer(SerializationInfo info, StreamingContext context)
- {
- _ptr = ((IntPtr)(info.GetValue("_ptr", typeof(IntPtr)))).ToPointer();
- _ptrType = (Type)info.GetValue("_ptrType", typeof(Type));
- if (!_ptrType.IsRuntimeImplemented())
- throw new SerializationException(SR.Arg_MustBeType);
- }
-
public static object Box(void* ptr, Type type)
{
if (type == null)
@@ -51,8 +42,7 @@ namespace System.Reflection
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- info.AddValue("_ptr", new IntPtr(_ptr));
- info.AddValue("_ptrType", _ptrType);
+ throw new PlatformNotSupportedException();
}
internal Type GetPointerType() => _ptrType;
diff --git a/src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs b/src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs
index 772620c..ca0c6ab 100644
--- a/src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs
+++ b/src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
public sealed class ReflectionTypeLoadException : SystemException, ISerializable
{
public ReflectionTypeLoadException(Type[] classes, Exception[] exceptions)
@@ -25,18 +24,9 @@ namespace System.Reflection
HResult = __HResults.COR_E_REFLECTIONTYPELOAD;
}
- internal ReflectionTypeLoadException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- Types = (Type[])(info.GetValue("Types", typeof(Type[])));
- LoaderExceptions = (Exception[])(info.GetValue("Exceptions", typeof(Exception[])));
- }
-
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
- info.AddValue("Types", Types, typeof(Type[]));
- info.AddValue("Exceptions", LoaderExceptions, typeof(Exception[]));
}
public Type[] Types { get; }
diff --git a/src/mscorlib/shared/System/Reflection/StrongNameKeyPair.cs b/src/mscorlib/shared/System/Reflection/StrongNameKeyPair.cs
index c04ddd6..6efa626 100644
--- a/src/mscorlib/shared/System/Reflection/StrongNameKeyPair.cs
+++ b/src/mscorlib/shared/System/Reflection/StrongNameKeyPair.cs
@@ -7,7 +7,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
public class StrongNameKeyPair : IDeserializationCallback, ISerializable
{
private bool _keyPairExported;
@@ -42,10 +41,7 @@ namespace System.Reflection
protected StrongNameKeyPair(SerializationInfo info, StreamingContext context)
{
- _keyPairExported = (bool)info.GetValue("_keyPairExported", typeof(bool));
- _keyPairArray = (byte[])info.GetValue("_keyPairArray", typeof(byte[]));
- _keyPairContainer = (string)info.GetValue("_keyPairContainer", typeof(string));
- _publicKey = (byte[])info.GetValue("_publicKey", typeof(byte[]));
+ throw new PlatformNotSupportedException();
}
public StrongNameKeyPair(string keyPairContainer)
@@ -63,12 +59,12 @@ namespace System.Reflection
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- info.AddValue("_keyPairExported", _keyPairExported);
- info.AddValue("_keyPairArray", _keyPairArray);
- info.AddValue("_keyPairContainer", _keyPairContainer);
- info.AddValue("_publicKey", _publicKey);
+ throw new PlatformNotSupportedException();
}
- void IDeserializationCallback.OnDeserialization(object sender) { }
+ void IDeserializationCallback.OnDeserialization(object sender)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/Reflection/TargetException.cs b/src/mscorlib/shared/System/Reflection/TargetException.cs
index 03f8730..6e43f56 100644
--- a/src/mscorlib/shared/System/Reflection/TargetException.cs
+++ b/src/mscorlib/shared/System/Reflection/TargetException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
public class TargetException : ApplicationException
{
public TargetException()
@@ -28,6 +27,7 @@ namespace System.Reflection
protected TargetException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Reflection/TargetInvocationException.cs b/src/mscorlib/shared/System/Reflection/TargetInvocationException.cs
index e934e5b..8d0bfef 100644
--- a/src/mscorlib/shared/System/Reflection/TargetInvocationException.cs
+++ b/src/mscorlib/shared/System/Reflection/TargetInvocationException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
public sealed class TargetInvocationException : ApplicationException
{
public TargetInvocationException(Exception inner)
@@ -20,10 +19,5 @@ namespace System.Reflection
{
HResult = __HResults.COR_E_TARGETINVOCATION;
}
-
- internal TargetInvocationException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
}
}
diff --git a/src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs b/src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs
index c360454..e200cdb 100644
--- a/src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs
+++ b/src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Reflection
{
- [Serializable]
public sealed class TargetParameterCountException : ApplicationException
{
public TargetParameterCountException()
@@ -26,10 +25,5 @@ namespace System.Reflection
{
HResult = __HResults.COR_E_TARGETPARAMCOUNT;
}
-
- internal TargetParameterCountException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
}
}
diff --git a/src/mscorlib/shared/System/Reflection/TypeDelegator.cs b/src/mscorlib/shared/System/Reflection/TypeDelegator.cs
index 7f928d24..bcbff05 100644
--- a/src/mscorlib/shared/System/Reflection/TypeDelegator.cs
+++ b/src/mscorlib/shared/System/Reflection/TypeDelegator.cs
@@ -10,7 +10,6 @@ using CultureInfo = System.Globalization.CultureInfo;
namespace System.Reflection
{
- [Serializable]
public class TypeDelegator : TypeInfo
{
public override bool IsAssignableFrom(TypeInfo typeInfo)
@@ -100,6 +99,7 @@ namespace System.Reflection
protected override TypeAttributes GetAttributeFlagsImpl() => typeImpl.Attributes;
+ public override bool IsTypeDefinition => typeImpl.IsTypeDefinition;
public override bool IsSZArray => typeImpl.IsSZArray;
protected override bool IsArrayImpl() => typeImpl.IsArray;
diff --git a/src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs b/src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs
index 70f41f4..ec81439 100644
--- a/src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs
+++ b/src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs
@@ -7,7 +7,6 @@ using System.Runtime.Serialization;
namespace System.Resources
{
- [Serializable]
public class MissingManifestResourceException : SystemException
{
public MissingManifestResourceException()
@@ -31,6 +30,7 @@ namespace System.Resources
protected MissingManifestResourceException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs b/src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs
index b343e0c..d2ddc99 100644
--- a/src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs
+++ b/src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs
@@ -20,7 +20,6 @@ using System.Runtime.Serialization;
namespace System.Resources
{
- [Serializable]
public class MissingSatelliteAssemblyException : SystemException
{
private String _cultureName;
@@ -53,6 +52,7 @@ namespace System.Resources
protected MissingSatelliteAssemblyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
public String CultureName
diff --git a/src/mscorlib/shared/System/Resources/ResourceFallbackManager.cs b/src/mscorlib/shared/System/Resources/ResourceFallbackManager.cs
new file mode 100644
index 0000000..8268f32
--- /dev/null
+++ b/src/mscorlib/shared/System/Resources/ResourceFallbackManager.cs
@@ -0,0 +1,87 @@
+// 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;
+
+ 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/shared/System/Resources/RuntimeResourceSet.cs b/src/mscorlib/shared/System/Resources/RuntimeResourceSet.cs
new file mode 100644
index 0000000..41d7541
--- /dev/null
+++ b/src/mscorlib/shared/System/Resources/RuntimeResourceSet.cs
@@ -0,0 +1,436 @@
+// 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.
+**
+**
+===========================================================*/
+
+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;
+
+namespace System.Resources
+{
+ // 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.
+ //
+#if CORECLR
+ internal
+#else
+ public // On CoreRT, this must be public because of need to whitelist past the ReflectionBlock.
+#endif
+ 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)
+ {
+ _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;
+ }
+
+ internal RuntimeResourceSet(Stream stream) : base(false)
+ {
+ _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
+ _defaultReader = new ResourceReader(stream, _resCache);
+ Reader = _defaultReader;
+ }
+
+ 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)
+ {
+ // 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)
+ {
+ 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 (_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;
+ }
+ }
+ return value;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs
index 198ed3d..66c9175 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class AsyncStateMachineAttribute : StateMachineAttribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs
index 4da9502..88e2657 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs
@@ -6,7 +6,6 @@ namespace System.Runtime.CompilerServices
{
/// IMPORTANT: Keep this in sync with corhdr.h
[Flags]
- [Serializable]
public enum CompilationRelaxations : int
{
NoStringInterning = 0x0008 // Start in 0x0008, we had other non public flags in this enum before,
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs
index 1f100bd..d6da23f 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Method)]
public class CompilationRelaxationsAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs
index 3da2a95..1c05abd 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.All, Inherited = true)]
public sealed class CompilerGeneratedAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
index 22fa694..752295e 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
@@ -6,7 +6,6 @@ namespace System.Runtime.CompilerServices
{
// Attribute used to communicate to the VS7 debugger that a class should be treated as if it has global scope.
- [Serializable]
[AttributeUsage(AttributeTargets.Class)]
public class CompilerGlobalScopeAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs
index f5419d4..4c1f489 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Assembly)]
public sealed class DefaultDependencyAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs
index 56f4242..0fe07ed 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class DependencyAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs
index baf5824..8dc6c43 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Field)]
public sealed class FixedAddressValueTypeAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs
index 65653a4..ea843b3 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public sealed class IndexerNameAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/IsByRefLikeAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/IsByRefLikeAttribute.cs
new file mode 100644
index 0000000..90e49d2
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/IsByRefLikeAttribute.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.ComponentModel;
+
+namespace System.Runtime.CompilerServices
+{
+ /// <summary>
+ /// Reserved to be used by the compiler for tracking metadata.
+ /// This attribute should not be used by developers in source code.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [AttributeUsage(AttributeTargets.Struct)]
+ public sealed class IsByRefLikeAttribute : Attribute
+ {
+ public IsByRefLikeAttribute()
+ {
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs
index 5ac3918..53afc95 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class IteratorStateMachineAttribute : StateMachineAttribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/LoadHint.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/LoadHint.cs
index ae6d9b9..3820f85 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/LoadHint.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/LoadHint.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
public enum LoadHint
{
Default = 0x0000, // No preference specified
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/MethodCodeType.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/MethodCodeType.cs
index e82993a..841b666 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/MethodCodeType.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/MethodCodeType.cs
@@ -6,7 +6,6 @@ using System.Reflection;
namespace System.Runtime.CompilerServices
{
- [Serializable]
public enum MethodCodeType
{
IL = MethodImplAttributes.IL,
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs
index 6e307e7..f3842ec 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs
@@ -15,7 +15,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class ReferenceAssemblyAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs
index 55dba0d..609c560 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs
@@ -13,7 +13,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
public sealed class RuntimeCompatibilityAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs
index 94ed5b5..e081d63 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs
@@ -6,7 +6,6 @@ using System;
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public class StateMachineAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs
index 7772a1a..25a8bfb 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs
@@ -6,7 +6,6 @@ namespace System.Runtime.CompilerServices
{
// Custom attribute to indicate that strings should be frozen.
- [Serializable]
[AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
public sealed class StringFreezingAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs
index 162676e..f049c89 100644
--- a/src/mscorlib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.CompilerServices
{
- [Serializable]
[AttributeUsage(AttributeTargets.Struct)]
sealed public class UnsafeValueTypeAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Runtime/ConstrainedExecution/Cer.cs b/src/mscorlib/shared/System/Runtime/ConstrainedExecution/Cer.cs
index c142ec9..77ab3ea 100644
--- a/src/mscorlib/shared/System/Runtime/ConstrainedExecution/Cer.cs
+++ b/src/mscorlib/shared/System/Runtime/ConstrainedExecution/Cer.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.ConstrainedExecution
{
- [Serializable]
public enum Cer : int
{
None = 0,
diff --git a/src/mscorlib/shared/System/Runtime/ConstrainedExecution/Consistency.cs b/src/mscorlib/shared/System/Runtime/ConstrainedExecution/Consistency.cs
index 7ee8480..e2cc79e 100644
--- a/src/mscorlib/shared/System/Runtime/ConstrainedExecution/Consistency.cs
+++ b/src/mscorlib/shared/System/Runtime/ConstrainedExecution/Consistency.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.ConstrainedExecution
{
- [Serializable]
public enum Consistency : int
{
MayCorruptProcess = 0,
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs b/src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs
index d7bde79..81b9a46 100644
--- a/src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs
@@ -21,7 +21,6 @@ namespace System.Runtime.InteropServices
// Base exception for COM Interop errors &; Structured Exception Handler
// exceptions.
//
- [Serializable]
public class ExternalException : SystemException
{
public ExternalException()
@@ -51,6 +50,7 @@ namespace System.Runtime.InteropServices
protected ExternalException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
public virtual int ErrorCode
diff --git a/src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs b/src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs
index a359daf..bfe3313 100644
--- a/src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs
+++ b/src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Runtime.Serialization
{
- [Serializable]
public class SerializationException : SystemException
{
private static String s_nullMessage = SR.SerializationException;
@@ -34,6 +33,7 @@ namespace System.Runtime.Serialization
protected SerializationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Runtime/Serialization/StreamingContext.cs b/src/mscorlib/shared/System/Runtime/Serialization/StreamingContext.cs
index 1026a87..4fe90ca 100644
--- a/src/mscorlib/shared/System/Runtime/Serialization/StreamingContext.cs
+++ b/src/mscorlib/shared/System/Runtime/Serialization/StreamingContext.cs
@@ -4,7 +4,6 @@
namespace System.Runtime.Serialization
{
- [Serializable]
public struct StreamingContext
{
private readonly object _additionalContext;
diff --git a/src/mscorlib/shared/System/Security/CryptographicException.cs b/src/mscorlib/shared/System/Security/CryptographicException.cs
index 89cb658..7c4fa17 100644
--- a/src/mscorlib/shared/System/Security/CryptographicException.cs
+++ b/src/mscorlib/shared/System/Security/CryptographicException.cs
@@ -7,7 +7,6 @@ using System.Runtime.Serialization;
namespace System.Security.Cryptography
{
- [Serializable]
public class CryptographicException : SystemException
{
public CryptographicException()
@@ -39,6 +38,7 @@ namespace System.Security.Cryptography
protected CryptographicException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Security/SafeBSTRHandle.cs b/src/mscorlib/shared/System/Security/SafeBSTRHandle.cs
index a1164dc..227fed3 100644
--- a/src/mscorlib/shared/System/Security/SafeBSTRHandle.cs
+++ b/src/mscorlib/shared/System/Security/SafeBSTRHandle.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime;
using System.Diagnostics;
using System.Runtime.InteropServices;
@@ -25,7 +26,7 @@ namespace System.Security
override protected bool ReleaseHandle()
{
- Interop.NtDll.ZeroMemory(handle, (UIntPtr)(Interop.OleAut32.SysStringLen(handle) * sizeof(char)));
+ RuntimeImports.RhZeroMemory(handle, (UIntPtr)(Interop.OleAut32.SysStringLen(handle) * sizeof(char)));
Interop.OleAut32.SysFreeString(handle);
return true;
}
@@ -36,7 +37,7 @@ namespace System.Security
try
{
AcquirePointer(ref bufferPtr);
- Interop.NtDll.ZeroMemory((IntPtr)bufferPtr, (UIntPtr)(Interop.OleAut32.SysStringLen((IntPtr)bufferPtr) * sizeof(char)));
+ RuntimeImports.RhZeroMemory((IntPtr)bufferPtr, (UIntPtr)(Interop.OleAut32.SysStringLen((IntPtr)bufferPtr) * sizeof(char)));
}
finally
{
diff --git a/src/mscorlib/shared/System/Security/SecureString.Unix.cs b/src/mscorlib/shared/System/Security/SecureString.Unix.cs
index 0ef38e4..cfeebc1 100644
--- a/src/mscorlib/shared/System/Security/SecureString.Unix.cs
+++ b/src/mscorlib/shared/System/Security/SecureString.Unix.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Runtime;
using System.Runtime.InteropServices;
using System.Text;
@@ -142,6 +143,41 @@ namespace System.Security
_buffer.Write((ulong)(index * sizeof(char)), c);
}
+ internal unsafe IntPtr MarshalToBSTR()
+ {
+ int length = _decryptedLength;
+ IntPtr ptr = IntPtr.Zero;
+ IntPtr result = IntPtr.Zero;
+ byte* bufferPtr = null;
+
+ try
+ {
+ _buffer.AcquirePointer(ref bufferPtr);
+ int resultByteLength = (length + 1) * sizeof(char);
+
+ ptr = PInvokeMarshal.AllocBSTR(length);
+
+ Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char));
+
+ result = ptr;
+ }
+ finally
+ {
+ // If we failed for any reason, free the new buffer
+ if (result == IntPtr.Zero && ptr != IntPtr.Zero)
+ {
+ RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
+ PInvokeMarshal.FreeBSTR(ptr);
+ }
+
+ if (bufferPtr != null)
+ {
+ _buffer.ReleasePointer();
+ }
+ }
+ return result;
+ }
+
internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode)
{
int length = _decryptedLength;
@@ -179,7 +215,7 @@ namespace System.Security
// release the string if we had one.
if (stringPtr != IntPtr.Zero && result == IntPtr.Zero)
{
- UnmanagedBuffer.ZeroMemory((byte*)stringPtr, (ulong)(length * sizeof(char)));
+ RuntimeImports.RhZeroMemory(stringPtr, (UIntPtr)(length * sizeof(char)));
MarshalFree(stringPtr, globalAlloc);
}
@@ -241,7 +277,7 @@ namespace System.Security
try
{
AcquirePointer(ref ptr);
- ZeroMemory(ptr, ByteLength);
+ RuntimeImports.RhZeroMemory((IntPtr)ptr, (UIntPtr)ByteLength);
}
finally
{
@@ -284,12 +320,6 @@ namespace System.Security
Marshal.FreeHGlobal(handle);
return true;
}
-
- internal static unsafe void ZeroMemory(byte* ptr, ulong len)
- {
- for (ulong i = 0; i < len; i++) *ptr++ = 0;
- }
}
-
}
}
diff --git a/src/mscorlib/shared/System/Security/SecureString.Windows.cs b/src/mscorlib/shared/System/Security/SecureString.Windows.cs
index 13f75a3..2a80081 100644
--- a/src/mscorlib/shared/System/Security/SecureString.Windows.cs
+++ b/src/mscorlib/shared/System/Security/SecureString.Windows.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Runtime;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32;
@@ -157,11 +158,7 @@ namespace System.Security
_buffer.AcquirePointer(ref bufferPtr);
int resultByteLength = (length + 1) * sizeof(char);
- ptr = Interop.OleAut32.SysAllocStringLen(null, length);
- if (ptr == IntPtr.Zero)
- {
- throw new OutOfMemoryException();
- }
+ ptr = PInvokeMarshal.AllocBSTR(length);
Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char));
@@ -174,8 +171,8 @@ namespace System.Security
// If we failed for any reason, free the new buffer
if (result == IntPtr.Zero && ptr != IntPtr.Zero)
{
- Interop.NtDll.ZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
- Interop.OleAut32.SysFreeString(ptr);
+ RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
+ PInvokeMarshal.FreeBSTR(ptr);
}
if (bufferPtr != null)
@@ -223,7 +220,7 @@ namespace System.Security
// If we failed for any reason, free the new buffer
if (result == IntPtr.Zero && ptr != IntPtr.Zero)
{
- Interop.NtDll.ZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
+ RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
MarshalFree(ptr, globalAlloc);
}
diff --git a/src/mscorlib/shared/System/Security/SecurityException.cs b/src/mscorlib/shared/System/Security/SecurityException.cs
index 86e3cd4..538f475 100644
--- a/src/mscorlib/shared/System/Security/SecurityException.cs
+++ b/src/mscorlib/shared/System/Security/SecurityException.cs
@@ -7,7 +7,6 @@ using System.Runtime.Serialization;
namespace System.Security
{
- [Serializable]
public class SecurityException : SystemException
{
public SecurityException()
@@ -46,6 +45,7 @@ namespace System.Security
protected SecurityException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
public override string ToString() => base.ToString();
diff --git a/src/mscorlib/shared/System/Security/VerificationException.cs b/src/mscorlib/shared/System/Security/VerificationException.cs
index 9641e1a..ea5a759 100644
--- a/src/mscorlib/shared/System/Security/VerificationException.cs
+++ b/src/mscorlib/shared/System/Security/VerificationException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Security
{
- [Serializable]
public class VerificationException : SystemException
{
public VerificationException()
@@ -30,6 +29,7 @@ namespace System.Security
protected VerificationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/StackOverflowException.cs b/src/mscorlib/shared/System/StackOverflowException.cs
index 0a875e7..fb0e882 100644
--- a/src/mscorlib/shared/System/StackOverflowException.cs
+++ b/src/mscorlib/shared/System/StackOverflowException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public sealed class StackOverflowException : SystemException
{
public StackOverflowException()
@@ -35,7 +34,5 @@ namespace System
{
HResult = __HResults.COR_E_STACKOVERFLOW;
}
-
- internal StackOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
diff --git a/src/mscorlib/shared/System/StringComparison.cs b/src/mscorlib/shared/System/StringComparison.cs
index 8b4e2ae..d5c18c8 100644
--- a/src/mscorlib/shared/System/StringComparison.cs
+++ b/src/mscorlib/shared/System/StringComparison.cs
@@ -4,7 +4,6 @@
namespace System
{
- [Serializable]
public enum StringComparison
{
CurrentCulture = 0,
diff --git a/src/mscorlib/shared/System/SystemException.cs b/src/mscorlib/shared/System/SystemException.cs
index f4779a2..d5bcde7 100644
--- a/src/mscorlib/shared/System/SystemException.cs
+++ b/src/mscorlib/shared/System/SystemException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class SystemException : Exception
{
public SystemException()
@@ -27,6 +26,9 @@ namespace System
HResult = __HResults.COR_E_SYSTEM;
}
- protected SystemException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected SystemException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/Text/ASCIIEncoding.cs b/src/mscorlib/shared/System/Text/ASCIIEncoding.cs
index e5c1194..628ec9a 100644
--- a/src/mscorlib/shared/System/Text/ASCIIEncoding.cs
+++ b/src/mscorlib/shared/System/Text/ASCIIEncoding.cs
@@ -19,11 +19,9 @@ namespace System.Text
// Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd
// use fallbacks, and we cannot guarantee that fallbacks are normalized.
- [Serializable]
public class ASCIIEncoding : Encoding
{
// Allow for devirtualization (see https://github.com/dotnet/coreclr/pull/9230)
- [Serializable]
internal sealed class ASCIIEncodingSealed : ASCIIEncoding { }
// Used by Encoding.ASCII for lazy initialization
diff --git a/src/mscorlib/shared/System/Text/Decoder.cs b/src/mscorlib/shared/System/Text/Decoder.cs
index b2a0030..aefe1f6 100644
--- a/src/mscorlib/shared/System/Text/Decoder.cs
+++ b/src/mscorlib/shared/System/Text/Decoder.cs
@@ -21,7 +21,6 @@ namespace System.Text
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
- [Serializable]
public abstract class Decoder
{
internal DecoderFallback m_fallback = null;
diff --git a/src/mscorlib/shared/System/Text/Encoder.cs b/src/mscorlib/shared/System/Text/Encoder.cs
index e4e9176..c4b54ce 100644
--- a/src/mscorlib/shared/System/Text/Encoder.cs
+++ b/src/mscorlib/shared/System/Text/Encoder.cs
@@ -21,7 +21,6 @@ namespace System.Text
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
- [Serializable]
public abstract class Encoder
{
internal EncoderFallback m_fallback = null;
diff --git a/src/mscorlib/shared/System/Text/EncodingInfo.cs b/src/mscorlib/shared/System/Text/EncodingInfo.cs
index 360dd7f..99995f7 100644
--- a/src/mscorlib/shared/System/Text/EncodingInfo.cs
+++ b/src/mscorlib/shared/System/Text/EncodingInfo.cs
@@ -7,7 +7,6 @@ using System.Text;
namespace System.Text
{
- [Serializable]
public sealed class EncodingInfo
{
private int iCodePage; // Code Page #
diff --git a/src/mscorlib/shared/System/Text/EncodingNLS.cs b/src/mscorlib/shared/System/Text/EncodingNLS.cs
index 205ae26..835bf8f 100644
--- a/src/mscorlib/shared/System/Text/EncodingNLS.cs
+++ b/src/mscorlib/shared/System/Text/EncodingNLS.cs
@@ -23,7 +23,6 @@ namespace System.Text
// So if you change the wrappers in this class, you must change the wrappers in the other classes
// as well because they should have the same behavior.
- [Serializable]
internal abstract class EncodingNLS : Encoding
{
protected EncodingNLS(int codePage) : base(codePage)
diff --git a/src/mscorlib/shared/System/Text/UTF32Encoding.cs b/src/mscorlib/shared/System/Text/UTF32Encoding.cs
index e4cd6c9..450aee2 100644
--- a/src/mscorlib/shared/System/Text/UTF32Encoding.cs
+++ b/src/mscorlib/shared/System/Text/UTF32Encoding.cs
@@ -21,7 +21,6 @@ namespace System.Text
// mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't
// switch the byte orderings.
- [Serializable]
public sealed class UTF32Encoding : Encoding
{
/*
@@ -1200,7 +1199,6 @@ namespace System.Text
CodePage + (_emitUTF32ByteOrderMark ? 4 : 0) + (_bigEndian ? 8 : 0);
}
- [Serializable]
private sealed class UTF32Decoder : DecoderNLS
{
// Need a place to store any extra bytes we may have picked up
diff --git a/src/mscorlib/shared/System/Text/UTF8Encoding.cs b/src/mscorlib/shared/System/Text/UTF8Encoding.cs
index 5cfa890..ee5c92c 100644
--- a/src/mscorlib/shared/System/Text/UTF8Encoding.cs
+++ b/src/mscorlib/shared/System/Text/UTF8Encoding.cs
@@ -34,7 +34,6 @@ namespace System.Text
// used mostly to distinguish UTF-8 text from other encodings, and doesn't
// switch the byte orderings.
- [Serializable]
public class UTF8Encoding : Encoding
{
/*
@@ -53,7 +52,6 @@ namespace System.Text
private const int UTF8_CODEPAGE = 65001;
// Allow for devirtualization (see https://github.com/dotnet/coreclr/pull/9230)
- [Serializable]
internal sealed class UTF8EncodingSealed : UTF8Encoding
{
public UTF8EncodingSealed(bool encoderShouldEmitUTF8Identifier) : base(encoderShouldEmitUTF8Identifier) { }
@@ -2521,7 +2519,6 @@ namespace System.Text
UTF8_CODEPAGE + (_emitUTF8Identifier ? 1 : 0);
}
- [Serializable]
private sealed class UTF8Encoder : EncoderNLS, ISerializable
{
// We must save a high surrogate value until the next call, looking
@@ -2533,46 +2530,10 @@ namespace System.Text
// base calls reset
}
- // Constructor called by serialization, have to handle deserializing from Everett
- internal UTF8Encoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Get common info
- this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
-
- // SurrogateChar happens to mean the same thing
- this.surrogateChar = (int)info.GetValue("surrogateChar", typeof(int));
-
- try
- {
- this.m_fallback = (EncoderFallback)info.GetValue("m_fallback", typeof(EncoderFallback));
- }
- catch (SerializationException)
- {
- this.m_fallback = null;
- }
- }
-
- // 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
- // Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding)
- info.AddValue("encoding", this.m_encoding);
- info.AddValue("surrogateChar", this.surrogateChar);
-
- info.AddValue("m_fallback", this.m_fallback);
-
- // Extra stuff for Everett that Whidbey doesn't use
- info.AddValue("storedSurrogate", this.surrogateChar > 0 ? true : false);
- info.AddValue("mustFlush", false); // Everett doesn't actually use this either, but it accidently serialized it!
+ throw new PlatformNotSupportedException();
}
public override void Reset()
@@ -2593,7 +2554,6 @@ namespace System.Text
}
}
- [Serializable]
private sealed class UTF8Decoder : DecoderNLS, ISerializable
{
// We'll need to remember the previous information. See the comments around definition
@@ -2608,44 +2568,13 @@ namespace System.Text
// Constructor called by serialization, have to handle deserializing from Everett
internal UTF8Decoder(SerializationInfo info, StreamingContext context)
{
- // Any info?
- if (info == null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Get common info
- this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
-
- try
- {
- // Get whidbey version of bits
- this.bits = (int)info.GetValue("wbits", typeof(int));
- this.m_fallback = (DecoderFallback)info.GetValue("m_fallback", typeof(DecoderFallback));
- }
- catch (SerializationException)
- {
- // Everett calls bits bits instead of wbits, so this is Everett
- this.bits = 0;
- this.m_fallback = null;
- }
+ 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();
-
- // Save new Whidbey data
- info.AddValue("encoding", this.m_encoding);
- info.AddValue("wbits", this.bits); // Special whidbey bits name
- info.AddValue("m_fallback", this.m_fallback);
-
- // Everett has extra stuff, we set it all to 0 in case this deserializes in Everett
- info.AddValue("bits", (int)0);
- info.AddValue("trailCount", (int)0);
- info.AddValue("isSurrogate", false);
- info.AddValue("byteSequence", (int)0);
+ throw new PlatformNotSupportedException();
}
public override void Reset()
diff --git a/src/mscorlib/shared/System/Text/UnicodeEncoding.cs b/src/mscorlib/shared/System/Text/UnicodeEncoding.cs
index 0e4db9a..846946c 100644
--- a/src/mscorlib/shared/System/Text/UnicodeEncoding.cs
+++ b/src/mscorlib/shared/System/Text/UnicodeEncoding.cs
@@ -14,7 +14,6 @@ using System.Diagnostics.Contracts;
namespace System.Text
{
- [Serializable]
public class UnicodeEncoding : Encoding
{
// Used by Encoding.BigEndianUnicode/Unicode for lazy initialization
@@ -1983,7 +1982,6 @@ namespace System.Text
(byteOrderMark ? 4 : 0) + (bigEndian ? 8 : 0);
}
- [Serializable]
private sealed class Decoder : System.Text.DecoderNLS, ISerializable
{
internal int lastByte = -1;
@@ -1993,47 +1991,16 @@ 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.lastByte = (int)info.GetValue("lastByte", typeof(int));
-
- try
- {
- // Try the encoding, which is only serialized in Whidbey
- this.m_encoding = (Encoding)info.GetValue("m_encoding", typeof(Encoding));
- this.lastChar = (char)info.GetValue("lastChar", typeof(char));
- this.m_fallback = (DecoderFallback)info.GetValue("m_fallback", typeof(DecoderFallback));
- }
- catch (SerializationException)
- {
- // Everett didn't serialize the UnicodeEncoding, get the default one
- bool bigEndian = (bool)info.GetValue("bigEndian", typeof(bool));
- this.m_encoding = new UnicodeEncoding(bigEndian, false);
- }
+ 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();
-
- // Save Whidbey data
- info.AddValue("m_encoding", this.m_encoding);
- info.AddValue("m_fallback", this.m_fallback);
- info.AddValue("lastChar", this.lastChar); // Unused by everett so it'll probably get lost
- info.AddValue("lastByte", this.lastByte);
-
- // Everett Only
- info.AddValue("bigEndian", ((UnicodeEncoding)(this.m_encoding)).bigEndian);
+ throw new PlatformNotSupportedException();
}
public override void Reset()
diff --git a/src/mscorlib/shared/System/ThreadStaticAttribute.cs b/src/mscorlib/shared/System/ThreadStaticAttribute.cs
index 3755e65..c12ac1c 100644
--- a/src/mscorlib/shared/System/ThreadStaticAttribute.cs
+++ b/src/mscorlib/shared/System/ThreadStaticAttribute.cs
@@ -17,7 +17,6 @@ using System;
namespace System
{
- [Serializable]
[AttributeUsage(AttributeTargets.Field, Inherited = false)]
public class ThreadStaticAttribute : Attribute
{
diff --git a/src/mscorlib/shared/System/Threading/AbandonedMutexException.cs b/src/mscorlib/shared/System/Threading/AbandonedMutexException.cs
index 8056a3b..15bc5a7 100644
--- a/src/mscorlib/shared/System/Threading/AbandonedMutexException.cs
+++ b/src/mscorlib/shared/System/Threading/AbandonedMutexException.cs
@@ -14,7 +14,6 @@ using System.Runtime.Serialization;
namespace System.Threading
{
- [Serializable]
public class AbandonedMutexException : SystemException
{
private int _mutexIndex = -1;
@@ -62,6 +61,7 @@ namespace System.Threading
protected AbandonedMutexException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
private void SetupException(int location, WaitHandle handle)
diff --git a/src/mscorlib/shared/System/Threading/ExecutionContext.cs b/src/mscorlib/shared/System/Threading/ExecutionContext.cs
index 67857e9..a573af3 100644
--- a/src/mscorlib/shared/System/Threading/ExecutionContext.cs
+++ b/src/mscorlib/shared/System/Threading/ExecutionContext.cs
@@ -44,7 +44,6 @@ namespace System.Threading
}
}
- [Serializable]
public sealed class ExecutionContext : IDisposable, ISerializable
{
internal static readonly ExecutionContext Default = new ExecutionContext();
@@ -71,15 +70,7 @@ namespace System.Threading
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- }
-
- private ExecutionContext(SerializationInfo info, StreamingContext context)
- {
+ throw new PlatformNotSupportedException();
}
public static ExecutionContext Capture()
diff --git a/src/mscorlib/shared/System/Threading/LockRecursionException.cs b/src/mscorlib/shared/System/Threading/LockRecursionException.cs
index 2f296cb..86e1903 100644
--- a/src/mscorlib/shared/System/Threading/LockRecursionException.cs
+++ b/src/mscorlib/shared/System/Threading/LockRecursionException.cs
@@ -7,7 +7,6 @@ using System.Runtime.Serialization;
namespace System.Threading
{
- [Serializable]
public class LockRecursionException : System.Exception
{
public LockRecursionException()
@@ -24,6 +23,9 @@ namespace System.Threading
{
}
- protected LockRecursionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected LockRecursionException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/Threading/SemaphoreFullException.cs b/src/mscorlib/shared/System/Threading/SemaphoreFullException.cs
index 19ac19d..777463b 100644
--- a/src/mscorlib/shared/System/Threading/SemaphoreFullException.cs
+++ b/src/mscorlib/shared/System/Threading/SemaphoreFullException.cs
@@ -7,7 +7,6 @@ using System.Runtime.Serialization;
namespace System.Threading
{
- [Serializable]
public class SemaphoreFullException : SystemException
{
public SemaphoreFullException() : base(SR.Threading_SemaphoreFullException)
@@ -24,6 +23,7 @@ namespace System.Threading
protected SemaphoreFullException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Threading/SynchronizationLockException.cs b/src/mscorlib/shared/System/Threading/SynchronizationLockException.cs
index 120577f..c64fc9c 100644
--- a/src/mscorlib/shared/System/Threading/SynchronizationLockException.cs
+++ b/src/mscorlib/shared/System/Threading/SynchronizationLockException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System.Threading
{
- [Serializable]
public class SynchronizationLockException : SystemException
{
public SynchronizationLockException()
@@ -39,6 +38,7 @@ namespace System.Threading
protected SynchronizationLockException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Threading/Tasks/TaskCanceledException.cs b/src/mscorlib/shared/System/Threading/Tasks/TaskCanceledException.cs
index d7690d4..6657bcd 100644
--- a/src/mscorlib/shared/System/Threading/Tasks/TaskCanceledException.cs
+++ b/src/mscorlib/shared/System/Threading/Tasks/TaskCanceledException.cs
@@ -19,7 +19,6 @@ namespace System.Threading.Tasks
/// <summary>
/// Represents an exception used to communicate task cancellation.
/// </summary>
- [Serializable]
public class TaskCanceledException : OperationCanceledException
{
[NonSerialized]
@@ -71,6 +70,7 @@ namespace System.Threading.Tasks
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination. </param>
protected TaskCanceledException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
/// <summary>
diff --git a/src/mscorlib/shared/System/Threading/Tasks/TaskSchedulerException.cs b/src/mscorlib/shared/System/Threading/Tasks/TaskSchedulerException.cs
index 148b630..2888415 100644
--- a/src/mscorlib/shared/System/Threading/Tasks/TaskSchedulerException.cs
+++ b/src/mscorlib/shared/System/Threading/Tasks/TaskSchedulerException.cs
@@ -20,7 +20,6 @@ namespace System.Threading.Tasks
/// Represents an exception used to communicate an invalid operation by a
/// <see cref="T:System.Threading.Tasks.TaskScheduler"/>.
/// </summary>
- [Serializable]
public class TaskSchedulerException : Exception
{
/// <summary>
@@ -72,6 +71,7 @@ namespace System.Threading.Tasks
protected TaskSchedulerException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Threading/ThreadAbortException.cs b/src/mscorlib/shared/System/Threading/ThreadAbortException.cs
index e693e71..5773f27 100644
--- a/src/mscorlib/shared/System/Threading/ThreadAbortException.cs
+++ b/src/mscorlib/shared/System/Threading/ThreadAbortException.cs
@@ -18,7 +18,6 @@ using System.Runtime.Serialization;
namespace System.Threading
{
- [Serializable]
public sealed class ThreadAbortException : SystemException
{
private ThreadAbortException()
@@ -26,11 +25,6 @@ namespace System.Threading
HResult = __HResults.COR_E_THREADABORTED;
}
- internal ThreadAbortException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
-
public object ExceptionState => null;
}
}
diff --git a/src/mscorlib/shared/System/Threading/ThreadStartException.cs b/src/mscorlib/shared/System/Threading/ThreadStartException.cs
index 2ff77bc..7a87943 100644
--- a/src/mscorlib/shared/System/Threading/ThreadStartException.cs
+++ b/src/mscorlib/shared/System/Threading/ThreadStartException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Threading
{
- [Serializable]
public sealed class ThreadStartException : SystemException
{
internal ThreadStartException()
@@ -20,10 +19,5 @@ namespace System.Threading
{
HResult = __HResults.COR_E_THREADSTART;
}
-
- internal ThreadStartException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
}
}
diff --git a/src/mscorlib/shared/System/Threading/ThreadStateException.cs b/src/mscorlib/shared/System/Threading/ThreadStateException.cs
index 33bc8ba..9477cb1 100644
--- a/src/mscorlib/shared/System/Threading/ThreadStateException.cs
+++ b/src/mscorlib/shared/System/Threading/ThreadStateException.cs
@@ -16,7 +16,6 @@ using System.Runtime.Serialization;
namespace System.Threading
{
- [Serializable]
public class ThreadStateException : SystemException
{
public ThreadStateException()
@@ -40,6 +39,7 @@ namespace System.Threading
protected ThreadStateException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs b/src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs
index e44946a..770e70d 100644
--- a/src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs
+++ b/src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System.Threading
{
- [Serializable]
public class WaitHandleCannotBeOpenedException : ApplicationException
{
public WaitHandleCannotBeOpenedException() : base(SR.Threading_WaitHandleCannotBeOpenedException)
@@ -26,6 +25,7 @@ namespace System.Threading
protected WaitHandleCannotBeOpenedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/TimeZone.cs b/src/mscorlib/shared/System/TimeZone.cs
index 88e2e21..d4059ba 100644
--- a/src/mscorlib/shared/System/TimeZone.cs
+++ b/src/mscorlib/shared/System/TimeZone.cs
@@ -26,7 +26,6 @@ using System.Globalization;
namespace System
{
- [Serializable]
[Obsolete("System.TimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo instead.")]
public abstract class TimeZone
{
diff --git a/src/mscorlib/shared/System/TimeZoneNotFoundException.cs b/src/mscorlib/shared/System/TimeZoneNotFoundException.cs
index ee21c25..5b7ce10 100644
--- a/src/mscorlib/shared/System/TimeZoneNotFoundException.cs
+++ b/src/mscorlib/shared/System/TimeZoneNotFoundException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class TimeZoneNotFoundException : Exception
{
public TimeZoneNotFoundException()
@@ -23,6 +22,9 @@ namespace System
{
}
- protected TimeZoneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected TimeZoneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/TimeoutException.cs b/src/mscorlib/shared/System/TimeoutException.cs
index 32775a1..4ba95bc 100644
--- a/src/mscorlib/shared/System/TimeoutException.cs
+++ b/src/mscorlib/shared/System/TimeoutException.cs
@@ -15,7 +15,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class TimeoutException : SystemException
{
public TimeoutException()
@@ -36,6 +35,9 @@ namespace System
HResult = __HResults.COR_E_TIMEOUT;
}
- protected TimeoutException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected TimeoutException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/Type.cs b/src/mscorlib/shared/System/Type.cs
index 7749c17..2ba5891 100644
--- a/src/mscorlib/shared/System/Type.cs
+++ b/src/mscorlib/shared/System/Type.cs
@@ -32,6 +32,7 @@ namespace System
public override Type ReflectedType => null;
public abstract Type UnderlyingSystemType { get; }
+ public virtual bool IsTypeDefinition { get { throw NotImplemented.ByDesign; } }
public bool IsArray => IsArrayImpl();
protected abstract bool IsArrayImpl();
public bool IsByRef => IsByRefImpl();
diff --git a/src/mscorlib/shared/System/TypeAccessException.cs b/src/mscorlib/shared/System/TypeAccessException.cs
index 32afbdf..302dcb1 100644
--- a/src/mscorlib/shared/System/TypeAccessException.cs
+++ b/src/mscorlib/shared/System/TypeAccessException.cs
@@ -8,7 +8,6 @@ namespace System
{
// TypeAccessException derives from TypeLoadException rather than MemberAccessException because in
// pre-v4 releases of the runtime TypeLoadException was used in lieu of a TypeAccessException.
- [Serializable]
public class TypeAccessException : TypeLoadException
{
public TypeAccessException()
@@ -29,6 +28,9 @@ namespace System
HResult = __HResults.COR_E_TYPEACCESS;
}
- protected TypeAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected TypeAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/TypeCode.cs b/src/mscorlib/shared/System/TypeCode.cs
index 293eb1f..2961986 100644
--- a/src/mscorlib/shared/System/TypeCode.cs
+++ b/src/mscorlib/shared/System/TypeCode.cs
@@ -23,7 +23,6 @@
namespace System
{
- [Serializable]
public enum TypeCode
{
Empty = 0, // Null reference
diff --git a/src/mscorlib/shared/System/TypeInitializationException.cs b/src/mscorlib/shared/System/TypeInitializationException.cs
index 9191028..8d0b8a9 100644
--- a/src/mscorlib/shared/System/TypeInitializationException.cs
+++ b/src/mscorlib/shared/System/TypeInitializationException.cs
@@ -19,7 +19,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public sealed class TypeInitializationException : SystemException
{
private String _typeName;
@@ -52,16 +51,9 @@ namespace System
HResult = __HResults.COR_E_TYPEINITIALIZATION;
}
- internal TypeInitializationException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- _typeName = info.GetString("TypeName");
- }
-
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
- info.AddValue("TypeName", TypeName, typeof(String));
}
public String TypeName
diff --git a/src/mscorlib/shared/System/TypeUnloadedException.cs b/src/mscorlib/shared/System/TypeUnloadedException.cs
index 33e4687..c7ed71c 100644
--- a/src/mscorlib/shared/System/TypeUnloadedException.cs
+++ b/src/mscorlib/shared/System/TypeUnloadedException.cs
@@ -6,7 +6,6 @@ using System.Runtime.Serialization;
namespace System
{
- [Serializable]
public class TypeUnloadedException : SystemException
{
public TypeUnloadedException()
@@ -26,13 +25,11 @@ namespace System
{
HResult = __HResults.COR_E_TYPEUNLOADED;
}
-
- //
- // This constructor is required for serialization;
- //
+
protected TypeUnloadedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
+ throw new PlatformNotSupportedException();
}
}
}
diff --git a/src/mscorlib/shared/System/UnauthorizedAccessException.cs b/src/mscorlib/shared/System/UnauthorizedAccessException.cs
index 9973588..667d576 100644
--- a/src/mscorlib/shared/System/UnauthorizedAccessException.cs
+++ b/src/mscorlib/shared/System/UnauthorizedAccessException.cs
@@ -19,7 +19,6 @@ namespace System
{
// The UnauthorizedAccessException is thrown when access errors
// occur from IO or other OS methods.
- [Serializable]
public class UnauthorizedAccessException : SystemException
{
public UnauthorizedAccessException()
@@ -40,6 +39,9 @@ namespace System
HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
}
- protected UnauthorizedAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ protected UnauthorizedAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
diff --git a/src/mscorlib/shared/System/UnhandledExceptionEventArgs.cs b/src/mscorlib/shared/System/UnhandledExceptionEventArgs.cs
index d338301..5cde572 100644
--- a/src/mscorlib/shared/System/UnhandledExceptionEventArgs.cs
+++ b/src/mscorlib/shared/System/UnhandledExceptionEventArgs.cs
@@ -4,7 +4,6 @@
namespace System
{
- [Serializable]
public class UnhandledExceptionEventArgs : EventArgs
{
private Object _exception;
diff --git a/src/mscorlib/shared/System/UnhandledExceptionEventHandler.cs b/src/mscorlib/shared/System/UnhandledExceptionEventHandler.cs
index b99414c..14e31c7 100644
--- a/src/mscorlib/shared/System/UnhandledExceptionEventHandler.cs
+++ b/src/mscorlib/shared/System/UnhandledExceptionEventHandler.cs
@@ -4,6 +4,5 @@
namespace System
{
- [Serializable]
public delegate void UnhandledExceptionEventHandler(Object sender, UnhandledExceptionEventArgs e);
}
diff --git a/src/mscorlib/shared/System/UnitySerializationHolder.cs b/src/mscorlib/shared/System/UnitySerializationHolder.cs
deleted file mode 100644
index f195798..0000000
--- a/src/mscorlib/shared/System/UnitySerializationHolder.cs
+++ /dev/null
@@ -1,329 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-
-using System.Runtime.Serialization;
-using System.Reflection;
-using System.Globalization;
-using System.Runtime.Versioning;
-using System.Collections.Generic;
-using System.Diagnostics.Contracts;
-
-namespace System
-{
- [Serializable]
- // Holds classes (Empty, Null, Missing) for which we guarantee that there is only ever one instance of.
-#if CORECLR
- internal
-#else
- public // On CoreRT, this must be public because of the Reflection.Core/CoreLib divide and the need to whitelist past the ReflectionBlock.
-#endif
- class UnitySerializationHolder : ISerializable, IObjectReference
- {
-#region Internal Constants
- internal const int EmptyUnity = 0x0001;
- internal const int NullUnity = 0x0002;
- internal const int MissingUnity = 0x0003;
- internal const int RuntimeTypeUnity = 0x0004;
- public const int ModuleUnity = 0x0005;
- public const int AssemblyUnity = 0x0006;
- internal const int GenericParameterTypeUnity = 0x0007;
- internal const int PartialInstantiationTypeUnity = 0x0008;
-
- internal const int Pointer = 0x0001;
- internal const int Array = 0x0002;
- internal const int SzArray = 0x0003;
- internal const int ByRef = 0x0004;
-#endregion
-
-#region Internal Static Members
- internal static void GetUnitySerializationInfo(SerializationInfo info, Missing missing)
- {
- info.SetType(typeof(UnitySerializationHolder));
- info.AddValue("UnityType", MissingUnity);
- }
-
- internal static Type AddElementTypes(SerializationInfo info, Type type)
- {
- List<int> elementTypes = new List<int>();
- while (type.HasElementType)
- {
- if (type.IsSZArray)
- {
- elementTypes.Add(SzArray);
- }
- else if (type.IsArray)
- {
- elementTypes.Add(type.GetArrayRank());
- elementTypes.Add(Array);
- }
- else if (type.IsPointer)
- {
- elementTypes.Add(Pointer);
- }
- else if (type.IsByRef)
- {
- elementTypes.Add(ByRef);
- }
-
- type = type.GetElementType();
- }
-
- info.AddValue("ElementTypes", elementTypes.ToArray(), typeof(int[]));
-
- return type;
- }
-
- internal Type MakeElementTypes(Type type)
- {
- for (int i = _elementTypes.Length - 1; i >= 0; i--)
- {
- if (_elementTypes[i] == SzArray)
- {
- type = type.MakeArrayType();
- }
- else if (_elementTypes[i] == Array)
- {
- type = type.MakeArrayType(_elementTypes[--i]);
- }
- else if ((_elementTypes[i] == Pointer))
- {
- type = type.MakePointerType();
- }
- else if ((_elementTypes[i] == ByRef))
- {
- type = type.MakeByRefType();
- }
- }
-
- return type;
- }
-
- public static void GetUnitySerializationInfo(SerializationInfo info, Type type)
- {
- Type rootElementType = type;
- while (rootElementType.HasElementType)
- {
- rootElementType = rootElementType.GetElementType();
- }
-
- if (rootElementType.IsGenericParameter)
- {
- type = AddElementTypes(info, type);
- info.SetType(typeof(UnitySerializationHolder));
- info.AddValue("UnityType", GenericParameterTypeUnity);
- info.AddValue("GenericParameterPosition", type.GenericParameterPosition);
- info.AddValue("DeclaringMethod", type.DeclaringMethod, typeof(MethodBase));
- info.AddValue("DeclaringType", type.DeclaringType, typeof(Type));
-
- return;
- }
-
- int unityType = RuntimeTypeUnity;
-
- if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters)
- {
- // Partial instantiation
- unityType = PartialInstantiationTypeUnity;
- type = AddElementTypes(info, type);
- info.AddValue("GenericArguments", type.GetGenericArguments(), typeof(Type[]));
- type = type.GetGenericTypeDefinition();
- }
-
- GetUnitySerializationInfo(info, unityType, type.FullName, type.Assembly);
- }
-
- public static void GetUnitySerializationInfo(
- SerializationInfo info, int unityType, string data, Assembly assembly)
- {
- // A helper method that returns the SerializationInfo that a class utilizing
- // UnitySerializationHelper should return from a call to GetObjectData. It contains
- // the unityType (defined above) and any optional data (used only for the reflection
- // types.)
-
- info.SetType(typeof(UnitySerializationHolder));
- info.AddValue("Data", data, typeof(string));
- info.AddValue("UnityType", unityType);
-
- string assemName;
-
- if (assembly == null)
- {
- assemName = string.Empty;
- }
- else
- {
- assemName = assembly.FullName;
- }
-
- info.AddValue("AssemblyName", assemName);
- }
-#endregion
-
-#region Private Data Members
- private readonly Type[] _instantiation;
- private readonly int[] _elementTypes;
- private readonly int _genericParameterPosition;
- private readonly Type _declaringType;
- private readonly MethodBase _declaringMethod;
- private readonly string _data;
- private readonly string _assemblyName;
- private int _unityType;
-#endregion
-
-#region Constructor
- public UnitySerializationHolder(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- _unityType = info.GetInt32("UnityType");
-
- if (_unityType == MissingUnity)
- return;
-
- if (_unityType == GenericParameterTypeUnity)
- {
- _declaringMethod = info.GetValue("DeclaringMethod", typeof(MethodBase)) as MethodBase;
- _declaringType = info.GetValue("DeclaringType", typeof(Type)) as Type;
- _genericParameterPosition = info.GetInt32("GenericParameterPosition");
- _elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
-
- return;
- }
-
- if (_unityType == PartialInstantiationTypeUnity)
- {
- _instantiation = info.GetValue("GenericArguments", typeof(Type[])) as Type[];
- _elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
- }
-
- _data = info.GetString("Data");
- _assemblyName = info.GetString("AssemblyName");
- }
-#endregion
-
-#region Private Methods
- private void ThrowInsufficientInformation(string field)
- {
- throw new SerializationException(
- SR.Format(SR.Serialization_InsufficientDeserializationState, field));
- }
-#endregion
-
-#region ISerializable
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- throw new NotSupportedException(SR.NotSupported_UnitySerHolder);
- }
-#endregion
-
-#region IObjectReference
- public virtual object GetRealObject(StreamingContext context)
- {
- // GetRealObject uses the data we have in _data and _unityType to do a lookup on the correct
- // object to return. We have specific code here to handle the different types which we support.
- // The reflection types (Assembly, Module, and Type) have to be looked up through their static
- // accessors by name.
-
- Assembly assembly;
-
- switch (_unityType)
- {
- case EmptyUnity:
- {
- return Empty.Value;
- }
-
- case NullUnity:
- {
- return DBNull.Value;
- }
-
- case MissingUnity:
- {
- return Missing.Value;
- }
-
- case PartialInstantiationTypeUnity:
- {
- _unityType = RuntimeTypeUnity;
- Type definition = GetRealObject(context) as Type;
- _unityType = PartialInstantiationTypeUnity;
-
- if (_instantiation[0] == null)
- return null;
-
- return MakeElementTypes(definition.MakeGenericType(_instantiation));
- }
-
- case GenericParameterTypeUnity:
- {
- if (_declaringMethod == null && _declaringType == null)
- ThrowInsufficientInformation("DeclaringMember");
-
- if (_declaringMethod != null)
- return _declaringMethod.GetGenericArguments()[_genericParameterPosition];
-
- return MakeElementTypes(_declaringType.GetGenericArguments()[_genericParameterPosition]);
- }
-
- case RuntimeTypeUnity:
- {
- if (_data == null || _data.Length == 0)
- ThrowInsufficientInformation("Data");
-
- if (_assemblyName == null)
- ThrowInsufficientInformation("AssemblyName");
-
- if (_assemblyName.Length == 0)
- return Type.GetType(_data, true, false);
-
- assembly = Assembly.Load(_assemblyName);
-
- Type t = assembly.GetType(_data, true, false);
-
- return t;
- }
-
- case ModuleUnity:
- {
- if (_data == null || _data.Length == 0)
- ThrowInsufficientInformation("Data");
-
- if (_assemblyName == null)
- ThrowInsufficientInformation("AssemblyName");
-
- assembly = Assembly.Load(_assemblyName);
-
- Module namedModule = assembly.GetModule(_data);
-
- if (namedModule == null)
- throw new SerializationException(
- SR.Format(SR.Serialization_UnableToFindModule, _data, _assemblyName));
-
- return namedModule;
- }
-
- case AssemblyUnity:
- {
- if (_data == null || _data.Length == 0)
- ThrowInsufficientInformation("Data");
-
- if (_assemblyName == null)
- ThrowInsufficientInformation("AssemblyName");
-
- assembly = Assembly.Load(_assemblyName);
-
- return assembly;
- }
-
- default:
- throw new ArgumentException(SR.Argument_InvalidUnity);
- }
- }
-#endregion
- }
-}
diff --git a/src/mscorlib/shared/System/Void.cs b/src/mscorlib/shared/System/Void.cs
index 5c20f63..5162e6a 100644
--- a/src/mscorlib/shared/System/Void.cs
+++ b/src/mscorlib/shared/System/Void.cs
@@ -10,7 +10,6 @@
namespace System
{
// This class represents the void return type
- [Serializable]
public struct Void
{
}