diff options
author | Jiyoung Yun <jy910.yun@samsung.com> | 2017-06-13 18:47:36 +0900 |
---|---|---|
committer | Jiyoung Yun <jy910.yun@samsung.com> | 2017-06-13 18:47:36 +0900 |
commit | 61d6a817e39d3bae0f47dbc09838d51db22a5d30 (patch) | |
tree | cb37caa1784bc738b976273335d6ed04a7cc80b0 /src/mscorlib | |
parent | 5b975f8233e8c8d17b215372f89ca713b45d6a0b (diff) | |
download | coreclr-61d6a817e39d3bae0f47dbc09838d51db22a5d30.tar.gz coreclr-61d6a817e39d3bae0f47dbc09838d51db22a5d30.tar.bz2 coreclr-61d6a817e39d3bae0f47dbc09838d51db22a5d30.zip |
Imported Upstream version 2.0.0.11992upstream/2.0.0.11992
Diffstat (limited to 'src/mscorlib')
412 files changed, 2190 insertions, 4865 deletions
diff --git a/src/mscorlib/Resources/Strings.resx b/src/mscorlib/Resources/Strings.resx index 791d1ca04d..cbf969e8fe 100644 --- a/src/mscorlib/Resources/Strings.resx +++ b/src/mscorlib/Resources/Strings.resx @@ -1628,9 +1628,6 @@ <data name="ArgumentOutOfRange_ArrayLBAndLength" xml:space="preserve"> <value>Higher indices will exceed Int32.MaxValue because of large lower bound and/or length.</value> </data> - <data name="ArgumentOutOfRange_ArrayListInsert" xml:space="preserve"> - <value>Insertion index was out of range. Must be non-negative and less than or equal to size.</value> - </data> <data name="ArgumentOutOfRange_BadHourMinuteSecond" xml:space="preserve"> <value>Hour, Minute, and Second parameters describe an un-representable DateTime.</value> </data> @@ -3185,6 +3182,9 @@ <data name="PlatformNotSupported_WinRT" xml:space="preserve"> <value>Windows Runtime is not supported on this operating system.</value> </data> + <data name="PlatformNotSupported_OverlappedIO" xml:space="preserve"> + <value>This API is specific to the way in which Windows handles asynchronous I/O, and is not supported on this platform.</value> + </data> <data name="Policy_CannotLoadSemiTrustAssembliesDuringInit" xml:space="preserve"> <value>All assemblies loaded as part of AppDomain initialization must be fully trusted.</value> </data> @@ -3287,6 +3287,9 @@ <data name="Serialization_DateTimeTicksOutOfRange" xml:space="preserve"> <value>Invalid serialized DateTime data. Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.</value> </data> + <data name="Serialization_DelegatesNotSupported" xml:space="preserve"> + <value>Serializing delegates is not supported on this platform.</value> + </data> <data name="Serialization_InsufficientDeserializationState" xml:space="preserve"> <value>Insufficient state to deserialize the object. Missing field '{0}'. More information is needed.</value> </data> diff --git a/src/mscorlib/System.Private.CoreLib.csproj b/src/mscorlib/System.Private.CoreLib.csproj index df86533182..513e002497 100644 --- a/src/mscorlib/System.Private.CoreLib.csproj +++ b/src/mscorlib/System.Private.CoreLib.csproj @@ -20,6 +20,7 @@ <!-- This prevents the default MsBuild targets from referencing System.Core.dll --> <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences> <!-- These prevent the default MsBuild targets from referencing System.dll and mscorlib.dll --> + <ExcludeMscorlibFacade>true</ExcludeMscorlibFacade> <NoStdLib>true</NoStdLib> <NoCompilerStandardLib>true</NoCompilerStandardLib> <SubsystemVersion>6.00</SubsystemVersion> @@ -86,11 +87,9 @@ <PropertyGroup Condition="'$(OsEnvironment)' == 'Unix'"> <DebugType>portable</DebugType> </PropertyGroup> - <PropertyGroup Condition="'$(TargetsOSX)' == 'true'"> <DefineConstants>PLATFORM_OSX;$(DefineConstants)</DefineConstants> </PropertyGroup> - <!-- Assembly attributes --> <PropertyGroup> <AssemblyName>System.Private.CoreLib</AssemblyName> @@ -104,6 +103,7 @@ <AssemblyInfoLines Include="[assembly: System.Security.AllowPartiallyTrustedCallers]" /> <AssemblyInfoLines Include="[assembly: System.Runtime.InteropServices.ComVisible(false)]" /> <AssemblyInfoLines Include="[assembly: System.Resources.NeutralResourcesLanguage("en-US")]" /> + <AssemblyInfoLines Include="[assembly: System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)]" /> </ItemGroup> <!-- Helper Paths @@ -152,7 +152,6 @@ <Compile Include="$(BclSourcesRoot)\System\Runtime\GcSettings.cs" /> </ItemGroup> <ItemGroup> - <Compile Include="$(BclSourcesRoot)\System\Collections\ArrayList.cs" /> <Compile Include="$(BclSourcesRoot)\System\Collections\Comparer.cs" /> <Compile Include="$(BclSourcesRoot)\System\Collections\CompatibleComparer.cs" /> <Compile Include="$(BclSourcesRoot)\System\Collections\ListDictionaryInternal.cs" /> @@ -173,6 +172,7 @@ <Compile Include="$(BclSourcesRoot)\System\Runtime\InteropServices\Marshal.cs" /> <Compile Include="$(BclSourcesRoot)\System\Runtime\InteropServices\MarshalDirectiveException.cs" /> <Compile Include="$(BclSourcesRoot)\System\Runtime\InteropServices\PInvokeMap.cs" /> + <Compile Include="$(BclSourcesRoot)\System\Runtime\InteropServices\PInvokeMarshal.cs" /> <Compile Include="$(BclSourcesRoot)\System\Runtime\InteropServices\RuntimeEnvironment.cs" /> <Compile Include="$(BclSourcesRoot)\System\Runtime\InteropServices\SEHException.cs" /> <Compile Include="$(BclSourcesRoot)\System\Runtime\InteropServices\SafeBuffer.cs" /> @@ -314,10 +314,9 @@ <Compile Include="$(BclSourcesRoot)\System\IAppDomainPauseManager.cs" /> <Compile Include="$(BclSourcesRoot)\System\AppDomainAttributes.cs" /> <Compile Include="$(BclSourcesRoot)\System\AppDomainUnloadedException.cs" /> - <Compile Include="$(BclSourcesRoot)\System\ArgumentOutOfRangeException.cs" /> <Compile Include="$(BclSourcesRoot)\System\ArgIterator.cs" /> <Compile Include="$(BclSourcesRoot)\System\Attribute.cs" /> - <Compile Include="$(BclSourcesRoot)\System\BadImageFormatException.cs" /> + <Compile Include="$(BclSourcesRoot)\System\BadImageFormatException.CoreCLR.cs" /> <Compile Include="$(BclSourcesRoot)\System\BitConverter.cs" /> <Compile Include="$(BclSourcesRoot)\System\Boolean.cs" /> <Compile Include="$(BclSourcesRoot)\System\Buffer.cs" /> @@ -326,11 +325,9 @@ <Compile Include="$(BclSourcesRoot)\System\Currency.cs" /> <Compile Include="$(BclSourcesRoot)\System\Decimal.cs" /> <Compile Include="$(BclSourcesRoot)\System\DefaultBinder.CanConvert.cs" /> - <Compile Include="$(BclSourcesRoot)\System\DelegateSerializationHolder.cs" /> <Compile Include="$(BclSourcesRoot)\System\Double.cs" /> <Compile Include="$(BclSourcesRoot)\System\Empty.cs" /> <Compile Include="$(BclSourcesRoot)\System\Enum.cs" /> - <Compile Include="$(BclSourcesRoot)\System\DllNotFoundException.cs" /> <Compile Include="$(BclSourcesRoot)\System\Environment.cs" /> <Compile Include="$(BclSourcesRoot)\System\GC.cs" /> <Compile Include="$(BclSourcesRoot)\System\Guid.cs" /> @@ -347,10 +344,7 @@ <Compile Include="$(BclSourcesRoot)\System\MissingMemberException.cs" /> <Compile Include="$(BclSourcesRoot)\System\NonSerializedAttribute.cs" /> <Compile Include="$(BclSourcesRoot)\System\Number.cs" /> - <Compile Include="$(BclSourcesRoot)\System\OperatingSystem.cs" /> - <Compile Include="$(BclSourcesRoot)\System\OperationCanceledException.cs" /> <Compile Include="$(BclSourcesRoot)\System\ParseNumbers.cs" /> - <Compile Include="$(BclSourcesRoot)\System\PlatformID.cs" /> <Compile Include="$(BclSourcesRoot)\System\ResId.cs" /> <Compile Include="$(BclSourcesRoot)\System\RtType.cs" /> <Compile Include="$(BclSourcesRoot)\System\RuntimeArgumentHandle.cs" /> @@ -403,7 +397,6 @@ <Compile Include="$(BclSourcesRoot)\System\Reflection\MdFieldInfo.cs" /> <Compile Include="$(BclSourcesRoot)\System\Reflection\MdImport.cs" /> <Compile Include="$(BclSourcesRoot)\System\Reflection\MemberInfo.Internal.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Reflection\MemberSerializationStringGenerator.cs" /> <Compile Include="$(BclSourcesRoot)\System\Reflection\MethodBase.CoreCLR.cs" /> <Compile Include="$(BclSourcesRoot)\System\Reflection\MethodBody.cs" /> <Compile Include="$(BclSourcesRoot)\System\Reflection\RtFieldInfo.cs" /> @@ -478,10 +471,7 @@ <Compile Include="$(BclSourcesRoot)\System\Globalization\GregorianCalendar.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\GregorianCalendarHelper.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\IdnMapping.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\NumberFormatInfo.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\RegionInfo.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\SortKey.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\StringInfo.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\TextElementEnumerator.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\TextInfo.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\TimeSpanFormat.cs" /> @@ -499,6 +489,7 @@ <Compile Include="$(BclSourcesRoot)\System\Threading\Monitor.cs" /> <Compile Include="$(BclSourcesRoot)\System\Threading\Mutex.cs" /> <Compile Include="$(BclSourcesRoot)\System\Threading\Overlapped.cs" /> + <Compile Include="$(BclSourcesRoot)\System\Threading\PinnableBufferCache.cs" /> <Compile Include="$(BclSourcesRoot)\System\Threading\Semaphore.cs" /> <Compile Include="$(BclSourcesRoot)\System\Threading\Thread.cs" /> <Compile Include="$(BclSourcesRoot)\System\Threading\ThreadInterruptedException.cs" /> @@ -546,17 +537,13 @@ <Compile Include="$(BclSourcesRoot)\System\IO\Directory.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\SearchOption.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\DriveNotFoundException.cs" /> - <Compile Include="$(BclSourcesRoot)\System\IO\EncodingCache.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\File.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\FileLoadException.CoreCLR.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\FileNotFoundException.CoreCLR.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\IOException.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\MemoryStream.cs" /> - <Compile Include="$(BclSourcesRoot)\System\IO\PinnedBufferMemoryStream.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\Stream.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\UnmanagedMemoryAccessor.cs" /> - <Compile Include="$(BclSourcesRoot)\System\IO\UnmanagedMemoryStream.cs" /> - <Compile Include="$(BclSourcesRoot)\System\IO\UnmanagedMemoryStreamWrapper.cs" /> </ItemGroup> <ItemGroup> <Compile Include="$(BclSourcesRoot)\System\Security\DynamicSecurityMethodAttribute.cs" /> @@ -577,6 +564,8 @@ <Compile Include="$(BclSourcesRoot)\System\Diagnostics\Eventing\EventSource_CoreCLR.cs" /> <Compile Condition="'$(FeatureXplatEventSource)' == 'true'" Include="$(BclSourcesRoot)\System\Diagnostics\Eventing\XplatEventLogger.cs" /> <Compile Include="$(BclSourcesRoot)\System\Diagnostics\Eventing\FrameworkEventSource.cs" /> + <Compile Condition="'$(FeaturePerfTracing)' == 'true'" Include="$(BclSourcesRoot)\System\Diagnostics\Eventing\EventPipe.cs" /> + <Compile Condition="'$(FeaturePerfTracing)' == 'true'" Include="$(BclSourcesRoot)\System\Diagnostics\Eventing\EventPipeEventProvider.cs" /> </ItemGroup> <ItemGroup> <Compile Include="$(BclSourcesRoot)\System\Diagnostics\Contracts\Contracts.cs" /> @@ -602,9 +591,6 @@ <Compile Include="$(BclSourcesRoot)\System\Runtime\Serialization\SerializationInfo.cs" /> </ItemGroup> <ItemGroup> - <Compile Include="$(BclSourcesRoot)\System\Runtime\Remoting\ObjectHandle.cs" /> - </ItemGroup> - <ItemGroup> <Compile Include="$(BclSourcesRoot)\System\Text\DecoderNLS.cs" /> <Compile Include="$(BclSourcesRoot)\System\Text\DecoderBestFitFallback.cs" /> <Compile Include="$(BclSourcesRoot)\System\Text\DecoderExceptionFallback.cs" /> @@ -635,11 +621,9 @@ <Compile Include="$(BclSourcesRoot)\System\Resources\IResourceGroveler.cs" /> <Compile Include="$(BclSourcesRoot)\System\Resources\LooselyLinkedResourceReference.cs" /> <Compile Include="$(BclSourcesRoot)\System\Resources\ManifestBasedResourceGroveler.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Resources\ResourceFallbackManager.cs" /> <Compile Include="$(BclSourcesRoot)\System\Resources\ResourceManager.cs" /> <Compile Include="$(BclSourcesRoot)\System\Resources\ResourceReader.cs" /> <Compile Include="$(BclSourcesRoot)\System\Resources\ResourceSet.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Resources\RuntimeResourceSet.cs" /> </ItemGroup> <ItemGroup> <Compile Include="$(BclSourcesRoot)\System\Nullable.cs" /> @@ -662,36 +646,28 @@ <Compile Include="$(BclSourcesRoot)\Microsoft\Win32\SafeHandles\SafeFindHandle.cs" /> <Compile Include="$(BclSourcesRoot)\Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs" /> <Compile Include="$(BclSourcesRoot)\Microsoft\Win32\SafeHandles\SafeWaitHandle.cs" /> - <Compile Include="$(BclSourcesRoot)\Microsoft\Win32\SafeHandles\Win32SafeHandles.cs" /> <Compile Condition="'$(FeatureWin32Registry)' == 'true'" Include="$(BclSourcesRoot)\Microsoft\Win32\SafeHandles\SafeRegistryHandle.cs" /> </ItemGroup> <ItemGroup> <Compile Include="$(BclSourcesRoot)\System\Numerics\Hashing\HashHelpers.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetsUnix)' == 'true'"> - <Compile Include="$(BclSourcesRoot)\Interop\Unix\System.Globalization.Native\Interop.Collation.cs" /> <Compile Include="$(BclSourcesRoot)\Interop\Unix\System.Globalization.Native\Interop.ICU.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Diagnostics\Debug.Unix.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\CalendarData.Unix.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\CompareInfo.Unix.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\CultureData.Unix.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\CultureInfo.Unix.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\EncodingTable.Unix.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\EncodingDataItem.Unix.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\GlobalizationMode.Unix.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\HijriCalendar.Unix.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\IdnMapping.Unix.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\JapaneseCalendar.Unix.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\TextInfo.Unix.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\FileSystemEnumerable.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\TextReader.cs" /> <Compile Include="$(BclSourcesRoot)\System\IO\StreamReader.cs" /> <Compile Include="$(BclSourcesRoot)\System\Runtime\Versioning\CompatibilitySwitch.cs" /> <Compile Include="$(BclSourcesRoot)\System\Text\Normalization.Unix.cs" /> + <Compile Include="$(BclSourcesRoot)\System\Threading\ClrThreadPoolBoundHandle.Unix.cs" /> <Compile Include="$(BclSourcesRoot)\System\TimeZoneInfo.Unix.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetsWindows)' == 'true'"> - <Compile Include="$(BclSourcesRoot)\Interop\Windows\kernel32\Interop.Globalization.cs" /> <Compile Include="$(BclSourcesRoot)\Interop\Windows\Normaliz\Interop.Idna.cs" /> <Compile Include="$(BclSourcesRoot)\Interop\Windows\Normaliz\Interop.Normalization.cs" /> <Compile Include="$(BclSourcesRoot)\System\Diagnostics\Debug.Windows.cs" /> @@ -700,11 +676,10 @@ <Compile Include="$(BclSourcesRoot)\System\Globalization\CultureData.Windows.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\CultureInfo.Windows.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\GlobalizationMode.Windows.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\HijriCalendar.Win32.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\IdnMapping.Windows.cs" /> - <Compile Include="$(BclSourcesRoot)\System\Globalization\JapaneseCalendar.Win32.cs" /> <Compile Include="$(BclSourcesRoot)\System\Globalization\TextInfo.Windows.cs" /> <Compile Include="$(BclSourcesRoot)\System\Text\Normalization.Windows.cs" /> + <Compile Include="$(BclSourcesRoot)\System\Threading\ClrThreadPoolBoundHandle.Windows.cs" /> <Compile Include="$(BclSourcesRoot)\System\TimeZoneInfo.Win32.cs" /> </ItemGroup> <!-- Include additional sources shared files in the compilation --> @@ -713,7 +688,6 @@ <Compile Include="$(CommonPath)\Preprocessed\AssemblyRefs.g.cs" /> <!-- These files are shared with other framework components and don't live the same folder as the rest of them--> <Compile Include="$(CommonPath)\NotImplemented.cs" /> - <Compile Include="$(CommonPath)\PinnableBufferCache.cs" /> <Compile Include="$(CommonPath)\System\SR.cs" /> <!-- Include Internals visible to file in the compilation --> <Compile Include="$(BclSourcesRoot)\mscorlib.Friends.cs" /> @@ -753,9 +727,11 @@ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" /> <PropertyGroup> <!-- Overwrite the key that we are going to use for signing --> - <AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)Tools\Signing\mscorlib.snk</AssemblyOriginatorKeyFile> + <AssemblyOriginatorKeyFile>$(ToolsDir)SilverlightPlatformPublicKey.snk</AssemblyOriginatorKeyFile> + <!-- Don't need a strong name signature because we only ship the native image --> + <StrongNameSig>None</StrongNameSig> <!-- Use a different nativeresource file to avoid conflicts with mscorlib--> <Win32Resource Condition="'$(GenerateNativeVersionInfo)'=='true'">$(IntermediateOutputPath)\System.Private.CoreLib.res</Win32Resource> </PropertyGroup> <Import Project="GenerateCompilerResponseFile.targets" /> -</Project> +</Project>
\ No newline at end of file diff --git a/src/mscorlib/Tools/Signing/mscorlib.snk b/src/mscorlib/Tools/Signing/mscorlib.snk Binary files differdeleted file mode 100644 index 60146e8891..0000000000 --- a/src/mscorlib/Tools/Signing/mscorlib.snk +++ /dev/null diff --git a/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs index fe14560a3a..79aedd74d3 100644 --- a/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.cs +++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security; @@ -61,8 +60,6 @@ internal static partial class Interop protected override bool ReleaseHandle() { - Debug.Assert(!GlobalizationMode.Invariant); - CloseSortHandle(handle); SetHandle(IntPtr.Zero); return true; diff --git a/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs b/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs index 58bb12d637..bf07a6815b 100644 --- a/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs +++ b/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs @@ -9,7 +9,6 @@ internal static partial class Interop internal const string BCrypt = "BCrypt.dll"; internal const string Crypt32 = "crypt32.dll"; internal const string Kernel32 = "kernel32.dll"; - internal const string NtDll = "ntdll.dll"; internal const string OleAut32 = "oleaut32.dll"; } } diff --git a/src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs index 2bb349d670..7d3287fe1a 100644 --- a/src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.cs +++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs @@ -89,20 +89,20 @@ internal static partial class Interop internal static extern bool GetUserPreferredUILanguages(uint dwFlags, out uint pulNumLanguages, char [] pwszLanguagesBuffer, ref uint pcchLanguagesBuffer); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, IntPtr lpLCData, int cchData); + internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, void* lpLCData, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved); + internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, void* lParam, IntPtr reserved); - internal delegate BOOL EnumLocalesProcEx(IntPtr lpLocaleString, uint dwFlags, IntPtr lParam); + internal delegate BOOL EnumLocalesProcEx(char* lpLocaleString, uint dwFlags, void* lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int ResolveLocaleName(string lpNameToResolve, char* lpLocaleName, int cchLocaleName); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam); + internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, void* lParam); - internal delegate BOOL EnumTimeFormatsProcEx(IntPtr lpTimeFormatString, IntPtr lParam); + internal delegate BOOL EnumTimeFormatsProcEx(char* lpTimeFormatString, void* lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue); @@ -111,12 +111,12 @@ internal static partial class Interop internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam); + internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, void* lParam); - internal delegate BOOL EnumCalendarInfoProcExEx(IntPtr lpCalendarInfoString, uint Calendar, IntPtr lpReserved, IntPtr lParam); + internal delegate BOOL EnumCalendarInfoProcExEx(char* lpCalendarInfoString, uint Calendar, IntPtr lpReserved, void* lParam); [StructLayout(LayoutKind.Sequential)] - internal struct NlsVersionInfoEx + internal struct NlsVersionInfoEx { internal int dwNLSVersionInfoSize; internal int dwNLSVersion; diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetErrorMode.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs index 276f49c519..123eb75d7b 100644 --- a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetErrorMode.cs +++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs @@ -8,8 +8,8 @@ internal partial class Interop { internal partial class Kernel32 { - [DllImport(Libraries.Kernel32, SetLastError = false, EntryPoint = "SetErrorMode", ExactSpelling = true)] - internal static extern uint SetErrorMode(uint newMode); + [DllImport(Libraries.Kernel32, SetLastError = true, ExactSpelling = true)] + internal static extern bool SetThreadErrorMode(uint dwNewMode, out uint lpOldMode); internal const uint SEM_FAILCRITICALERRORS = 1; } diff --git a/src/mscorlib/shared/Interop/Windows/NtDll/Interop.ZeroMemory.cs b/src/mscorlib/shared/Interop/Windows/NtDll/Interop.ZeroMemory.cs deleted file mode 100644 index 9bf7321f2a..0000000000 --- a/src/mscorlib/shared/Interop/Windows/NtDll/Interop.ZeroMemory.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Security; - -internal partial class Interop -{ - internal partial class NtDll - { - [DllImport(Libraries.NtDll, CharSet = CharSet.Unicode, EntryPoint = "RtlZeroMemory")] - internal static extern void ZeroMemory(IntPtr address, UIntPtr length); - } -} diff --git a/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs index d13b536204..f28f44fdad 100644 --- a/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs +++ b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs @@ -4,6 +4,7 @@ using System; using System.Diagnostics; +using System.IO; using System.Runtime.InteropServices; namespace Microsoft.Win32.SafeHandles @@ -38,18 +39,30 @@ namespace Microsoft.Win32.SafeHandles internal static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode) { Debug.Assert(path != null); + SafeFileHandle handle = Interop.Sys.Open(path, flags, mode); - // If we fail to open the file due to a path not existing, we need to know whether to blame - // the file itself or its directory. If we're creating the file, then we blame the directory, - // otherwise we blame the file. - bool enoentDueToDirectory = (flags & Interop.Sys.OpenFlags.O_CREAT) != 0; - - // Open the file. - SafeFileHandle handle = Interop.CheckIo( - Interop.Sys.Open(path, flags, mode), - path, - isDirectory: enoentDueToDirectory, - errorRewriter: e => (e.Error == Interop.Error.EISDIR) ? Interop.Error.EACCES.Info() : e); + if (handle.IsInvalid) + { + handle.Dispose(); + Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); + + // If we fail to open the file due to a path not existing, we need to know whether to blame + // the file itself or its directory. If we're creating the file, then we blame the directory, + // otherwise we blame the file. + // + // When opening, we need to align with Windows, which considers a missing path to be + // FileNotFound only if the containing directory exists. + + bool isDirectory = (error.Error == Interop.Error.ENOENT) && + ((flags & Interop.Sys.OpenFlags.O_CREAT) != 0 + || !DirectoryExists(Path.GetDirectoryName(PathInternal.TrimEndingDirectorySeparator(path)))); + + Interop.CheckIo( + error.Error, + path, + isDirectory, + errorRewriter: e => (e.Error == Interop.Error.EISDIR) ? Interop.Error.EACCES.Info() : e); + } // Make sure it's not a directory; we do this after opening it once we have a file descriptor // to avoid race conditions. @@ -68,6 +81,31 @@ namespace Microsoft.Win32.SafeHandles return handle; } + private static bool DirectoryExists(string fullPath) + { + int fileType = Interop.Sys.FileTypes.S_IFDIR; + + Interop.Sys.FileStatus fileinfo; + Interop.ErrorInfo errorInfo = default(Interop.ErrorInfo); + + // First use stat, as we want to follow symlinks. If that fails, it could be because the symlink + // is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate + // based on the symlink itself. + if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 && + Interop.Sys.LStat(fullPath, out fileinfo) < 0) + { + errorInfo = Interop.Sys.GetLastErrorInfo(); + return false; + } + + // Something exists at this path. If the caller is asking for a directory, return true if it's + // a directory and false for everything else. If the caller is asking for a file, return false for + // a directory and true for everything else. + return + (fileType == Interop.Sys.FileTypes.S_IFDIR) == + ((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR); + } + /// <summary>Opens a SafeFileHandle for a file descriptor created by a provided delegate.</summary> /// <param name="fdFunc"> /// The function that creates the file descriptor. Returns the file descriptor on success, or an invalid diff --git a/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs new file mode 100644 index 0000000000..5415f2c35d --- /dev/null +++ b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.InteropServices; + +namespace Microsoft.Win32.SafeHandles +{ + // Class of safe handle which uses only -1 as an invalid handle. + public abstract class SafeHandleMinusOneIsInvalid : SafeHandle + { + protected SafeHandleMinusOneIsInvalid(bool ownsHandle) : base(new IntPtr(-1), ownsHandle) + { + } + + public override bool IsInvalid => handle == new IntPtr(-1); + } +} diff --git a/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs new file mode 100644 index 0000000000..8d0220bf90 --- /dev/null +++ b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.InteropServices; + +namespace Microsoft.Win32.SafeHandles +{ + // Class of safe handle which uses 0 or -1 as an invalid handle. + public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle + { + protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle) + { + } + + public override bool IsInvalid => handle == IntPtr.Zero || handle == new IntPtr(-1); + } +} diff --git a/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems b/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems index 3443a2b339..e409be0364 100644 --- a/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems +++ b/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems @@ -1,4 +1,4 @@ -<?xml version="1.0" encoding="utf-8"?> +<?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> @@ -16,10 +16,13 @@ <ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\CriticalHandleMinusOneIsInvalid.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\CriticalHandleZeroOrMinusOneIsInvalid.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeHandleMinusOneIsInvalid.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Action.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ApplicationException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ArgumentException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ArgumentNullException.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\ArgumentOutOfRangeException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ArithmeticException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ArrayTypeMismatchException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\AssemblyLoadEventArgs.cs" /> @@ -27,6 +30,7 @@ <Compile Include="$(MSBuildThisFileDirectory)System\AsyncCallback.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\AttributeTargets.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\AttributeUsageAttribute.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\BadImageFormatException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\ArrayPool.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\ConfigurableArrayPool.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\TlsOverPerCoreLockedStacksArrayPool.cs"/> @@ -74,6 +78,7 @@ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\ConditionalAttribute.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Debug.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\DivideByZeroException.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\DllNotFoundException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\DuplicateWaitObjectException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\EntryPointNotFoundException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\EventArgs.cs"/> @@ -107,9 +112,12 @@ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JulianCalendar.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\KoreanCalendar.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\KoreanLunisolarCalendar.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\NumberFormatInfo.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\NumberStyles.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\PersianCalendar.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\SortKey.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\SortVersion.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\StringInfo.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TaiwanCalendar.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TaiwanLunisolarCalendar.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\ThaiBuddhistCalendar.cs"/> @@ -132,6 +140,7 @@ <Compile Include="$(MSBuildThisFileDirectory)System\InvalidProgramException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\InvalidTimeZoneException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\DirectoryNotFoundException.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\IO\EncodingCache.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\EndOfStreamException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\Error.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileAccess.cs"/> @@ -144,8 +153,11 @@ <Compile Include="$(MSBuildThisFileDirectory)System\IO\Path.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\PathInternal.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\PathTooLongException.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\IO\PinnedBufferMemoryStream.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\SeekOrigin.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\StreamHelpers.CopyValidation.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\IO\UnmanagedMemoryStream.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\IO\UnmanagedMemoryStreamWrapper.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IObservable.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IObserver.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\IProgress.cs"/> @@ -162,6 +174,7 @@ <Compile Include="$(MSBuildThisFileDirectory)System\NullReferenceException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ObjectDisposedException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ObsoleteAttribute.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\OperationCanceledException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\OverflowException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ParamArrayAttribute.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ParamsArray.cs"/> @@ -188,6 +201,7 @@ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyKeyNameAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyMetadataAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyNameFlags.cs" /> + <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyNameFormatter.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyProductAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblySignatureKeyAttribute.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyTitleAttribute.cs" /> @@ -215,7 +229,6 @@ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ManifestResourceInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MemberFilter.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MemberInfo.cs" /> - <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MemberInfoSerializationHolder.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MemberTypes.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MethodAttributes.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MethodBase.cs" /> @@ -252,7 +265,9 @@ <Compile Include="$(MSBuildThisFileDirectory)System\Resources\MissingManifestResourceException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Resources\MissingSatelliteAssemblyException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Resources\NeutralResourcesLanguageAttribute.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Resources\ResourceFallbackManager.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Resources\ResourceTypeCode.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Resources\RuntimeResourceSet.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Resources\SatelliteContractVersionAttribute.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Resources\UltimateResourceFallbackLocation.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\AccessedThroughPropertyAttribute.cs"/> @@ -274,9 +289,10 @@ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\FormattableStringFactory.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IAsyncStateMachine.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IndexerNameAttribute.cs"/> - <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\InternalsVisibleToAttribute.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\INotifyCompletion.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\InternalsVisibleToAttribute.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IsConst.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IsByRefLikeAttribute.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IsVolatile.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IteratorStateMachineAttribute.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\ITuple.cs"/> @@ -354,9 +370,9 @@ <Compile Include="$(MSBuildThisFileDirectory)System\Text\EncodingProvider.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Text\Normalization.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Text\StringBuilder.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Text\UnicodeEncoding.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Text\UTF32Encoding.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Text\UTF8Encoding.cs"/> - <Compile Include="$(MSBuildThisFileDirectory)System\Text\UnicodeEncoding.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ThreadAttributes.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Threading\AbandonedMutexException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ApartmentState.cs"/> @@ -399,7 +415,6 @@ <Compile Include="$(MSBuildThisFileDirectory)System\UnauthorizedAccessException.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\UnhandledExceptionEventArgs.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\UnhandledExceptionEventHandler.cs"/> - <Compile Include="$(MSBuildThisFileDirectory)System\UnitySerializationHolder.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\ValueTuple.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Version.cs"/> <Compile Include="$(MSBuildThisFileDirectory)System\Void.cs"/> @@ -411,6 +426,7 @@ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\EventProvider.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\EventSource.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\EventSourceException.cs" /> + <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\IEventProvider.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\StubEnvironment.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\Winmeta.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\ArrayTypeInfo.cs" /> @@ -465,6 +481,7 @@ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetLongPathNameW.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetTempFileNameW.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetTempPathW.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.Globalization.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.LockFile.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.OutputDebugString.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_IntPtr.cs"/> @@ -472,16 +489,19 @@ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SecurityOptions.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SetEndOfFile.cs"/> - <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SetErrorMode.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SetThreadErrorMode.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SetFilePointerEx.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.WideCharToMultiByte.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_IntPtr.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_NativeOverlapped.cs"/> - <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\NtDll\Interop.ZeroMemory.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\OleAut32\Interop.SysAllocStringLen.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\OleAut32\Interop.SysFreeString.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\OleAut32\Interop.SysStringLen.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeFileHandle.Windows.cs" /> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\HijriCalendar.Win32.cs" Condition="'$(IsProjectNLibrary)' != 'true' and '$(EnableDummyGlobalizationImplementation)' != 'true'"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\HijriCalendar.WinRT.cs" Condition="'$(IsProjectNLibrary)' == 'true'"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JapaneseCalendar.Win32.cs" Condition="'$(IsProjectNLibrary)' != 'true' and '$(EnableDummyGlobalizationImplementation)' != 'true'"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JapaneseCalendar.WinRT.cs" Condition="'$(IsProjectNLibrary)' == 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Win32.cs" Condition="'$(IsProjectNLibrary)' != 'true'" /> <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Windows.cs" /> <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.WinRT.cs" Condition="'$(IsProjectNLibrary)' == 'true'" /> @@ -500,6 +520,7 @@ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\Interop.Libraries.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Calendar.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Casing.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> + <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Collation.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Idna.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Locale.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Normalization.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> @@ -526,7 +547,13 @@ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.Unlink.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.Write.cs"/> <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeFileHandle.Unix.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Debug.Unix.cs"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\CalendarData.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\CultureData.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\HijriCalendar.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\IdnMapping.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\LocaleData.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> + <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JapaneseCalendar.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.OSX.cs" Condition="'$(TargetsOSX)' == 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Linux.cs" Condition="'$(TargetsOSX)' != 'true'"/> <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Unix.cs"/> diff --git a/src/mscorlib/shared/System/ApplicationException.cs b/src/mscorlib/shared/System/ApplicationException.cs index 900feb57f9..cb98902de1 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 96afbe10d9..de2d775c84 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 3a86223ccf..74b39fed8e 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/src/System/ArgumentOutOfRangeException.cs b/src/mscorlib/shared/System/ArgumentOutOfRangeException.cs index 90837810d1..4721a503b6 100644 --- a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs +++ b/src/mscorlib/shared/System/ArgumentOutOfRangeException.cs @@ -11,43 +11,27 @@ ** =============================================================================*/ - -using System; -using System.Runtime.Remoting; -using System.Runtime.Serialization; using System.Globalization; -using System.Diagnostics.Contracts; +using System.Runtime.Serialization; namespace System { // The ArgumentOutOfRangeException is thrown when an argument // is outside the legal range for that argument. - [Serializable] - public class ArgumentOutOfRangeException : ArgumentException, ISerializable + public class ArgumentOutOfRangeException : ArgumentException { - private static volatile String _rangeMessage; - private Object m_actualValue; - - private static String RangeMessage - { - get - { - if (_rangeMessage == null) - _rangeMessage = SR.Arg_ArgumentOutOfRangeException; - return _rangeMessage; - } - } + 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(RangeMessage) + : base(SR.Arg_ArgumentOutOfRangeException) { HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE; } public ArgumentOutOfRangeException(String paramName) - : base(RangeMessage, paramName) + : base(SR.Arg_ArgumentOutOfRangeException, paramName) { HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE; } @@ -70,18 +54,29 @@ namespace System public ArgumentOutOfRangeException(String paramName, Object actualValue, String message) : base(message, paramName) { - m_actualValue = actualValue; + _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 (m_actualValue != null) + if (_actualValue != null) { - String valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, m_actualValue.ToString()); + String valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, _actualValue.ToString()); if (s == null) return valueMessage; return s + Environment.NewLine + valueMessage; @@ -96,23 +91,7 @@ namespace System // want to avoid sticking printf's in their code. public virtual Object ActualValue { - get { return m_actualValue; } - } - - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); - base.GetObjectData(info, context); - info.AddValue("ActualValue", m_actualValue, typeof(Object)); - } - - protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) - { - m_actualValue = info.GetValue("ActualValue", typeof(Object)); + get { return _actualValue; } } } } diff --git a/src/mscorlib/shared/System/ArithmeticException.cs b/src/mscorlib/shared/System/ArithmeticException.cs index 081ba454f5..2c8abe51fa 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 3e941fdf8e..d06a450603 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 5c49535cff..036d44a4b9 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 fdfa4ab730..c33d19e85e 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 6f9aeb20f3..219dc43e15 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/src/System/BadImageFormatException.cs b/src/mscorlib/shared/System/BadImageFormatException.cs index 42005cccce..6bed5e9b78 100644 --- a/src/mscorlib/src/System/BadImageFormatException.cs +++ b/src/mscorlib/shared/System/BadImageFormatException.cs @@ -11,16 +11,13 @@ ** ===========================================================*/ +using System.Globalization; +using System.IO; +using System.Runtime.Serialization; + namespace System { - using System; - using System.Runtime.Serialization; - using FileLoadException = System.IO.FileLoadException; - using SecurityException = System.Security.SecurityException; - using System.Globalization; - - [Serializable] - public class BadImageFormatException : SystemException + public partial class BadImageFormatException : SystemException { private String _fileName; // The name of the corrupt PE file. private String _fusionLog; // fusion log (when applicable) @@ -56,6 +53,17 @@ namespace System _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 @@ -70,7 +78,7 @@ namespace System if (_message == null) { if ((_fileName == null) && - (HResult == System.__HResults.COR_E_EXCEPTION)) + (HResult == __HResults.COR_E_EXCEPTION)) _message = SR.Arg_BadImageFormatException; else @@ -85,7 +93,7 @@ namespace System public override String ToString() { - String s = GetType().FullName + ": " + Message; + String s = GetType().ToString() + ": " + Message; if (_fileName != null && _fileName.Length != 0) s += Environment.NewLine + SR.Format(SR.IO_FileName_Name, _fileName); @@ -95,68 +103,22 @@ namespace System if (StackTrace != null) s += Environment.NewLine + StackTrace; - try - { - if (FusionLog != null) - { - if (s == null) - s = " "; - s += Environment.NewLine; - s += Environment.NewLine; - s += FusionLog; - } - } - catch (SecurityException) - { - } - return s; - } - - protected BadImageFormatException(SerializationInfo info, StreamingContext context) : base(info, context) - { - // Base class constructor will check info != null. - _fileName = info.GetString("BadImageFormat_FileName"); - try + if (_fusionLog != null) { - _fusionLog = info.GetString("BadImageFormat_FusionLog"); + if (s == null) + s = " "; + s += Environment.NewLine; + s += Environment.NewLine; + s += _fusionLog; } - catch - { - _fusionLog = null; - } - } - private BadImageFormatException(String fileName, String fusionLog, int hResult) - : base(null) - { - HResult = hResult; - _fileName = fileName; - _fusionLog = fusionLog; - SetMessageField(); + return s; } public String FusionLog { -#pragma warning disable CS0618 // Type or member is obsolete -#pragma warning restore CS0618 // Type or member is obsolete get { return _fusionLog; } } - - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - // Serialize data for our base classes. base will verify info != null. - base.GetObjectData(info, context); - - // Serialize data for this class - info.AddValue("BadImageFormat_FileName", _fileName, typeof(String)); - try - { - info.AddValue("BadImageFormat_FusionLog", FusionLog, typeof(String)); - } - catch (SecurityException) - { - } - } } } diff --git a/src/mscorlib/shared/System/CLSCompliantAttribute.cs b/src/mscorlib/shared/System/CLSCompliantAttribute.cs index e03600d132..d895b5ac71 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 2b3133a669..3fad7a4827 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 4dbd5cd587..ea9915a7c4 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 1fca7732ae..cdd6faf030 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 2d848397a9..3f17d6f371 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 486eb72f2a..4f4d64bf66 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 b1991a048e..ff5b29f1cf 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 6b5e690df0..33c9bd925f 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 5d84257158..f67d10e181 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 3b46d5f4d3..9adf702a02 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 d5bca6e208..416625b779 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/src/System/Diagnostics/Debug.Unix.cs b/src/mscorlib/shared/System/Diagnostics/Debug.Unix.cs index 495f2f713c..495f2f713c 100644 --- a/src/mscorlib/src/System/Diagnostics/Debug.Unix.cs +++ b/src/mscorlib/shared/System/Diagnostics/Debug.Unix.cs diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs index e18574c1b4..5292551314 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 cf4901de6f..3349c069c6 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 88b8da93cd..73e32aaf53 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 0000000000..71a2fe4d44 --- /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 4abd43adaf..0fad2f8d56 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/src/System/DllNotFoundException.cs b/src/mscorlib/shared/System/DllNotFoundException.cs index a3b46c76b3..8c69e45eda 100644 --- a/src/mscorlib/src/System/DllNotFoundException.cs +++ b/src/mscorlib/shared/System/DllNotFoundException.cs @@ -4,6 +4,7 @@ /*============================================================================= ** +** Class: DllNotFoundException ** ** ** Purpose: The exception class for some failed P/Invoke calls. @@ -11,13 +12,10 @@ ** =============================================================================*/ - -using System; using System.Runtime.Serialization; namespace System { - [Serializable] public class DllNotFoundException : TypeLoadException { public DllNotFoundException() @@ -40,6 +38,7 @@ namespace System 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 da29e2ad76..7eadead8c7 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 835d33413d..0b881cec05 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 c0356613de..be12af25b6 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 e6923cf637..3d1cbfef26 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 bebfd493a0..b89f6d9a8d 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 ac62c0fcac..b56d749771 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 5f8c108ae4..4f3ab36bfd 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 c5758e11cd..9baaac2353 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/src/System/Globalization/CalendarData.Unix.cs b/src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs index 319f66ae8c..a2ceeb1e67 100644 --- a/src/mscorlib/src/System/Globalization/CalendarData.Unix.cs +++ b/src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs @@ -306,21 +306,30 @@ namespace System.Globalization private static void EnumCalendarInfoCallback(string calendarString, IntPtr context) { - CallbackContext callbackContext = (CallbackContext)((GCHandle)context).Target; - - if (callbackContext.DisallowDuplicates) + try { - foreach (string existingResult in callbackContext.Results) + CallbackContext callbackContext = (CallbackContext)((GCHandle)context).Target; + + if (callbackContext.DisallowDuplicates) { - if (string.Equals(calendarString, existingResult, StringComparison.Ordinal)) + foreach (string existingResult in callbackContext.Results) { - // the value is already in the results, so don't add it again - return; + 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); + 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 diff --git a/src/mscorlib/shared/System/Globalization/CalendarWeekRule.cs b/src/mscorlib/shared/System/Globalization/CalendarWeekRule.cs index b381b5c544..f683ed05e7 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 404add0936..e09011a9d8 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/src/System/Globalization/CultureData.Unix.cs b/src/mscorlib/shared/System/Globalization/CultureData.Unix.cs index 4f685de580..4f685de580 100644 --- a/src/mscorlib/src/System/Globalization/CultureData.Unix.cs +++ b/src/mscorlib/shared/System/Globalization/CultureData.Unix.cs diff --git a/src/mscorlib/shared/System/Globalization/CultureNotFoundException.cs b/src/mscorlib/shared/System/Globalization/CultureNotFoundException.cs index 929f4bb000..dde1a8b2ba 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 d3f1ea9a45..5d3239ebfc 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 b3c70e1d10..10f074dc24 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 d06b13cd7d..0697b602db 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 1b61e5256e..46f13b00e0 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 b4f54f8fbb..6ba4f082f1 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/src/System/Globalization/HijriCalendar.Unix.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.Unix.cs index a6e8f73d3e..a6e8f73d3e 100644 --- a/src/mscorlib/src/System/Globalization/HijriCalendar.Unix.cs +++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.Unix.cs diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs index 869b809bff..869b809bff 100644 --- a/src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs +++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.WinRT.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.WinRT.cs index fb91c27ef6..fb91c27ef6 100644 --- a/src/mscorlib/src/System/Globalization/HijriCalendar.WinRT.cs +++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.WinRT.cs diff --git a/src/mscorlib/shared/System/Globalization/HijriCalendar.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.cs index cafde5fbb8..125248a685 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/src/System/Globalization/IdnMapping.Unix.cs b/src/mscorlib/shared/System/Globalization/IdnMapping.Unix.cs index f1ad6f1d0a..2bbda0d3a7 100644 --- a/src/mscorlib/src/System/Globalization/IdnMapping.Unix.cs +++ b/src/mscorlib/shared/System/Globalization/IdnMapping.Unix.cs @@ -39,7 +39,7 @@ namespace System.Globalization } char[] outputHeap = new char[actualLength]; - fixed (char* pOutputHeap = outputHeap) + fixed (char* pOutputHeap = &outputHeap[0]) { actualLength = Interop.GlobalizationInterop.ToAscii(flags, unicode, count, pOutputHeap, actualLength); if (actualLength == 0 || actualLength > outputHeap.Length) @@ -66,7 +66,7 @@ namespace System.Globalization else { char[] output = new char[count]; - fixed (char* pOutput = output) + fixed (char* pOutput = &output[0]) { return GetUnicodeCore(ascii, count, flags, pOutput, count, reattempt: true); } diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Unix.cs index 51ff8095a3..51ff8095a3 100644 --- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs +++ b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Unix.cs diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs index a83c4fad9e..a83c4fad9e 100644 --- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs +++ b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.WinRT.cs index 6a9df97200..6a9df97200 100644 --- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.cs +++ b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.WinRT.cs diff --git a/src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs index 4655e08a4e..0db1e6517a 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 95e87f85d7..a90c4e8f21 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 f4678c1a85..8d94290547 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 b962b1c427..ef7495f07d 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 d4c71632aa..8364532c9e 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/src/System/Globalization/NumberFormatInfo.cs b/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs index c44c085a69..9fea694cca 100644 --- a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs +++ b/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs @@ -41,7 +41,6 @@ namespace System.Globalization // CurrencySymbol "$" String used as local monetary symbol. // - [Serializable] sealed public class NumberFormatInfo : IFormatProvider, ICloneable { // invariantInfo is constant irrespective of your current culture. @@ -84,7 +83,7 @@ namespace System.Globalization internal int percentDecimalDigits = 2; [OptionalField(VersionAdded = 2)] - internal int digitSubstitution = (int) DigitShapes.None; + internal int digitSubstitution = (int)DigitShapes.None; internal bool isReadOnly = false; @@ -131,7 +130,7 @@ namespace System.Globalization Contract.EndContractBlock(); } - private static void VerifyNativeDigits(string [] nativeDig, string propertyName) + private static void VerifyNativeDigits(string[] nativeDig, string propertyName) { if (nativeDig == null) { @@ -157,7 +156,7 @@ namespace System.Globalization { // 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 @@ -175,8 +174,8 @@ namespace System.Globalization } } - private static void VerifyDigitSubstitution(DigitShapes digitSub, string propertyName) - { + private static void VerifyDigitSubstitution(DigitShapes digitSub, string propertyName) + { switch (digitSub) { case DigitShapes.Context: @@ -309,7 +308,7 @@ namespace System.Globalization set { VerifyWritable(); - VerifyDecimalSeparator(value, "CurrencyDecimalSeparator"); + VerifyDecimalSeparator(value, nameof(CurrencyDecimalSeparator)); currencyDecimalSeparator = value; } } @@ -404,13 +403,13 @@ namespace System.Globalization { if (value == null) { - throw new ArgumentNullException("PercentGroupSizes", + throw new ArgumentNullException(nameof(PercentGroupSizes), SR.ArgumentNull_Obj); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); - CheckGroupSize("PercentGroupSizes", inputSizes); + CheckGroupSize(nameof(PercentGroupSizes), inputSizes); percentGroupSizes = inputSizes; } } @@ -807,9 +806,9 @@ namespace System.Globalization } } - public string [] NativeDigits + public string[] NativeDigits { - get { return (String[]) nativeDigits.Clone(); } + get { return (String[])nativeDigits.Clone(); } set { VerifyWritable(); @@ -820,12 +819,12 @@ namespace System.Globalization public DigitShapes DigitSubstitution { - get { return (DigitShapes) digitSubstitution; } + get { return (DigitShapes)digitSubstitution; } set { VerifyWritable(); VerifyDigitSubstitution(value, nameof(DigitSubstitution)); - digitSubstitution = (int) value; + digitSubstitution = (int)value; } } diff --git a/src/mscorlib/shared/System/Globalization/PersianCalendar.cs b/src/mscorlib/shared/System/Globalization/PersianCalendar.cs index 445bbd6d0c..78a081e1b9 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/src/System/Globalization/SortKey.cs b/src/mscorlib/shared/System/Globalization/SortKey.cs index 0930965e5d..d65e097cb4 100644 --- a/src/mscorlib/src/System/Globalization/SortKey.cs +++ b/src/mscorlib/shared/System/Globalization/SortKey.cs @@ -11,15 +11,14 @@ // //////////////////////////////////////////////////////////////////////////// +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using System.Diagnostics; +using System.Diagnostics.Contracts; + namespace System.Globalization { - using System; - using System.Runtime.CompilerServices; - using System.Runtime.Serialization; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - [Serializable] public partial class SortKey { //--------------------------------------------------------------------// @@ -30,8 +29,7 @@ namespace System.Globalization internal string _localeName; // locale identifier [OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it - internal int _win32LCID; - // Whidbey serialization + internal int _win32LCID; internal CompareOptions _options; // options internal string _string; // original string @@ -45,8 +43,8 @@ namespace System.Globalization { _keyData = keyData; _localeName = localeName; - _options = options; - _string = str; + _options = options; + _string = str; } [OnSerializing] @@ -84,7 +82,7 @@ namespace System.Globalization return (_string); } } - + //////////////////////////////////////////////////////////////////////// // // GetKeyData @@ -100,7 +98,7 @@ namespace System.Globalization return (byte[])(_keyData.Clone()); } } - + //////////////////////////////////////////////////////////////////////// // // Compare @@ -112,14 +110,15 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// public static int Compare(SortKey sortkey1, SortKey sortkey2) { - if (sortkey1==null || sortkey2==null) + 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"); @@ -138,13 +137,13 @@ namespace System.Globalization int compLen = (key1Data.Length < key2Data.Length) ? key1Data.Length : key2Data.Length; - for (int i=0; i<compLen; i++) + for (int i = 0; i < compLen; i++) { - if (key1Data[i]>key2Data[i]) + if (key1Data[i] > key2Data[i]) { return (1); } - if (key1Data[i]<key2Data[i]) + if (key1Data[i] < key2Data[i]) { return (-1); } diff --git a/src/mscorlib/shared/System/Globalization/SortVersion.cs b/src/mscorlib/shared/System/Globalization/SortVersion.cs index a7aef6d84b..94c04d7063 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/src/System/Globalization/StringInfo.cs b/src/mscorlib/shared/System/Globalization/StringInfo.cs index f1dd30561b..87d1b9f684 100644 --- a/src/mscorlib/src/System/Globalization/StringInfo.cs +++ b/src/mscorlib/shared/System/Globalization/StringInfo.cs @@ -19,7 +19,6 @@ using System.Runtime.Serialization; namespace System.Globalization { - [Serializable] public class StringInfo { [OptionalField(VersionAdded = 2)] @@ -93,7 +92,7 @@ namespace System.Globalization { if (null == value) { - throw new ArgumentNullException("String", + throw new ArgumentNullException(nameof(String), SR.ArgumentNull_String); } Contract.EndContractBlock(); @@ -117,13 +116,13 @@ namespace System.Globalization } } - public string SubstringByTextElements(int startingTextElement) + public string SubstringByTextElements(int startingTextElement) { // If the string is empty, no sense going further. - if (null == this.Indexes) + if (null == this.Indexes) { // Just decide which error to give depending on the param they gave us.... - if (startingTextElement < 0) + if (startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum); } @@ -135,7 +134,7 @@ namespace System.Globalization return (SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement)); } - public string SubstringByTextElements(int startingTextElement, int lengthInTextElements) + public string SubstringByTextElements(int startingTextElement, int lengthInTextElements) { if (startingTextElement < 0) { diff --git a/src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs b/src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs index 2e735e0cb9..ec4188161a 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 8ba1f278e7..1e2ec62a71 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 9e6e30406c..e1646bfa8e 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 b7ba6d0112..c03ac23d95 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 786c2106a3..de09760fcb 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/src/System/IO/EncodingCache.cs b/src/mscorlib/shared/System/IO/EncodingCache.cs index 53379bc77f..53379bc77f 100644 --- a/src/mscorlib/src/System/IO/EncodingCache.cs +++ b/src/mscorlib/shared/System/IO/EncodingCache.cs diff --git a/src/mscorlib/shared/System/IO/EndOfStreamException.cs b/src/mscorlib/shared/System/IO/EndOfStreamException.cs index 7c4b2b744f..68e1b2c882 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 c6e583b34a..1b70bae172 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 b5e197c143..6fdf2d58cf 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 5d86b8f635..374c976055 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 0045ebeaf8..61cd007895 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 062b160b57..b9a9f8a783 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 7c09ae1a1c..c036ee6a83 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 500c60aa8c..68c5f70036 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 d6f0c628c3..1e573cd95d 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 b3a8783c32..9feb2873d8 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 08dc1d0251..ac9c4e77cd 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 ee0dd54383..ee2d29c032 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 613af051ca..64c8e6c7e6 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/src/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs index 284cd927dc..c8e720b7ac 100644 --- a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs +++ b/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs @@ -26,9 +26,6 @@ namespace System.IO private byte[] _array; private GCHandle _pinningHandle; - // The new inheritance model requires a Critical default ctor since base (UnmanagedMemoryStream) has one - private PinnedBufferMemoryStream() : base() { } - internal PinnedBufferMemoryStream(byte[] array) { Debug.Assert(array != null, "Array can't be null"); @@ -42,7 +39,7 @@ namespace System.IO } _array = array; - _pinningHandle = new GCHandle(array, GCHandleType.Pinned); + _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]) @@ -56,20 +53,11 @@ namespace System.IO protected override void Dispose(bool disposing) { - if (_isOpen) + if (_pinningHandle.IsAllocated) { _pinningHandle.Free(); - _isOpen = false; - } -#if _DEBUG - // To help track down lifetime issues on checked builds, force - //a full GC here. - if (disposing) - { - GC.Collect(); - GC.WaitForPendingFinalizers(); } -#endif + base.Dispose(disposing); } } diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs index f21fe47371..b78f50fe7b 100644 --- a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs +++ b/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs @@ -2,28 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** -** Purpose: Create a stream over unmanaged memory, mostly -** useful for memory-mapped files. -** -** -===========================================================*/ - -using System; -using System.Runtime; +using System.Diagnostics; +using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Security; using System.Threading; -using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Threading.Tasks; - namespace System.IO { /* @@ -47,45 +32,14 @@ namespace System.IO * call free, run a user-provided delegate to free the memory, etc. * We'll suggest user write a subclass of UnmanagedMemoryStream that uses * a SafeHandle subclass to hold onto the memory. - * Check for problems when using this in the negative parts of a - * process's address space. We may need to use unsigned longs internally - * and change the overflow detection logic. - * - * -----SECURITY MODEL AND SILVERLIGHT----- - * A few key notes about exposing UMS in silverlight: - * 1. No ctors are exposed to transparent code. This version of UMS only - * supports byte* (not SafeBuffer). Therefore, framework code can create - * a UMS and hand it to transparent code. Transparent code can use most - * operations on a UMS, but not operations that directly expose a - * pointer. - * - * 2. Scope of "unsafe" and non-CLS compliant operations reduced: The - * Whidbey version of this class has CLSCompliant(false) at the class - * level and unsafe modifiers at the method level. These were reduced to - * only where the unsafe operation is performed -- i.e. immediately - * around the pointer manipulation. Note that this brings UMS in line - * with recent changes in pu/clr to support SafeBuffer. * - * 3. Currently, the only caller that creates a UMS is ResourceManager, - * which creates read-only UMSs, and therefore operations that can - * change the length will throw because write isn't supported. A - * conservative option would be to formalize the concept that _only_ - * read-only UMSs can be creates, and enforce this by making WriteX and - * SetLength SecurityCritical. However, this is a violation of - * security inheritance rules, so we must keep these safe. The - * following notes make this acceptable for future use. - * a. a race condition in WriteX that could have allowed a thread to - * read from unzeroed memory was fixed - * b. memory region cannot be expanded beyond _capacity; in other - * words, a UMS creator is saying a writable UMS is safe to - * write to anywhere in the memory range up to _capacity, specified - * in the ctor. Even if the caller doesn't specify a capacity, then - * length is used as the capacity. */ + + /// <summary> + /// Stream over a memory pointer or over a SafeBuffer + /// </summary> public class UnmanagedMemoryStream : Stream { - private const long UnmanagedMemStreamMaxLength = Int64.MaxValue; - private SafeBuffer _buffer; private unsafe byte* _mem; private long _length; @@ -93,11 +47,12 @@ namespace System.IO private long _position; private long _offset; private FileAccess _access; - internal bool _isOpen; - [NonSerialized] + 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() { @@ -108,16 +63,32 @@ namespace System.IO _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) @@ -177,18 +148,27 @@ namespace System.IO _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) { @@ -215,24 +195,37 @@ namespace System.IO _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; @@ -244,11 +237,19 @@ namespace System.IO base.Dispose(disposing); } + /// <summary> + /// Since it's a memory stream, this method does nothing. + /// </summary> public override void Flush() { - if (!_isOpen) __Error.StreamIsClosed(); + 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) @@ -265,98 +266,92 @@ namespace System.IO } } - + /// <summary> + /// Number of bytes in the stream. + /// </summary> public override long Length { get { - if (!_isOpen) __Error.StreamIsClosed(); + 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) __Error.StreamIsClosed(); + 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) __Error.StreamIsClosed(); + 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 (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); + if (!CanSeek) throw Error.GetStreamIsClosed(); Contract.EndContractBlock(); - if (!CanSeek) __Error.StreamIsClosed(); -#if !BIT64 - unsafe { - // On 32 bit machines, ensure we don't wrap around. - if (value > (long) Int32.MaxValue || _mem + value < _mem) - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); - } -#endif Interlocked.Exchange(ref _position, value); } } + /// <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 (_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; - if (!_isOpen) __Error.StreamIsClosed(); return ptr; } set { - if (_buffer != null) - throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); - if (!_isOpen) __Error.StreamIsClosed(); + if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); + if (!_isOpen) throw Error.GetStreamIsClosed(); - // Note: subtracting pointers returns an Int64. Working around - // to avoid hitting compiler warning CS0652 on this line. - if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength) - throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength); if (value < _mem) throw new IOException(SR.IO_SeekBeforeBegin); + long newPosition = (long)value - (long)_mem; + if (newPosition < 0) + throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength); - Interlocked.Exchange(ref _position, value - _mem); - } - } - - internal unsafe byte* Pointer - { - get - { - if (_buffer != null) - throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); - - return _mem; + Interlocked.Exchange(ref _position, newPosition); } } - public override int Read([In, Out] byte[] buffer, int offset, int count) + /// <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); @@ -368,8 +363,8 @@ namespace System.IO throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync - if (!_isOpen) __Error.StreamIsClosed(); - if (!CanRead) __Error.ReadNotSupported(); + 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. @@ -418,6 +413,14 @@ namespace System.IO 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) @@ -446,10 +449,14 @@ namespace System.IO } } + /// <summary> + /// Returns the byte at the stream current Position and advances the Position. + /// </summary> + /// <returns></returns> public override int ReadByte() { - if (!_isOpen) __Error.StreamIsClosed(); - if (!CanRead) __Error.ReadNotSupported(); + 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); @@ -487,11 +494,15 @@ namespace System.IO 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) __Error.StreamIsClosed(); - if (offset > UnmanagedMemStreamMaxLength) - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_UnmanagedMemStreamLength); + if (!_isOpen) throw Error.GetStreamIsClosed(); switch (loc) { case SeekOrigin.Begin: @@ -523,15 +534,19 @@ namespace System.IO 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("length", SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); - if (!_isOpen) __Error.StreamIsClosed(); - if (!CanWrite) __Error.WriteNotSupported(); + if (!_isOpen) throw Error.GetStreamIsClosed(); + if (!CanWrite) throw Error.GetWriteNotSupported(); if (value > _capacity) throw new IOException(SR.IO_FixedCapacity); @@ -552,6 +567,12 @@ namespace System.IO } } + /// <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) @@ -564,8 +585,8 @@ namespace System.IO throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..) - if (!_isOpen) __Error.StreamIsClosed(); - if (!CanWrite) __Error.WriteNotSupported(); + 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); @@ -635,6 +656,14 @@ namespace System.IO 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) @@ -658,15 +687,18 @@ namespace System.IO catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); - return Task.FromException<Int32>(ex); + 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) __Error.StreamIsClosed(); - if (!CanWrite) __Error.WriteNotSupported(); + 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); diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs index 86e4707dfd..d547e771d7 100644 --- a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs +++ b/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs @@ -34,19 +34,16 @@ namespace System.IO public override bool CanRead { - [Pure] get { return _unmanagedStream.CanRead; } } public override bool CanSeek { - [Pure] get { return _unmanagedStream.CanSeek; } } public override bool CanWrite { - [Pure] get { return _unmanagedStream.CanWrite; } } @@ -55,7 +52,7 @@ namespace System.IO try { if (disposing) - _unmanagedStream.Close(); + _unmanagedStream.Dispose(); } finally { @@ -112,7 +109,7 @@ namespace System.IO } } - public override int Read([In, Out] byte[] buffer, int offset, int count) + public override int Read(byte[] buffer, int offset, int count) { return _unmanagedStream.Read(buffer, offset, count); } @@ -129,11 +126,8 @@ namespace System.IO public unsafe override byte[] ToArray() { - if (!_unmanagedStream._isOpen) __Error.StreamIsClosed(); - if (!_unmanagedStream.CanRead) __Error.ReadNotSupported(); - byte[] buffer = new byte[_unmanagedStream.Length]; - Buffer.Memcpy(buffer, 0, _unmanagedStream.Pointer, 0, (int)_unmanagedStream.Length); + _unmanagedStream.Read(buffer, 0, (int)_unmanagedStream.Length); return buffer; } @@ -154,9 +148,6 @@ namespace System.IO throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); Contract.EndContractBlock(); - if (!_unmanagedStream._isOpen) __Error.StreamIsClosed(); - if (!CanRead) __Error.ReadNotSupported(); - byte[] buffer = ToArray(); stream.Write(buffer, 0, buffer.Length); @@ -217,4 +208,3 @@ namespace System.IO } // class UnmanagedMemoryStreamWrapper } // namespace - diff --git a/src/mscorlib/shared/System/IndexOutOfRangeException.cs b/src/mscorlib/shared/System/IndexOutOfRangeException.cs index 4969c2b86d..d5b24b35d5 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 b9a4a12ddd..41df3ae970 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 01d92b2837..cf359ac0b5 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 24a08c8089..ad743e05ff 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 401b3a0ddb..47e7325836 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 8f0751c426..8b300f453d 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 55f915b65d..5d68714c7e 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<T> to surface additional debugging properties and diff --git a/src/mscorlib/shared/System/MarshalByRefObject.cs b/src/mscorlib/shared/System/MarshalByRefObject.cs index 1f1739b9cb..390b728329 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 54eee67b07..abca952f19 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 2ecbd14d6d..2c9c998c15 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 07d428967b..967f434302 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 4fcaa9857d..493671e227 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 5bc8df1e28..99882b9eb2 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 4d141eac8c..ae62527fac 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 21b2d54a46..8532e5ad2f 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 0aa5c6197a..f689345654 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 abb7c89dae..6e8e6b2d74 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 f183685998..a63db137f8 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/src/System/OperationCanceledException.cs b/src/mscorlib/shared/System/OperationCanceledException.cs index 826561776f..2c7654854f 100644 --- a/src/mscorlib/src/System/OperationCanceledException.cs +++ b/src/mscorlib/shared/System/OperationCanceledException.cs @@ -17,7 +17,6 @@ using System.Threading; namespace System { - [Serializable] public class OperationCanceledException : SystemException { [NonSerialized] @@ -68,6 +67,7 @@ namespace System 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 e28c688dd6..4052e41a18 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 d2370b3924..f679ac9454 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 a66a9ea423..4affed8a1a 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 612d0f086c..15759ea75d 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 459a19cb71..a0075bbc0b 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 d35ffc7066..b965c9f7fb 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 0000000000..7c4a980079 --- /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 6e11540505..13766ae8d0 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 3511433713..585fdb07cd 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 e3f882c409..07880a768d 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 dfc56667bd..0000000000 --- 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 fa32d43ccb..46ab32fccf 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 56f83c40d9..7822e9ff10 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 94bfffaa53..fd130e569b 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 18d6cf669d..640fee284a 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 13a5efff46..55376c66c0 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 772620cf84..ca0c6ab0db 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 c04ddd6d1a..6efa626946 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 03f8730cdd..6e43f56fa4 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 e934e5bde7..8d0bfef40d 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 c3604548e6..e200cdb94f 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 7f928d2486..bcbff05d62 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 70f41f4d9e..ec814393d0 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 b343e0cfbc..d2ddc992ac 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/src/System/Resources/ResourceFallbackManager.cs b/src/mscorlib/shared/System/Resources/ResourceFallbackManager.cs index 4ad7b4c93a..8268f3208d 100644 --- a/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs +++ b/src/mscorlib/shared/System/Resources/ResourceFallbackManager.cs @@ -30,15 +30,6 @@ namespace System.Resources private CultureInfo m_neutralResourcesCulture; private bool m_useParents; - // This is a cache of the thread, process, user, and OS-preferred fallback cultures. - // However, each thread may have a different value, and these may change during the - // lifetime of the process. So this cache must be verified each time we use it. - // Hence, we'll keep an array of strings for culture names & check it each time, - // but we'll really cache an array of CultureInfo's. Using thread-local statics - // as well to avoid differences across threads. - [ThreadStatic] - private static CultureInfo[] cachedOsFallbackArray; - internal ResourceFallbackManager(CultureInfo startingCulture, CultureInfo neutralResourcesCulture, bool useParents) { if (startingCulture != null) diff --git a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs b/src/mscorlib/shared/System/Resources/RuntimeResourceSet.cs index e9c038a498..41d7541c24 100644 --- a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs +++ b/src/mscorlib/shared/System/Resources/RuntimeResourceSet.cs @@ -13,18 +13,18 @@ ** ===========================================================*/ +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 { - using System; - using System.IO; - using System.Collections; - using System.Collections.Generic; - using System.Globalization; - using System.Reflection; - using System.Runtime.Versioning; - using System.Diagnostics; - using System.Diagnostics.Contracts; - // A RuntimeResourceSet stores all the resources defined in one // particular CultureInfo, with some loading optimizations. // @@ -161,7 +161,12 @@ namespace System.Resources // into smaller chunks, each of size sqrt(n), would be substantially better for // resource files containing thousands of resources. // - internal sealed class RuntimeResourceSet : ResourceSet, IEnumerable +#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 @@ -189,31 +194,18 @@ namespace System.Resources internal RuntimeResourceSet(String fileName) : base(false) { - BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(String)"); _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default); Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); _defaultReader = new ResourceReader(stream, _resCache); Reader = _defaultReader; } -#if LOOSELY_LINKED_RESOURCE_REFERENCE - internal RuntimeResourceSet(Stream stream, Assembly assembly) : base(false) - { - BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(Stream)"); - _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default); - _defaultReader = new ResourceReader(stream, _resCache); - Reader = _defaultReader; - Assembly = assembly; - } -#else internal RuntimeResourceSet(Stream stream) : base(false) { - BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(Stream)"); _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default); _defaultReader = new ResourceReader(stream, _resCache); Reader = _defaultReader; } -#endif // LOOSELY_LINKED_RESOURCE_REFERENCE protected override void Dispose(bool disposing) { @@ -305,8 +297,6 @@ namespace System.Resources if (_defaultReader != null) { - BCLDebug.Log("RESMGRFILEFORMAT", "Going down fast path in RuntimeResourceSet::GetObject"); - // Find the offset within the data section int dataPos = -1; if (_resCache.TryGetValue(key, out resLocation)) @@ -348,13 +338,6 @@ namespace System.Resources if (value != null || !ignoreCase) { -#if LOOSELY_LINKED_RESOURCE_REFERENCE - if (Assembly != null && (value is LooselyLinkedResourceReference)) { - LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value; - value = assRef.Resolve(Assembly); - } -#endif // LOOSELY_LINKED_RESOURCE_REFERENCE - return value; // may be null } } // if (_defaultReader != null) @@ -369,9 +352,6 @@ namespace System.Resources { _caseInsensitiveTable = new Dictionary<String, ResourceLocator>(StringComparer.OrdinalIgnoreCase); } -#if _DEBUG - BCLDebug.Perf(!ignoreCase, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing " + key + " correctly in your source"); -#endif if (_defaultReader == null) { @@ -450,13 +430,7 @@ namespace System.Resources copyOfCache[key] = resLocation; } } -#if LOOSELY_LINKED_RESOURCE_REFERENCE - if (Assembly != null && value is LooselyLinkedResourceReference) { - LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value; - value = assRef.Resolve(Assembly); - } -#endif // LOOSELY_LINKED_RESOURCE_REFERENCE return value; } } -} +}
\ 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 198ed3d0e7..66c9175ee7 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 4da95024c5..88e2657a6a 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 1f100bd415..d6da23fdf2 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 3da2a95aeb..1c05abd1fe 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 22fa694200..752295e876 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 f5419d413b..4c1f489215 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 56f4242bb1..0fe07edc9e 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 baf5824241..8dc6c43126 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 65653a44d9..ea843b3daa 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 0000000000..90e49d2a42 --- /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 5ac3918028..53afc95664 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 ae6d9b9372..3820f8544b 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 e82993a5de..841b666198 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 6e307e72af..f3842ec562 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 55dba0d113..609c560330 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 94ed5b5c74..e081d63e71 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 7772a1a263..25a8bfbc26 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 162676efe8..f049c89b3f 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 c142ec9ecc..77ab3ea770 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 7ee8480e89..e2cc79ec35 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 d7bde79c43..81b9a46928 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 a359daf4f9..bfe3313659 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 1026a87d1e..4fe90cad8d 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 89cb658aa9..7c4fa176f3 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 a1164dce91..227fed3fc3 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 0ef38e40ee..cfeebc1daf 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 13f75a37e9..2a80081912 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 86e3cd4631..538f475343 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 9641e1aa46..ea5a75906e 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 0a875e7373..fb0e88246c 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 8b4e2ae2fe..d5c18c8021 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 f4779a2cd4..d5bcde7efc 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 e5c1194849..628ec9a3fa 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 b2a003037b..aefe1f64bd 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 e4e91765e1..c4b54ce75c 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 360dd7f638..99995f759b 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 205ae26902..835bf8fb37 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 e4cd6c960e..450aee2a4a 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 5cfa89018a..ee5c92c3a8 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 0e4db9aaad..846946ce94 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 3755e65a7b..c12ac1c18d 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 8056a3b330..15bc5a7341 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 67857e9b11..a573af3383 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 2f296cb14e..86e19032b3 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 19ac19d6e0..777463b60d 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 120577fdcf..c64fc9ced8 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 d7690d4c7c..6657bcd36c 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 148b6300ef..2888415d0d 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 e693e7192f..5773f2726a 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 2ff77bc5fd..7a87943ed1 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 33bc8baee6..9477cb1ae4 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 e44946a669..770e70d7ab 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 88e2e21864..d4059babfc 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 ee21c2524f..5b7ce10268 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 32775a1c56..4ba95bc47b 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 7749c17414..2ba58918a0 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 32afbdfeb8..302dcb1ac1 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 293eb1f1aa..296198656b 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 9191028346..8d0b8a9f79 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 33e4687772..c7ed71c9cb 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 997358826f..667d576292 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 d33830181c..5cde572161 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 b99414c189..14e31c7bbd 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 f1957981d3..0000000000 --- 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 5c20f634fc..5162e6ad02 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 { } diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs deleted file mode 100644 index 8a7f591dfc..0000000000 --- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// Abstract derivations of SafeHandle designed to provide the common -// functionality supporting Win32 handles. More specifically, they describe how -// an invalid handle looks (for instance, some handles use -1 as an invalid -// handle value, others use 0). -// -// Further derivations of these classes can specialise this even further (e.g. -// file or registry handles). -// -// - -using System; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Runtime.ConstrainedExecution; - -namespace Microsoft.Win32.SafeHandles -{ - // Class of safe handle which uses 0 or -1 as an invalid handle. - public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle - { - protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle) - { - } - - // A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime - protected SafeHandleZeroOrMinusOneIsInvalid() - { - throw new NotImplementedException(); - } - - public override bool IsInvalid - { - get { return handle.IsNull() || handle == new IntPtr(-1); } - } - } - - // Class of safe handle which uses only -1 as an invalid handle. - public abstract class SafeHandleMinusOneIsInvalid : SafeHandle - { - protected SafeHandleMinusOneIsInvalid(bool ownsHandle) : base(new IntPtr(-1), ownsHandle) - { - } - - // A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime - protected SafeHandleMinusOneIsInvalid() - { - throw new NotImplementedException(); - } - - public override bool IsInvalid - { - get { return handle == new IntPtr(-1); } - } - } -} diff --git a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs index 8543bc8a99..b05445961d 100644 --- a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs +++ b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs @@ -93,7 +93,6 @@ namespace Microsoft.Win32 using System.Security; using System.Text; using System.Configuration.Assemblies; - using System.Runtime.Remoting; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; @@ -400,7 +399,6 @@ namespace Microsoft.Win32 internal int bInheritHandle = 0; } - [Serializable] [StructLayout(LayoutKind.Sequential)] internal struct WIN32_FILE_ATTRIBUTE_DATA { @@ -461,13 +459,11 @@ namespace Microsoft.Win32 internal const String USER32 = "user32.dll"; internal const String OLE32 = "ole32.dll"; internal const String OLEAUT32 = "oleaut32.dll"; - internal const String NTDLL = "ntdll.dll"; #else //FEATURE_PAL internal const String KERNEL32 = "libcoreclr"; internal const String USER32 = "libcoreclr"; internal const String OLE32 = "libcoreclr"; internal const String OLEAUT32 = "libcoreclr"; - internal const String NTDLL = "libcoreclr"; #endif //FEATURE_PAL internal const String ADVAPI32 = "advapi32.dll"; internal const String SHELL32 = "shell32.dll"; @@ -476,9 +472,6 @@ namespace Microsoft.Win32 internal const String SECUR32 = "secur32.dll"; internal const String MSCORWKS = "coreclr.dll"; - // From WinBase.h - internal const int SEM_FAILCRITICALERRORS = 1; - [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = true)] internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer, @@ -509,10 +502,6 @@ namespace Microsoft.Win32 [DllImport(KERNEL32, SetLastError = true)] internal static extern IntPtr LocalFree(IntPtr handle); - // MSDN says the length is a SIZE_T. - [DllImport(NTDLL, EntryPoint = "RtlZeroMemory")] - internal static extern void ZeroMemory(IntPtr address, UIntPtr length); - internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer) { buffer.length = Marshal.SizeOf(typeof(MEMORYSTATUSEX)); @@ -733,7 +722,6 @@ namespace Microsoft.Win32 } // Win32 Structs in N/Direct style - [Serializable] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] [BestFitMapping(false)] internal class WIN32_FIND_DATA @@ -783,18 +771,6 @@ namespace Microsoft.Win32 [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern bool SetCurrentDirectory(String path); - [DllImport(KERNEL32, SetLastError = false, EntryPoint = "SetErrorMode", ExactSpelling = true)] - private static extern int SetErrorMode_VistaAndOlder(int newMode); - - // RTM versions of Win7 and Windows Server 2008 R2 - private static readonly Version ThreadErrorModeMinOsVersion = new Version(6, 1, 7600); - - // this method uses the thread-safe version of SetErrorMode on Windows 7 / Windows Server 2008 R2 operating systems. - internal static int SetErrorMode(int newMode) - { - return SetErrorMode_VistaAndOlder(newMode); - } - internal const int LCID_SUPPORTED = 0x00000002; // supported locale ids [DllImport(KERNEL32)] diff --git a/src/mscorlib/src/System/AccessViolationException.cs b/src/mscorlib/src/System/AccessViolationException.cs index 12911c1b17..23d086fb42 100644 --- a/src/mscorlib/src/System/AccessViolationException.cs +++ b/src/mscorlib/src/System/AccessViolationException.cs @@ -16,7 +16,6 @@ using System.Runtime.Serialization; namespace System { - [Serializable] public class AccessViolationException : SystemException { public AccessViolationException() @@ -37,7 +36,10 @@ namespace System HResult = __HResults.E_POINTER; } - protected AccessViolationException(SerializationInfo info, StreamingContext context) : base(info, context) { } + protected AccessViolationException(SerializationInfo info, StreamingContext context) : base(info, context) + { + throw new PlatformNotSupportedException(); + } #pragma warning disable 169 // Field is not used from managed. private IntPtr _ip; // Address of faulting instruction. diff --git a/src/mscorlib/src/System/Activator.cs b/src/mscorlib/src/System/Activator.cs index 34c6ea5874..d11739b826 100644 --- a/src/mscorlib/src/System/Activator.cs +++ b/src/mscorlib/src/System/Activator.cs @@ -16,7 +16,6 @@ namespace System { using System; using System.Reflection; - using System.Runtime.Remoting; using System.Security; using CultureInfo = System.Globalization.CultureInfo; using Evidence = System.Security.Policy.Evidence; @@ -113,47 +112,6 @@ namespace System return Activator.CreateInstance(type, false); } - /* - * Create an instance using the name of type and the assembly where it exists. This allows - * types to be created remotely without having to load the type locally. - */ - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - static public ObjectHandle CreateInstance(String assemblyName, - String typeName) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return CreateInstance(assemblyName, - typeName, - false, - Activator.ConstructorDefault, - null, - null, - null, - null, - null, - ref stackMark); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - static public ObjectHandle CreateInstance(String assemblyName, - String typeName, - Object[] activationAttributes) - - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return CreateInstance(assemblyName, - typeName, - false, - Activator.ConstructorDefault, - null, - null, - null, - activationAttributes, - null, - ref stackMark); - } - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod static public Object CreateInstance(Type type, bool nonPublic) { @@ -185,221 +143,5 @@ namespace System // Skip the CreateInstanceCheckThis call to avoid perf cost and to maintain compatibility with V2 (throwing the same exceptions). return (T)rt.CreateInstanceDefaultCtor(true /*publicOnly*/, true /*skipCheckThis*/, true /*fillCache*/, ref stackMark); } - - static public ObjectHandle CreateInstanceFrom(String assemblyFile, - String typeName) - - { - return CreateInstanceFrom(assemblyFile, typeName, null); - } - - static public ObjectHandle CreateInstanceFrom(String assemblyFile, - String typeName, - Object[] activationAttributes) - - { - return CreateInstanceFrom(assemblyFile, - typeName, - false, - Activator.ConstructorDefault, - null, - null, - null, - activationAttributes); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static ObjectHandle CreateInstance(string assemblyName, - string typeName, - bool ignoreCase, - BindingFlags bindingAttr, - Binder binder, - object[] args, - CultureInfo culture, - object[] activationAttributes) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return CreateInstance(assemblyName, - typeName, - ignoreCase, - bindingAttr, - binder, - args, - culture, - activationAttributes, - null, - ref stackMark); - } - - static internal ObjectHandle CreateInstance(String assemblyString, - String typeName, - bool ignoreCase, - BindingFlags bindingAttr, - Binder binder, - Object[] args, - CultureInfo culture, - Object[] activationAttributes, - Evidence securityInfo, - ref StackCrawlMark stackMark) - { - Type type = null; - Assembly assembly = null; - if (assemblyString == null) - { - assembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark); - } - else - { - RuntimeAssembly assemblyFromResolveEvent; - AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, false /*forIntrospection*/, out assemblyFromResolveEvent); - if (assemblyFromResolveEvent != null) - { - // Assembly was resolved via AssemblyResolve event - assembly = assemblyFromResolveEvent; - } - else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) - { - // WinRT type - we have to use Type.GetType - type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase); - } - else - { - // Classic managed type - assembly = RuntimeAssembly.InternalLoadAssemblyName( - assemblyName, securityInfo, null, ref stackMark, - true /*thrownOnFileNotFound*/, false /*forIntrospection*/); - } - } - - if (type == null) - { - // It's classic managed type (not WinRT type) - Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyString); - if (assembly == null) return null; - - type = assembly.GetType(typeName, true /*throwOnError*/, ignoreCase); - } - - Object o = Activator.CreateInstance(type, - bindingAttr, - binder, - args, - culture, - activationAttributes); - - Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); - if (o == null) - return null; - else - { - ObjectHandle Handle = new ObjectHandle(o); - return Handle; - } - } - - public static ObjectHandle CreateInstanceFrom(string assemblyFile, - string typeName, - bool ignoreCase, - BindingFlags bindingAttr, - Binder binder, - object[] args, - CultureInfo culture, - object[] activationAttributes) - { - return CreateInstanceFromInternal(assemblyFile, - typeName, - ignoreCase, - bindingAttr, - binder, - args, - culture, - activationAttributes, - null); - } - - private static ObjectHandle CreateInstanceFromInternal(String assemblyFile, - String typeName, - bool ignoreCase, - BindingFlags bindingAttr, - Binder binder, - Object[] args, - CultureInfo culture, - Object[] activationAttributes, - Evidence securityInfo) - { -#pragma warning disable 618 - Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo); -#pragma warning restore 618 - Type t = assembly.GetType(typeName, true, ignoreCase); - - Object o = Activator.CreateInstance(t, - bindingAttr, - binder, - args, - culture, - activationAttributes); - - Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); - if (o == null) - return null; - else - { - ObjectHandle Handle = new ObjectHandle(o); - return Handle; - } - } - - public static ObjectHandle CreateComInstanceFrom(String assemblyName, - String typeName) - { - return CreateComInstanceFrom(assemblyName, - typeName, - null, - AssemblyHashAlgorithm.None); - } - - public static ObjectHandle CreateComInstanceFrom(String assemblyName, - String typeName, - byte[] hashValue, - AssemblyHashAlgorithm hashAlgorithm) - { - Assembly assembly = Assembly.LoadFrom(assemblyName, hashValue, hashAlgorithm); - - Type t = assembly.GetType(typeName, true, false); - - Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute), false); - if (Attr.Length > 0) - { - if (((ComVisibleAttribute)Attr[0]).Value == false) - throw new TypeLoadException(SR.Argument_TypeMustBeVisibleFromCom); - } - - Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName); - - if (assembly == null) return null; - - - Object o = Activator.CreateInstance(t, - Activator.ConstructorDefault, - null, - null, - null, - null); - - Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); - if (o == null) - return null; - else - { - ObjectHandle Handle = new ObjectHandle(o); - return Handle; - } - } - - [System.Diagnostics.Conditional("_DEBUG")] - private static void Log(bool test, string title, string success, string failure) - { - } } } - diff --git a/src/mscorlib/src/System/AppDomain.cs b/src/mscorlib/src/System/AppDomain.cs index 7d2f2ceaf8..24c6765026 100644 --- a/src/mscorlib/src/System/AppDomain.cs +++ b/src/mscorlib/src/System/AppDomain.cs @@ -25,7 +25,6 @@ namespace System using System.Collections.Generic; using System.Threading; using System.Runtime.InteropServices; - using System.Runtime.Remoting; using System.Reflection.Emit; using CultureInfo = System.Globalization.CultureInfo; using System.IO; @@ -37,7 +36,6 @@ namespace System using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; - [Serializable] internal delegate void AppDomainInitializer(string[] args); internal class AppDomainInitializerInfo @@ -258,18 +256,6 @@ namespace System private static extern APPX_FLAGS nGetAppXFlags(); #endif - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetAppDomainManagerType(AppDomainHandle domain, - StringHandleOnStack retAssembly, - StringHandleOnStack retType); - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void SetAppDomainManagerType(AppDomainHandle domain, - string assembly, - string type); - [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void SetSecurityHomogeneousFlag(AppDomainHandle domain, @@ -328,54 +314,6 @@ namespace System SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths, appLocalWinMD); } - string domainManagerAssembly; - string domainManagerType; - GetAppDomainManagerType(out domainManagerAssembly, out domainManagerType); - - if (domainManagerAssembly != null && domainManagerType != null) - { - try - { - _domainManager = CreateInstanceAndUnwrap(domainManagerAssembly, domainManagerType) as AppDomainManager; - } - catch (FileNotFoundException e) - { - throw new TypeLoadException(SR.Argument_NoDomainManager, e); - } - catch (SecurityException e) - { - throw new TypeLoadException(SR.Argument_NoDomainManager, e); - } - catch (TypeLoadException e) - { - throw new TypeLoadException(SR.Argument_NoDomainManager, e); - } - - if (_domainManager == null) - { - throw new TypeLoadException(SR.Argument_NoDomainManager); - } - - // If this domain was not created by a managed call to CreateDomain, then the AppDomainSetup - // will not have the correct values for the AppDomainManager set. - FusionStore.AppDomainManagerAssembly = domainManagerAssembly; - FusionStore.AppDomainManagerType = domainManagerType; - - bool notifyFusion = _domainManager.GetType() != typeof(System.AppDomainManager) && !DisableFusionUpdatesFromADManager(); - - - - AppDomainSetup FusionStoreOld = null; - if (notifyFusion) - FusionStoreOld = new AppDomainSetup(FusionStore, true); - - // Initialize the AppDomainMAnager and register the instance with the native host if requested - _domainManager.InitializeNewDomain(FusionStore); - - if (notifyFusion) - SetupFusionStore(_FusionStore, FusionStoreOld); // Notify Fusion about the changes the user implementation of InitializeNewDomain may have made to the FusionStore object. - } - InitializeCompatibilityFlags(); } @@ -485,34 +423,6 @@ namespace System } /// <summary> - /// Get the name of the assembly and type that act as the AppDomainManager for this domain - /// </summary> - internal void GetAppDomainManagerType(out string assembly, out string type) - { - // We can't just use our parameters because we need to ensure that the strings used for hte QCall - // are on the stack. - string localAssembly = null; - string localType = null; - - GetAppDomainManagerType(GetNativeHandle(), - JitHelpers.GetStringHandleOnStack(ref localAssembly), - JitHelpers.GetStringHandleOnStack(ref localType)); - - assembly = localAssembly; - type = localType; - } - - /// <summary> - /// Set the assembly and type which act as the AppDomainManager for this domain - /// </summary> - private void SetAppDomainManagerType(string assembly, string type) - { - Debug.Assert(assembly != null, "assembly != null"); - Debug.Assert(type != null, "type != null"); - SetAppDomainManagerType(GetNativeHandle(), assembly, type); - } - - /// <summary> /// Called for every AppDomain (including the default domain) to initialize the security of the AppDomain) /// </summary> private void InitializeDomainSecurity(Evidence providedSecurityInfo, @@ -584,23 +494,6 @@ namespace System } } - - public ObjectHandle CreateInstance(String assemblyName, - String typeName) - - { - // jit does not check for that, so we should do it ... - if (this == null) - throw new NullReferenceException(); - - if (assemblyName == null) - throw new ArgumentNullException(nameof(assemblyName)); - Contract.EndContractBlock(); - - return Activator.CreateInstance(assemblyName, - typeName); - } - public static AppDomain CurrentDomain { get @@ -646,6 +539,14 @@ namespace System return StringBuilderCache.GetStringAndRelease(sb); } + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Assembly[] nGetAssemblies(bool forIntrospection); + + internal Assembly[] GetAssemblies(bool forIntrospection) + { + return nGetAssemblies(forIntrospection); + } + // this is true when we've removed the handles etc so really can't do anything [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern bool IsUnloadingForcedFinalize(); @@ -664,17 +565,6 @@ namespace System throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); - // SetData should only be used to set values that don't already exist. - object currentVal; - lock (((ICollection)LocalStore).SyncRoot) - { - LocalStore.TryGetValue(name, out currentVal); - } - if (currentVal != null) - { - throw new InvalidOperationException(SR.InvalidOperation_SetData_OnlyOnce); - } - lock (((ICollection)LocalStore).SyncRoot) { LocalStore[name] = data; @@ -688,38 +578,14 @@ namespace System throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); - int key = AppDomainSetup.Locate(name); - if (key == -1) + object data; + lock (((ICollection)LocalStore).SyncRoot) { - if (name.Equals(AppDomainSetup.LoaderOptimizationKey)) - return FusionStore.LoaderOptimization; - else - { - object data; - lock (((ICollection)LocalStore).SyncRoot) - { - LocalStore.TryGetValue(name, out data); - } - if (data == null) - return null; - return data; - } - } - else - { - // Be sure to call these properties, not Value, so - // that the appropriate permission demand will be done - switch (key) - { - case (int)AppDomainSetup.LoaderInformation.ApplicationBaseValue: - return FusionStore.ApplicationBase; - case (int)AppDomainSetup.LoaderInformation.ApplicationNameValue: - return FusionStore.ApplicationName; - default: - Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()"); - return null; - } + LocalStore.TryGetValue(name, out data); } + if (data == null) + return null; + return data; } [Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)] @@ -1150,12 +1016,6 @@ namespace System } #endif // FEATURE_COMINTEROP - // set up the AppDomainManager for this domain and initialize security. - if (adSetup.AppDomainManagerAssembly != null && adSetup.AppDomainManagerType != null) - { - ad.SetAppDomainManagerType(adSetup.AppDomainManagerAssembly, adSetup.AppDomainManagerType); - } - ad.CreateAppDomainManager(); // could modify FusionStore's object ad.InitializeDomainSecurity(providedSecurityInfo, creatorsSecurityInfo, @@ -1293,16 +1153,6 @@ namespace System } } - public Object CreateInstanceAndUnwrap(String assemblyName, - String typeName) - { - ObjectHandle oh = CreateInstance(assemblyName, typeName); - if (oh == null) - return null; - - return oh.Unwrap(); - } // CreateInstanceAndUnwrap - public Int32 Id { get diff --git a/src/mscorlib/src/System/AppDomainAttributes.cs b/src/mscorlib/src/System/AppDomainAttributes.cs index deb43eadf9..92d6d8bbb2 100644 --- a/src/mscorlib/src/System/AppDomainAttributes.cs +++ b/src/mscorlib/src/System/AppDomainAttributes.cs @@ -13,7 +13,6 @@ namespace System { - [Serializable] internal enum LoaderOptimization { NotSpecified = 0, diff --git a/src/mscorlib/src/System/AppDomainSetup.cs b/src/mscorlib/src/System/AppDomainSetup.cs index 142b8a05f7..7714da12ab 100644 --- a/src/mscorlib/src/System/AppDomainSetup.cs +++ b/src/mscorlib/src/System/AppDomainSetup.cs @@ -22,10 +22,8 @@ namespace System using System.Diagnostics.Contracts; using System.Collections.Generic; - [Serializable] internal sealed class AppDomainSetup { - [Serializable] internal enum LoaderInformation { // If you add a new value, add the corresponding property @@ -338,18 +336,6 @@ namespace System } } - static internal int Locate(String s) - { - if (String.IsNullOrEmpty(s)) - return -1; - - Debug.Assert('A' == ACTAG_APP_BASE_URL[0], "Assumption violated"); - if (s[0] == 'A' && s == ACTAG_APP_BASE_URL) - return (int)LoaderInformation.ApplicationBaseValue; - - return -1; - } - #if FEATURE_COMINTEROP public bool SandboxInterop { diff --git a/src/mscorlib/src/System/AppDomainUnloadedException.cs b/src/mscorlib/src/System/AppDomainUnloadedException.cs index 52cbb980af..a5e74e2b23 100644 --- a/src/mscorlib/src/System/AppDomainUnloadedException.cs +++ b/src/mscorlib/src/System/AppDomainUnloadedException.cs @@ -16,7 +16,6 @@ using System.Runtime.Serialization; namespace System { - [Serializable] internal class AppDomainUnloadedException : SystemException { public AppDomainUnloadedException() @@ -30,6 +29,7 @@ namespace System // protected AppDomainUnloadedException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/Array.cs b/src/mscorlib/src/System/Array.cs index 05c4804cc5..fcfeb94675 100644 --- a/src/mscorlib/src/System/Array.cs +++ b/src/mscorlib/src/System/Array.cs @@ -2415,7 +2415,6 @@ namespace System } } - [Serializable] private sealed class SZArrayEnumerator : IEnumerator, ICloneable { private Array _array; @@ -2461,7 +2460,6 @@ namespace System } } - [Serializable] private sealed class ArrayEnumerator : IEnumerator, ICloneable { private Array array; @@ -2723,7 +2721,6 @@ namespace System // This is a normal generic Enumerator for SZ arrays. It doesn't have any of the "this" stuff // that SZArrayHelper does. // - [Serializable] private sealed class SZGenericArrayEnumerator<T> : IEnumerator<T> { private T[] _array; diff --git a/src/mscorlib/src/System/ArraySegment.cs b/src/mscorlib/src/System/ArraySegment.cs index a18590d5d8..664352708d 100644 --- a/src/mscorlib/src/System/ArraySegment.cs +++ b/src/mscorlib/src/System/ArraySegment.cs @@ -316,7 +316,6 @@ namespace System } } - [Serializable] public struct Enumerator : IEnumerator<T> { private readonly T[] _array; diff --git a/src/mscorlib/src/System/BCLDebug.cs b/src/mscorlib/src/System/BCLDebug.cs index 67f7c9a0f7..4a5f6d1891 100644 --- a/src/mscorlib/src/System/BCLDebug.cs +++ b/src/mscorlib/src/System/BCLDebug.cs @@ -15,7 +15,6 @@ namespace System { using System.IO; using System.Text; - using System.Runtime.Remoting; using System.Diagnostics; using Microsoft.Win32; using System.Runtime.CompilerServices; @@ -23,7 +22,6 @@ namespace System using System.Security; using System.Diagnostics.Contracts; - [Serializable] internal enum LogLevel { Trace = 0, diff --git a/src/mscorlib/src/System/BadImageFormatException.CoreCLR.cs b/src/mscorlib/src/System/BadImageFormatException.CoreCLR.cs new file mode 100644 index 0000000000..094668bde0 --- /dev/null +++ b/src/mscorlib/src/System/BadImageFormatException.CoreCLR.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System +{ + public partial class BadImageFormatException + { + // Do not delete: this is invoked from native code. + private BadImageFormatException(string fileName, string fusionLog, int hResult) + : base(null) + { + HResult = hResult; + _fileName = fileName; + _fusionLog = fusionLog; + SetMessageField(); + } + } +} diff --git a/src/mscorlib/src/System/Boolean.cs b/src/mscorlib/src/System/Boolean.cs index fe25e22920..59cab74456 100644 --- a/src/mscorlib/src/System/Boolean.cs +++ b/src/mscorlib/src/System/Boolean.cs @@ -26,10 +26,10 @@ namespace System // // Member Variables // - private bool m_value; + private bool m_value; // Do not rename (binary serialization) - // The true value. - // + // The true value. + // internal const int True = 1; // The false value. diff --git a/src/mscorlib/src/System/Byte.cs b/src/mscorlib/src/System/Byte.cs index 27fdcd7a64..da3b790ac6 100644 --- a/src/mscorlib/src/System/Byte.cs +++ b/src/mscorlib/src/System/Byte.cs @@ -28,7 +28,7 @@ namespace System public struct Byte : IComparable, IFormattable, IConvertible , IComparable<Byte>, IEquatable<Byte> { - private byte m_value; + private byte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; diff --git a/src/mscorlib/src/System/Collections/ArrayList.cs b/src/mscorlib/src/System/Collections/ArrayList.cs deleted file mode 100644 index cee7be726a..0000000000 --- a/src/mscorlib/src/System/Collections/ArrayList.cs +++ /dev/null @@ -1,626 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** -** -** Purpose: Implements a dynamically sized List as an array, -** and provides many convenience methods for treating -** an array as an IList. -** -** -===========================================================*/ - -using System; -using System.Runtime; -using System.Security; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Runtime.Serialization; -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; - -namespace System.Collections -{ - // Implements a variable-size List that uses an array of objects to store the - // elements. A ArrayList has a capacity, which is the allocated length - // of the internal array. As elements are added to a ArrayList, the capacity - // of the ArrayList is automatically increased as required by reallocating the - // internal array. - // - [FriendAccessAllowed] - [DebuggerTypeProxy(typeof(System.Collections.ArrayList.ArrayListDebugView))] - [DebuggerDisplay("Count = {Count}")] - [Serializable] - internal class ArrayList : IList, ICloneable - { - private Object[] _items; - [ContractPublicPropertyName("Count")] - private int _size; - private int _version; - [NonSerialized] - private Object _syncRoot; - - private const int _defaultCapacity = 4; - private static readonly Object[] emptyArray = Array.Empty<Object>(); - - // Constructs a ArrayList. The list is initially empty and has a capacity - // of zero. Upon adding the first element to the list the capacity is - // increased to _defaultCapacity, and then increased in multiples of two as required. - public ArrayList() - { - _items = emptyArray; - } - - // Constructs a ArrayList with a given initial capacity. The list is - // initially empty, but will have room for the given number of elements - // before any reallocations are required. - // - public ArrayList(int capacity) - { - if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(capacity))); - Contract.EndContractBlock(); - - if (capacity == 0) - _items = emptyArray; - else - _items = new Object[capacity]; - } - - // Constructs a ArrayList, copying the contents of the given collection. The - // size and capacity of the new list will both be equal to the size of the - // given collection. - // - public ArrayList(ICollection c) - { - if (c == null) - throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); - Contract.EndContractBlock(); - - int count = c.Count; - if (count == 0) - { - _items = emptyArray; - } - else - { - _items = new Object[count]; - AddRange(c); - } - } - - // Gets and sets the capacity of this list. The capacity is the size of - // the internal array used to hold items. When set, the internal - // array of the list is reallocated to the given capacity. - // - public virtual int Capacity - { - get - { - Contract.Ensures(Contract.Result<int>() >= Count); - return _items.Length; - } - set - { - if (value < _size) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); - } - Contract.Ensures(Capacity >= 0); - Contract.EndContractBlock(); - // We don't want to update the version number when we change the capacity. - // Some existing applications have dependency on this. - if (value != _items.Length) - { - if (value > 0) - { - Object[] newItems = new Object[value]; - if (_size > 0) - { - Array.Copy(_items, 0, newItems, 0, _size); - } - _items = newItems; - } - else - { - _items = new Object[_defaultCapacity]; - } - } - } - } - - // Read-only property describing how many elements are in the List. - public virtual int Count - { - get - { - Contract.Ensures(Contract.Result<int>() >= 0); - return _size; - } - } - - public virtual bool IsFixedSize - { - get { return false; } - } - - - // Is this ArrayList read-only? - public virtual bool IsReadOnly - { - get { return false; } - } - - // Is this ArrayList synchronized (thread-safe)? - public virtual bool IsSynchronized - { - get { return false; } - } - - // Synchronization root for this object. - public virtual Object SyncRoot - { - get - { - if (_syncRoot == null) - { - System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); - } - return _syncRoot; - } - } - - // Sets or Gets the element at the given index. - // - public virtual Object this[int index] - { - get - { - if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); - return _items[index]; - } - set - { - if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); - _items[index] = value; - _version++; - } - } - - // Adds the given object to the end of this list. The size of the list is - // increased by one. If required, the capacity of the list is doubled - // before adding the new element. - // - public virtual int Add(Object value) - { - Contract.Ensures(Contract.Result<int>() >= 0); - if (_size == _items.Length) EnsureCapacity(_size + 1); - _items[_size] = value; - _version++; - return _size++; - } - - // Adds the elements of the given collection to the end of this list. If - // required, the capacity of the list is increased to twice the previous - // capacity or the new size, whichever is larger. - // - public virtual void AddRange(ICollection c) - { - InsertRange(_size, c); - } - - - // Clears the contents of ArrayList. - public virtual void Clear() - { - if (_size > 0) - { - Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. - _size = 0; - } - _version++; - } - - // Clones this ArrayList, doing a shallow copy. (A copy is made of all - // Object references in the ArrayList, but the Objects pointed to - // are not cloned). - public virtual Object Clone() - { - Contract.Ensures(Contract.Result<Object>() != null); - ArrayList la = new ArrayList(_size); - la._size = _size; - la._version = _version; - Array.Copy(_items, 0, la._items, 0, _size); - return la; - } - - - // Contains returns true if the specified element is in the ArrayList. - // It does a linear, O(n) search. Equality is determined by calling - // item.Equals(). - // - public virtual bool Contains(Object item) - { - if (item == null) - { - for (int i = 0; i < _size; i++) - if (_items[i] == null) - return true; - return false; - } - else - { - for (int i = 0; i < _size; i++) - if ((_items[i] != null) && (_items[i].Equals(item))) - return true; - return false; - } - } - - // Copies this ArrayList into array, which must be of a - // compatible array type. - // - public virtual void CopyTo(Array array, int arrayIndex) - { - if ((array != null) && (array.Rank != 1)) - throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); - Contract.EndContractBlock(); - // Delegate rest of error checking to Array.Copy. - Array.Copy(_items, 0, array, arrayIndex, _size); - } - - // Ensures that the capacity of this list is at least the given minimum - // value. If the currect capacity of the list is less than min, the - // capacity is increased to twice the current capacity or to min, - // whichever is larger. - private void EnsureCapacity(int min) - { - if (_items.Length < min) - { - int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2; - // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. - // Note that this check works even when _items.Length overflowed thanks to the (uint) cast - if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; - if (newCapacity < min) newCapacity = min; - Capacity = newCapacity; - } - } - - // Returns an enumerator for this list with the given - // permission for removal of elements. If modifications made to the list - // while an enumeration is in progress, the MoveNext and - // GetObject methods of the enumerator will throw an exception. - // - public virtual IEnumerator GetEnumerator() - { - Contract.Ensures(Contract.Result<IEnumerator>() != null); - return new ArrayListEnumeratorSimple(this); - } - - // Returns the index of the first occurrence of a given value in a range of - // this list. The list is searched forwards from beginning to end. - // The elements of the list are compared to the given value using the - // Object.Equals method. - // - // This method uses the Array.IndexOf method to perform the - // search. - // - public virtual int IndexOf(Object value) - { - Contract.Ensures(Contract.Result<int>() < Count); - return Array.IndexOf((Array)_items, value, 0, _size); - } - - // Inserts an element into this list at a given index. The size of the list - // is increased by one. If required, the capacity of the list is doubled - // before inserting the new element. - // - public virtual void Insert(int index, Object value) - { - // Note that insertions at the end are legal. - if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_ArrayListInsert); - //Contract.Ensures(Count == Contract.OldValue(Count) + 1); - Contract.EndContractBlock(); - - if (_size == _items.Length) EnsureCapacity(_size + 1); - if (index < _size) - { - Array.Copy(_items, index, _items, index + 1, _size - index); - } - _items[index] = value; - _size++; - _version++; - } - - // Inserts the elements of the given collection at a given index. If - // required, the capacity of the list is increased to twice the previous - // capacity or the new size, whichever is larger. Ranges may be added - // to the end of the list by setting index to the ArrayList's size. - // - public virtual void InsertRange(int index, ICollection c) - { - if (c == null) - throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); - if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - //Contract.Ensures(Count == Contract.OldValue(Count) + c.Count); - Contract.EndContractBlock(); - - int count = c.Count; - if (count > 0) - { - EnsureCapacity(_size + count); - // shift existing items - if (index < _size) - { - Array.Copy(_items, index, _items, index + count, _size - index); - } - - Object[] itemsToInsert = new Object[count]; - c.CopyTo(itemsToInsert, 0); - itemsToInsert.CopyTo(_items, index); - _size += count; - _version++; - } - } - - // Returns a read-only IList wrapper for the given IList. - // - [FriendAccessAllowed] - public static IList ReadOnly(IList list) - { - if (list == null) - throw new ArgumentNullException(nameof(list)); - Contract.Ensures(Contract.Result<IList>() != null); - Contract.EndContractBlock(); - return new ReadOnlyList(list); - } - - // Removes the element at the given index. The size of the list is - // decreased by one. - // - public virtual void Remove(Object obj) - { - Contract.Ensures(Count >= 0); - - int index = IndexOf(obj); - BCLDebug.Correctness(index >= 0 || !(obj is Int32), "You passed an Int32 to Remove that wasn't in the ArrayList." + Environment.NewLine + "Did you mean RemoveAt? int: " + obj + " Count: " + Count); - if (index >= 0) - RemoveAt(index); - } - - // Removes the element at the given index. The size of the list is - // decreased by one. - // - public virtual void RemoveAt(int index) - { - if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - Contract.Ensures(Count >= 0); - //Contract.Ensures(Count == Contract.OldValue(Count) - 1); - Contract.EndContractBlock(); - - _size--; - if (index < _size) - { - Array.Copy(_items, index + 1, _items, index, _size - index); - } - _items[_size] = null; - _version++; - } - - // ToArray returns a new array of a particular type containing the contents - // of the ArrayList. This requires copying the ArrayList and potentially - // downcasting all elements. This copy may fail and is an O(n) operation. - // Internally, this implementation calls Array.Copy. - // - public virtual Array ToArray(Type type) - { - if (type == null) - throw new ArgumentNullException(nameof(type)); - Contract.Ensures(Contract.Result<Array>() != null); - Contract.EndContractBlock(); - Array array = Array.UnsafeCreateInstance(type, _size); - Array.Copy(_items, 0, array, 0, _size); - return array; - } - - [Serializable] - private class ReadOnlyList : IList - { - private IList _list; - - internal ReadOnlyList(IList l) - { - _list = l; - } - - public virtual int Count - { - get { return _list.Count; } - } - - public virtual bool IsReadOnly - { - get { return true; } - } - - public virtual bool IsFixedSize - { - get { return true; } - } - - public virtual bool IsSynchronized - { - get { return _list.IsSynchronized; } - } - - public virtual Object this[int index] - { - get - { - return _list[index]; - } - set - { - throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); - } - } - - public virtual Object SyncRoot - { - get { return _list.SyncRoot; } - } - - public virtual int Add(Object obj) - { - throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); - } - - public virtual void Clear() - { - throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); - } - - public virtual bool Contains(Object obj) - { - return _list.Contains(obj); - } - - public virtual void CopyTo(Array array, int index) - { - _list.CopyTo(array, index); - } - - public virtual IEnumerator GetEnumerator() - { - return _list.GetEnumerator(); - } - - public virtual int IndexOf(Object value) - { - return _list.IndexOf(value); - } - - public virtual void Insert(int index, Object obj) - { - throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); - } - - public virtual void Remove(Object value) - { - throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); - } - - public virtual void RemoveAt(int index) - { - throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); - } - } - - [Serializable] - private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable - { - private ArrayList list; - private int index; - private int version; - private Object currentElement; - [NonSerialized] - private bool isArrayList; - // this object is used to indicate enumeration has not started or has terminated - private static Object dummyObject = new Object(); - - internal ArrayListEnumeratorSimple(ArrayList list) - { - this.list = list; - index = -1; - version = list._version; - isArrayList = (list.GetType() == typeof(ArrayList)); - currentElement = dummyObject; - } - - public Object Clone() - { - return MemberwiseClone(); - } - - public bool MoveNext() - { - if (version != list._version) - { - throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); - } - - if (isArrayList) - { // avoid calling virtual methods if we are operating on ArrayList to improve performance - if (index < list._size - 1) - { - currentElement = list._items[++index]; - return true; - } - else - { - currentElement = dummyObject; - index = list._size; - return false; - } - } - else - { - if (index < list.Count - 1) - { - currentElement = list[++index]; - return true; - } - else - { - index = list.Count; - currentElement = dummyObject; - return false; - } - } - } - - public Object Current - { - get - { - object temp = currentElement; - if (dummyObject == temp) - { // check if enumeration has not started or has terminated - if (index == -1) - { - throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); - } - else - { - throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumEnded)); - } - } - - return temp; - } - } - - public void Reset() - { - if (version != list._version) - { - throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); - } - - currentElement = dummyObject; - index = -1; - } - } - - internal class ArrayListDebugView - { - private ArrayList arrayList; - } - } -} diff --git a/src/mscorlib/src/System/Collections/Comparer.cs b/src/mscorlib/src/System/Collections/Comparer.cs index 7f4f9f0a07..76e19e77f1 100644 --- a/src/mscorlib/src/System/Collections/Comparer.cs +++ b/src/mscorlib/src/System/Collections/Comparer.cs @@ -20,7 +20,6 @@ using System.Diagnostics.Contracts; namespace System.Collections { - [Serializable] internal sealed class Comparer : IComparer, ISerializable { private CompareInfo m_compareInfo; @@ -44,21 +43,6 @@ namespace System.Collections m_compareInfo = culture.CompareInfo; } - private Comparer(SerializationInfo info, StreamingContext context) - { - m_compareInfo = null; - SerializationInfoEnumerator enumerator = info.GetEnumerator(); - while (enumerator.MoveNext()) - { - switch (enumerator.Name) - { - case CompareInfoName: - m_compareInfo = (CompareInfo)info.GetValue(CompareInfoName, typeof(CompareInfo)); - break; - } - } - } - // Compares two Objects by calling CompareTo. If a == // b,0 is returned. If a implements // IComparable, a.CompareTo(b) is returned. If a @@ -92,16 +76,7 @@ namespace System.Collections public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); - - if (m_compareInfo != null) - { - info.AddValue(CompareInfoName, m_compareInfo); - } + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/Collections/CompatibleComparer.cs b/src/mscorlib/src/System/Collections/CompatibleComparer.cs index 1c90707184..7dcaa4e103 100644 --- a/src/mscorlib/src/System/Collections/CompatibleComparer.cs +++ b/src/mscorlib/src/System/Collections/CompatibleComparer.cs @@ -8,7 +8,6 @@ using System.Diagnostics.Contracts; namespace System.Collections { - [Serializable] internal class CompatibleComparer : IEqualityComparer { private IComparer _comparer; diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs index c6211dadd3..3540cca8cf 100644 --- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs +++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs @@ -20,7 +20,6 @@ namespace System.Collections.Concurrent /// </remarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))] - [Serializable] internal class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { // This implementation provides an unbounded, multi-producer multi-consumer queue diff --git a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs index 63e0d47c75..9841bdb4bb 100644 --- a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs +++ b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs @@ -18,7 +18,6 @@ using System.Diagnostics.Contracts; namespace System.Collections { /// This is a simple implementation of IDictionary that is empty and readonly. - [Serializable] internal sealed class EmptyReadOnlyDictionaryInternal : IDictionary { // Note that this class must be agile with respect to AppDomains. See its usage in diff --git a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs index e313cda0fb..e4a4acf74e 100644 --- a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs +++ b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs @@ -368,7 +368,6 @@ namespace System.Collections.Generic } } - [Serializable()] internal class GenericArraySortHelper<T> : IArraySortHelper<T> where T : IComparable<T> diff --git a/src/mscorlib/src/System/Collections/Generic/Comparer.cs b/src/mscorlib/src/System/Collections/Generic/Comparer.cs index a9b4b3f0dd..e163faa80f 100644 --- a/src/mscorlib/src/System/Collections/Generic/Comparer.cs +++ b/src/mscorlib/src/System/Collections/Generic/Comparer.cs @@ -51,7 +51,6 @@ namespace System.Collections.Generic // reasons. Adding another base class (even one with no fields) // means another generic instantiation, which can be costly esp. // for value types. - [Serializable] internal sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T> { @@ -112,7 +111,6 @@ namespace System.Collections.Generic GetType().GetHashCode(); } - [Serializable] internal sealed class ComparisonComparer<T> : Comparer<T> { private readonly Comparison<T> _comparison; @@ -133,7 +131,6 @@ namespace System.Collections.Generic // and have a SerializationInfo/StreamingContext ctor, // since we want to serialize as ObjectComparer for // back-compat reasons (see below). - [Serializable] internal sealed class Int32EnumComparer<T> : Comparer<T>, ISerializable where T : struct { diff --git a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs index e360eef897..cd33428ca1 100644 --- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs +++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs @@ -17,29 +17,6 @@ ** thread safety. If a reader writer lock is available, then that may be used ** with a Dictionary to get the same thread safety guarantee. ** -** Reader writer locks don't exist in silverlight, so we do the following as a -** result of removing non-generic collections from silverlight: -** 1. If the Hashtable was fully synchronized, then we replace it with a -** Dictionary with full locks around reads/writes (same thread safety -** guarantee). -** 2. Otherwise, the Hashtable has the default MR/SW thread safety behavior, -** so we do one of the following on a case-by-case basis: -** a. If the race condition can be addressed by rearranging the code and using a temp -** variable (for example, it's only populated immediately after created) -** then we address the race condition this way and use Dictionary. -** b. If there's concern about degrading performance with the increased -** locking, we ifdef with FEATURE_NONGENERIC_COLLECTIONS so we can at -** least use Hashtable in the desktop build, but Dictionary with full -** locks in silverlight builds. Note that this is heavier locking than -** MR/SW, but this is the only option without rewriting (or adding back) -** the reader writer lock. -** c. If there's no performance concern (e.g. debug-only code) we -** consistently replace Hashtable with Dictionary plus full locks to -** reduce complexity. -** d. Most of serialization is dead code in silverlight. Instead of updating -** those Hashtable occurences in serialization, we carved out references -** to serialization such that this code doesn't need to build in -** silverlight. ===========================================================*/ namespace System.Collections.Generic @@ -706,22 +683,6 @@ namespace System.Collections.Generic value = default(TValue); return false; } - - // Method similar to TryGetValue that returns the value instead of putting it in an out param. - public TValue GetValueOrDefault(TKey key) => GetValueOrDefault(key, default(TValue)); - - // Method similar to TryGetValue that returns the value instead of putting it in an out param. If the entry - // doesn't exist, returns the defaultValue instead. - public TValue GetValueOrDefault(TKey key, TValue defaultValue) - { - int i = FindEntry(key); - if (i >= 0) - { - return entries[i].value; - } - return defaultValue; - } - public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None); bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly @@ -947,7 +908,6 @@ namespace System.Collections.Generic } } - [Serializable] public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { @@ -1076,7 +1036,6 @@ namespace System.Collections.Generic [DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] - [Serializable] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private Dictionary<TKey, TValue> dictionary; @@ -1227,7 +1186,6 @@ namespace System.Collections.Generic get { return ((ICollection)dictionary).SyncRoot; } } - [Serializable] public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; @@ -1306,7 +1264,6 @@ namespace System.Collections.Generic [DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] - [Serializable] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private Dictionary<TKey, TValue> dictionary; @@ -1455,7 +1412,6 @@ namespace System.Collections.Generic get { return ((ICollection)dictionary).SyncRoot; } } - [Serializable] public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; diff --git a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs index 0cd1bc1c12..d6b213c9d7 100644 --- a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs +++ b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs @@ -10,6 +10,7 @@ using System.Security; using System.Globalization; using System.Runtime; using System.Runtime.CompilerServices; +using System.Runtime.Serialization; using System.Diagnostics.Contracts; namespace System.Collections.Generic @@ -352,7 +353,7 @@ namespace System.Collections.Generic } [Serializable] - internal class EnumEqualityComparer<T> : EqualityComparer<T> where T : struct + internal class EnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct { [Pure] public override bool Equals(T x, T y) @@ -371,6 +372,9 @@ namespace System.Collections.Generic public EnumEqualityComparer() { } + // This is used by the serialization engine. + protected EnumEqualityComparer(SerializationInfo information, StreamingContext context) { } + // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); @@ -401,6 +405,14 @@ namespace System.Collections.Generic } return -1; } + + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + // For back-compat we need to serialize the comparers for enums with underlying types other than int as ObjectEqualityComparer + if (Type.GetTypeCode(Enum.GetUnderlyingType(typeof(T))) != TypeCode.Int32) { + info.SetType(typeof(ObjectEqualityComparer<T>)); + } + } } [Serializable] @@ -408,6 +420,9 @@ namespace System.Collections.Generic { public SByteEnumEqualityComparer() { } + // This is used by the serialization engine. + public SByteEnumEqualityComparer(SerializationInfo information, StreamingContext context) { } + [Pure] public override int GetHashCode(T obj) { @@ -417,10 +432,13 @@ namespace System.Collections.Generic } [Serializable] - internal sealed class ShortEnumEqualityComparer<T> : EnumEqualityComparer<T> where T : struct + internal sealed class ShortEnumEqualityComparer<T> : EnumEqualityComparer<T>, ISerializable where T : struct { public ShortEnumEqualityComparer() { } + // This is used by the serialization engine. + public ShortEnumEqualityComparer(SerializationInfo information, StreamingContext context) { } + [Pure] public override int GetHashCode(T obj) { @@ -430,7 +448,7 @@ namespace System.Collections.Generic } [Serializable] - internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T> where T : struct + internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct { [Pure] public override bool Equals(T x, T y) @@ -479,5 +497,15 @@ namespace System.Collections.Generic } return -1; } + + // This is used by the serialization engine. + public LongEnumEqualityComparer(SerializationInfo information, StreamingContext context) { } + + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + // The LongEnumEqualityComparer does not exist on 4.0 so we need to serialize this comparer as ObjectEqualityComparer + // to allow for roundtrip between 4.0 and 4.5. + info.SetType(typeof(ObjectEqualityComparer<T>)); + } } } diff --git a/src/mscorlib/src/System/Collections/Generic/List.cs b/src/mscorlib/src/System/Collections/Generic/List.cs index 4e480885ef..94e794cfd2 100644 --- a/src/mscorlib/src/System/Collections/Generic/List.cs +++ b/src/mscorlib/src/System/Collections/Generic/List.cs @@ -1254,7 +1254,6 @@ namespace System.Collections.Generic } } - [Serializable] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private List<T> list; diff --git a/src/mscorlib/src/System/Collections/Hashtable.cs b/src/mscorlib/src/System/Collections/Hashtable.cs index e2fd57ea4d..0c89632828 100644 --- a/src/mscorlib/src/System/Collections/Hashtable.cs +++ b/src/mscorlib/src/System/Collections/Hashtable.cs @@ -66,7 +66,6 @@ namespace System.Collections // [DebuggerTypeProxy(typeof(System.Collections.Hashtable.HashtableDebugView))] [DebuggerDisplay("Count = {Count}")] - [Serializable] internal class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable { /* @@ -919,58 +918,7 @@ namespace System.Collections public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); - // This is imperfect - it only works well if all other writes are - // also using our synchronized wrapper. But it's still a good idea. - lock (SyncRoot) - { - // This method hasn't been fully tweaked to be safe for a concurrent writer. - int oldVersion = version; - info.AddValue(LoadFactorName, loadFactor); - info.AddValue(VersionName, version); - - // - // We need to maintain serialization compatibility with Everett and RTM. - // If the comparer is null or a compatible comparer, serialize Hashtable - // in a format that can be deserialized on Everett and RTM. - // -#pragma warning disable 618 - IEqualityComparer keyComparerForSerilization = _keycomparer; - - if (keyComparerForSerilization == null) - { - info.AddValue(ComparerName, null, typeof(IComparer)); - info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider)); - } - else if (keyComparerForSerilization is CompatibleComparer) - { - CompatibleComparer c = keyComparerForSerilization as CompatibleComparer; - info.AddValue(ComparerName, c.Comparer, typeof(IComparer)); - info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider)); - } - else - { - info.AddValue(KeyComparerName, keyComparerForSerilization, typeof(IEqualityComparer)); - } -#pragma warning restore 618 - - info.AddValue(HashSizeName, buckets.Length); //This is the length of the bucket array. - Object[] serKeys = new Object[count]; - Object[] serValues = new Object[count]; - CopyKeys(serKeys, 0); - CopyValues(serValues, 0); - info.AddValue(KeysName, serKeys, typeof(Object[])); - info.AddValue(ValuesName, serValues, typeof(Object[])); - - // Explicitly check to see if anyone changed the Hashtable while we - // were serializing it. That's a race condition in their code. - if (version != oldVersion) - throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); - } + throw new PlatformNotSupportedException(); } // @@ -1073,7 +1021,6 @@ namespace System.Collections // Implements a Collection for the keys of a hashtable. An instance of this // class is created by the GetKeys method of a hashtable. - [Serializable] private class KeyCollection : ICollection { private Hashtable _hashtable; @@ -1120,7 +1067,6 @@ namespace System.Collections // Implements a Collection for the values of a hashtable. An instance of // this class is created by the GetValues method of a hashtable. - [Serializable] private class ValueCollection : ICollection { private Hashtable _hashtable; @@ -1166,7 +1112,6 @@ namespace System.Collections } // Synchronized wrapper for hashtable - [Serializable] private class SyncHashtable : Hashtable, IEnumerable { protected Hashtable _table; @@ -1189,17 +1134,7 @@ namespace System.Collections ==============================================================================*/ public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); - // Our serialization code hasn't been fully tweaked to be safe - // for a concurrent writer. - lock (_table.SyncRoot) - { - info.AddValue("ParentTable", _table, typeof(Hashtable)); - } + throw new PlatformNotSupportedException(); } public override int Count @@ -1339,7 +1274,7 @@ namespace System.Collections ==============================================================================*/ public override void OnDeserialization(Object sender) { - return; + throw new PlatformNotSupportedException(); } } @@ -1347,7 +1282,6 @@ namespace System.Collections // Implements an enumerator for a hashtable. The enumerator uses the // internal version number of the hashtabke to ensure that no modifications // are made to the hashtable while an enumeration is in progress. - [Serializable] private class HashtableEnumerator : IDictionaryEnumerator, ICloneable { private Hashtable hashtable; diff --git a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs index ebf86cdc58..3fd0cf8c6c 100644 --- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs +++ b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs @@ -19,7 +19,6 @@ using System.Diagnostics.Contracts; namespace System.Collections.ObjectModel { - [Serializable] [DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] internal class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> @@ -365,7 +364,6 @@ namespace System.Collections.ObjectModel } } - [Serializable] private struct DictionaryEnumerator : IDictionaryEnumerator { private readonly IDictionary<TKey, TValue> m_dictionary; @@ -432,7 +430,6 @@ namespace System.Collections.ObjectModel [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] - [Serializable] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private readonly ICollection<TKey> m_collection; @@ -543,7 +540,6 @@ namespace System.Collections.ObjectModel [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] - [Serializable] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private readonly ICollection<TValue> m_collection; diff --git a/src/mscorlib/src/System/Currency.cs b/src/mscorlib/src/System/Currency.cs index 13ec1b0c4e..4b735bbfe3 100644 --- a/src/mscorlib/src/System/Currency.cs +++ b/src/mscorlib/src/System/Currency.cs @@ -10,7 +10,6 @@ using System.Runtime.Versioning; namespace System { - [Serializable] internal struct Currency { internal long m_value; diff --git a/src/mscorlib/src/System/Delegate.cs b/src/mscorlib/src/System/Delegate.cs index 75ec57a003..8a9763694b 100644 --- a/src/mscorlib/src/System/Delegate.cs +++ b/src/mscorlib/src/System/Delegate.cs @@ -15,7 +15,6 @@ namespace System using System.Diagnostics; using System.Diagnostics.Contracts; - [Serializable] [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Delegate : ICloneable, ISerializable @@ -545,8 +544,9 @@ namespace System public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - throw new NotSupportedException(); + throw new PlatformNotSupportedException(); } + // // internal implementation details (FCALLS and utilities) // diff --git a/src/mscorlib/src/System/DelegateSerializationHolder.cs b/src/mscorlib/src/System/DelegateSerializationHolder.cs deleted file mode 100644 index d7ad827673..0000000000 --- a/src/mscorlib/src/System/DelegateSerializationHolder.cs +++ /dev/null @@ -1,287 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - - -using System; -using System.Reflection; -using System.Runtime.Remoting; -using System.Runtime.Serialization; -using System.Globalization; -using System.Diagnostics.Contracts; - -namespace System -{ - [Serializable] - internal sealed class DelegateSerializationHolder : IObjectReference, ISerializable - { - #region Static Members - internal static DelegateEntry GetDelegateSerializationInfo( - SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex) - { - // Used for MulticastDelegate - - if (method == null) - throw new ArgumentNullException(nameof(method)); - Contract.EndContractBlock(); - - Type c = delegateType.BaseType; - - if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate))) - throw new ArgumentException(SR.Arg_MustBeDelegate, "type"); - - if (method.DeclaringType == null) - throw new NotSupportedException(SR.NotSupported_GlobalMethodSerialization); - - DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target, - method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name); - - if (info.MemberCount == 0) - { - info.SetType(typeof(DelegateSerializationHolder)); - info.AddValue("Delegate", de, typeof(DelegateEntry)); - } - - // target can be an object so it needs to be added to the info, or else a fixup is needed - // when deserializing, and the fixup will occur too late. If it is added directly to the - // info then the rules of deserialization will guarantee that it will be available when - // needed - - if (target != null) - { - String targetName = "target" + targetIndex; - info.AddValue(targetName, de.target); - de.target = targetName; - } - - // Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the - // first parameter and delegates over generic methods) we need to send a deal more information than previously. We can - // get this by serializing the target MethodInfo. We still need to send the same information as before though (the - // DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an - // ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an - // order of deserialization guarantee otherwise. - String methodInfoName = "method" + targetIndex; - info.AddValue(methodInfoName, method); - - return de; - } - #endregion - - #region Definitions - [Serializable] - internal class DelegateEntry - { - #region Internal Data Members - internal String type; - internal String assembly; - internal Object target; - internal String targetTypeAssembly; - internal String targetTypeName; - internal String methodName; - internal DelegateEntry delegateEntry; - #endregion - - #region Constructor - internal DelegateEntry( - String type, String assembly, Object target, String targetTypeAssembly, String targetTypeName, String methodName) - { - this.type = type; - this.assembly = assembly; - this.target = target; - this.targetTypeAssembly = targetTypeAssembly; - this.targetTypeName = targetTypeName; - this.methodName = methodName; - } - #endregion - - #region Internal Members - internal DelegateEntry Entry - { - get { return delegateEntry; } - set { delegateEntry = value; } - } - #endregion - } - - #endregion - - #region Private Data Members - private DelegateEntry m_delegateEntry; - private MethodInfo[] m_methods; - #endregion - - #region Constructor - private DelegateSerializationHolder(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - bool bNewWire = true; - - try - { - m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry)); - } - catch - { - // Old wire format - m_delegateEntry = OldDelegateWireFormat(info, context); - bNewWire = false; - } - - if (bNewWire) - { - // retrieve the targets - DelegateEntry deiter = m_delegateEntry; - int count = 0; - while (deiter != null) - { - if (deiter.target != null) - { - string stringTarget = deiter.target as string; //need test to pass older wire format - if (stringTarget != null) - deiter.target = info.GetValue(stringTarget, typeof(Object)); - } - count++; - deiter = deiter.delegateEntry; - } - - // If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack - // them into an ordered array if present. - MethodInfo[] methods = new MethodInfo[count]; - int i; - for (i = 0; i < count; i++) - { - String methodInfoName = "method" + i; - methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo)); - if (methods[i] == null) - break; - } - - // If we got the info then make the array available for deserialization. - if (i == count) - m_methods = methods; - } - } - #endregion - - #region Private Members - private void ThrowInsufficientState(string field) - { - throw new SerializationException( - SR.Format(SR.Serialization_InsufficientDeserializationState, field)); - } - - private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - String delegateType = info.GetString("DelegateType"); - String delegateAssembly = info.GetString("DelegateAssembly"); - Object target = info.GetValue("Target", typeof(Object)); - String targetTypeAssembly = info.GetString("TargetTypeAssembly"); - String targetTypeName = info.GetString("TargetTypeName"); - String methodName = info.GetString("MethodName"); - - return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName); - } - - private Delegate GetDelegate(DelegateEntry de, int index) - { - Delegate d; - - try - { - if (de.methodName == null || de.methodName.Length == 0) - ThrowInsufficientState("MethodName"); - - if (de.assembly == null || de.assembly.Length == 0) - ThrowInsufficientState("DelegateAssembly"); - - if (de.targetTypeName == null || de.targetTypeName.Length == 0) - ThrowInsufficientState("TargetTypeName"); - - // We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load. - RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type); - - // {de.targetTypeAssembly, de.targetTypeName} do not actually refer to the type of the target, but the reflected - // type of the method. Those types may be the same when the method is on the target's type or on a type in its - // inheritance chain, but those types may not be the same when the method is an extension method for the - // target's type or a type in its inheritance chain. - - // If we received the new style delegate encoding we already have the target MethodInfo in hand. - if (m_methods != null) - { - // The method info is serialized, so the target type info is redundant. The desktop framework does no - // additional verification on the target type info. - d = Delegate.CreateDelegateNoSecurityCheck(type, de.target, m_methods[index]); - } - else - { - if (de.target != null) - { - // For consistency with the desktop framework, when the method info is not serialized for a closed - // delegate, the method is assumed to be on the target's type or in its inheritance chain. An extension - // method would not work on this path for the above reason and also because the delegate binds to - // instance methods only. The desktop framework does no additional verification on the target type info. - d = Delegate.CreateDelegate(type, de.target, de.methodName); - } - else - { - RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName); - d = Delegate.CreateDelegate(type, targetType, de.methodName); - } - } - } - catch (Exception e) - { - if (e is SerializationException) - throw e; - - throw new SerializationException(e.Message, e); - } - - return d; - } - #endregion - - #region IObjectReference - public Object GetRealObject(StreamingContext context) - { - int count = 0; - for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry) - count++; - - int maxindex = count - 1; - - if (count == 1) - { - return GetDelegate(m_delegateEntry, 0); - } - else - { - object[] invocationList = new object[count]; - - for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry) - { - // Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to - // the order we process the entries: we're actually looking at them in reverse order. - --count; - invocationList[count] = GetDelegate(de, maxindex - count); - } - return ((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length); - } - } - #endregion - - #region ISerializable - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - throw new NotSupportedException(SR.NotSupported_DelegateSerHolderSerial); - } - #endregion - } -} diff --git a/src/mscorlib/src/System/Diagnostics/AssertFilter.cs b/src/mscorlib/src/System/Diagnostics/AssertFilter.cs index 7c861de58e..39ce93ff51 100644 --- a/src/mscorlib/src/System/Diagnostics/AssertFilter.cs +++ b/src/mscorlib/src/System/Diagnostics/AssertFilter.cs @@ -15,7 +15,6 @@ namespace System.Diagnostics // // The default filter brings up a simple Win32 dialog with 3 buttons. - [Serializable] abstract internal class AssertFilter { // Called when an assert fails. This should be overridden with logic which diff --git a/src/mscorlib/src/System/Diagnostics/AssertFilters.cs b/src/mscorlib/src/System/Diagnostics/AssertFilters.cs index 0f34b41dba..a97e8839ae 100644 --- a/src/mscorlib/src/System/Diagnostics/AssertFilters.cs +++ b/src/mscorlib/src/System/Diagnostics/AssertFilters.cs @@ -16,7 +16,6 @@ using System; namespace System.Diagnostics { - [Serializable] internal enum AssertFilters { FailDebug = 0, diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs index 09d1e6baca..d29b860bd1 100644 --- a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs +++ b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs @@ -186,7 +186,6 @@ namespace System.Diagnostics.Contracts } } - [Serializable] [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] internal sealed class ContractException : Exception { @@ -218,21 +217,9 @@ namespace System.Diagnostics.Contracts _Condition = condition; } - private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) - : base(info, context) - { - _Kind = (ContractFailureKind)info.GetInt32("Kind"); - _UserMessage = info.GetString("UserMessage"); - _Condition = info.GetString("Condition"); - } - public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); - - info.AddValue("Kind", _Kind); - info.AddValue("UserMessage", _UserMessage); - info.AddValue("Condition", _Condition); } } } diff --git a/src/mscorlib/src/System/Diagnostics/Debugger.cs b/src/mscorlib/src/System/Diagnostics/Debugger.cs index 92df7e7f5f..cda3c4e729 100644 --- a/src/mscorlib/src/System/Diagnostics/Debugger.cs +++ b/src/mscorlib/src/System/Diagnostics/Debugger.cs @@ -5,101 +5,63 @@ // The Debugger class is a part of the System.Diagnostics package // and is used for communicating with a debugger. -using System; -using System.IO; -using System.Collections; -using System.Reflection; using System.Runtime.CompilerServices; -using System.Security; -using System.Runtime.Versioning; namespace System.Diagnostics { - // No data, does not need to be marked with the serializable attribute - public sealed class Debugger + public static class Debugger { - // This should have been a static class, but wasn't as of v3.5. Clearly, this is - // broken. We'll keep this in V4 for binary compat, but marked obsolete as error - // so migrated source code gets fixed. - [Obsolete("Do not create instances of the Debugger class. Call the static methods directly on this type instead", true)] - public Debugger() - { - // Should not have been instantiable - here for binary compatibility in V4. - } - // Break causes a breakpoint to be signalled to an attached debugger. If no debugger - // is attached, the user is asked if he wants to attach a debugger. If yes, then the + // is attached, the user is asked if he wants to attach a debugger. If yes, then the // debugger is launched. - [MethodImplAttribute(MethodImplOptions.NoInlining)] - public static void Break() - { - // Causing a break is now allowed. - BreakInternal(); - } + [MethodImpl(MethodImplOptions.NoInlining)] + public static void Break() => BreakInternal(); - private static void BreakCanThrow() - { - BreakInternal(); - } + // The VM depends on this private method. + private static void BreakCanThrow() => BreakInternal(); - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] private static extern void BreakInternal(); // Launch launches & attaches a debugger to the process. If a debugger is already attached, - // nothing happens. + // nothing happens. // - public static bool Launch() - { - if (Debugger.IsAttached) - return (true); - - // Causing the debugger to launch is now allowed. - return (LaunchInternal()); - } + public static bool Launch() => IsAttached ? true : LaunchInternal(); // This class implements code:ICustomDebuggerNotification and provides a type to be used to notify - // the debugger that execution is about to enter a path that involves a cross-thread dependency. - // See code:NotifyOfCrossThreadDependency for more details. - private class CrossThreadDependencyNotification : ICustomDebuggerNotification - { - // constructor - public CrossThreadDependencyNotification() - { - } - } - - // Do not inline the slow path - [MethodImplAttribute(MethodImplOptions.NoInlining)] - private static void NotifyOfCrossThreadDependencySlow() - { - CrossThreadDependencyNotification notification = new CrossThreadDependencyNotification(); - CustomNotification(notification); - } - - // Sends a notification to the debugger to indicate that execution is about to enter a path - // involving a cross thread dependency. A debugger that has opted into this type of notification - // can take appropriate action on receipt. For example, performing a funceval normally requires - // freezing all threads but the one performing the funceval. If the funceval requires execution on - // more than one thread, as might occur in remoting scenarios, the funceval will block. This - // notification will apprise the debugger that it will need to slip a thread or abort the funceval - // in such a situation. The notification is subject to collection after this function returns. - // + // the debugger that execution is about to enter a path that involves a cross-thread dependency. + // See code:NotifyOfCrossThreadDependency for more details. + private class CrossThreadDependencyNotification : ICustomDebuggerNotification { } + + // Do not inline the slow path + [MethodImpl(MethodImplOptions.NoInlining)] + private static void NotifyOfCrossThreadDependencySlow() => + CustomNotification(new CrossThreadDependencyNotification()); + + // Sends a notification to the debugger to indicate that execution is about to enter a path + // involving a cross thread dependency. A debugger that has opted into this type of notification + // can take appropriate action on receipt. For example, performing a funceval normally requires + // freezing all threads but the one performing the funceval. If the funceval requires execution on + // more than one thread, as might occur in remoting scenarios, the funceval will block. This + // notification will apprise the debugger that it will need to slip a thread or abort the funceval + // in such a situation. The notification is subject to collection after this function returns. + // public static void NotifyOfCrossThreadDependency() { - if (Debugger.IsAttached) + if (IsAttached) { NotifyOfCrossThreadDependencySlow(); } } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool LaunchInternal(); // Returns whether or not a debugger is attached to the process. // public static extern bool IsAttached { - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] get; } @@ -108,26 +70,26 @@ namespace System.Diagnostics // An attached debugger can enable or disable which messages will // actually be reported to the user through the COM+ debugger // services API. This info is communicated to the runtime so only - // desired events are actually reported to the debugger. + // desired events are actually reported to the debugger. // // Constant representing the default category - public static readonly String DefaultCategory = null; + public static readonly string DefaultCategory = null; // Posts a message for the attached debugger. If there is no // debugger attached, has no effect. The debugger may or may not - // report the message depending on its settings. - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern void Log(int level, String category, String message); + // report the message depending on its settings. + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Log(int level, string category, string message); // Checks to see if an attached debugger has logging enabled - // - [MethodImplAttribute(MethodImplOptions.InternalCall)] + // + [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool IsLogging(); // Posts a custom notification for the attached debugger. If there is no // debugger attached, has no effect. The debugger may or may not - // report the notification depending on its settings. - [MethodImplAttribute(MethodImplOptions.InternalCall)] + // report the notification depending on its settings. + [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CustomNotification(ICustomDebuggerNotification data); } } diff --git a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs index 5e1dfd82a5..34e65bcb3e 100644 --- a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs +++ b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs @@ -18,21 +18,18 @@ using System.Diagnostics.Contracts; namespace System.Diagnostics { - [Serializable] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] public sealed class DebuggerStepThroughAttribute : Attribute { public DebuggerStepThroughAttribute() { } } - [Serializable] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)] public sealed class DebuggerHiddenAttribute : Attribute { public DebuggerHiddenAttribute() { } } - [Serializable] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)] public sealed class DebuggerNonUserCodeAttribute : Attribute { diff --git a/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs b/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs index 8ad4fec082..6b8c150ab8 100644 --- a/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs +++ b/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs @@ -16,7 +16,6 @@ using System; namespace System.Diagnostics { - [Serializable] internal sealed class EditAndContinueHelper { #pragma warning disable 169 diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs new file mode 100644 index 0000000000..2f6fdf62ef --- /dev/null +++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs @@ -0,0 +1,175 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; +using Microsoft.Win32; + +namespace System.Diagnostics.Tracing +{ + [StructLayout(LayoutKind.Sequential)] + internal struct EventPipeProviderConfiguration + { + [MarshalAs(UnmanagedType.LPWStr)] + private string m_providerName; + private UInt64 m_keywords; + private uint m_loggingLevel; + + internal EventPipeProviderConfiguration( + string providerName, + UInt64 keywords, + uint loggingLevel) + { + if(string.IsNullOrEmpty(providerName)) + { + throw new ArgumentNullException(nameof(providerName)); + } + if(loggingLevel > 5) // 5 == Verbose, the highest value in EventPipeLoggingLevel. + { + throw new ArgumentOutOfRangeException(nameof(loggingLevel)); + } + m_providerName = providerName; + m_keywords = keywords; + m_loggingLevel = loggingLevel; + } + + internal string ProviderName + { + get { return m_providerName; } + } + + internal UInt64 Keywords + { + get { return m_keywords; } + } + + internal uint LoggingLevel + { + get { return m_loggingLevel; } + } + } + + internal sealed class EventPipeConfiguration + { + private string m_outputFile; + private uint m_circularBufferSizeInMB; + private List<EventPipeProviderConfiguration> m_providers; + private TimeSpan m_minTimeBetweenSamples = TimeSpan.FromMilliseconds(1); + + internal EventPipeConfiguration( + string outputFile, + uint circularBufferSizeInMB) + { + if(string.IsNullOrEmpty(outputFile)) + { + throw new ArgumentNullException(nameof(outputFile)); + } + if(circularBufferSizeInMB == 0) + { + throw new ArgumentOutOfRangeException(nameof(circularBufferSizeInMB)); + } + m_outputFile = outputFile; + m_circularBufferSizeInMB = circularBufferSizeInMB; + m_providers = new List<EventPipeProviderConfiguration>(); + } + + internal string OutputFile + { + get { return m_outputFile; } + } + + internal uint CircularBufferSizeInMB + { + get { return m_circularBufferSizeInMB; } + } + + internal EventPipeProviderConfiguration[] Providers + { + get { return m_providers.ToArray(); } + } + + internal long ProfilerSamplingRateInNanoseconds + { + // 100 nanoseconds == 1 tick. + get { return m_minTimeBetweenSamples.Ticks * 100; } + } + + internal void EnableProvider(string providerName, UInt64 keywords, uint loggingLevel) + { + m_providers.Add(new EventPipeProviderConfiguration( + providerName, + keywords, + loggingLevel)); + } + + internal void SetProfilerSamplingRate(TimeSpan minTimeBetweenSamples) + { + if(minTimeBetweenSamples.Ticks <= 0) + { + throw new ArgumentOutOfRangeException(nameof(minTimeBetweenSamples)); + } + + m_minTimeBetweenSamples = minTimeBetweenSamples; + } + } + + internal static class EventPipe + { + internal static void Enable(EventPipeConfiguration configuration) + { + if(configuration == null) + { + throw new ArgumentNullException(nameof(configuration)); + } + + EventPipeProviderConfiguration[] providers = configuration.Providers; + + EventPipeInternal.Enable( + configuration.OutputFile, + configuration.CircularBufferSizeInMB, + configuration.ProfilerSamplingRateInNanoseconds, + providers, + providers.Length); + } + + internal static void Disable() + { + EventPipeInternal.Disable(); + } + } + + internal static class EventPipeInternal + { + // + // These PInvokes are used by the configuration APIs to interact with EventPipe. + // + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + internal static extern void Enable(string outputFile, uint circularBufferSizeInMB, long profilerSamplingRateInNanoseconds, EventPipeProviderConfiguration[] providers, int numProviders); + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + internal static extern void Disable(); + + // + // These PInvokes are used by EventSource to interact with the EventPipe. + // + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + internal static extern IntPtr CreateProvider(Guid providerID, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback callbackFunc); + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + internal static extern unsafe IntPtr DefineEvent(IntPtr provHandle, uint eventID, Int64 keywords, uint eventVersion, uint level, void *pMetadata, uint metadataLength); + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + internal static extern void DeleteProvider(IntPtr provHandle); + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + internal static extern unsafe void WriteEvent(IntPtr eventHandle, uint eventID, void* pData, uint length, Guid* activityId, Guid* relatedActivityId); + } +} diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs new file mode 100644 index 0000000000..d5bc4c2889 --- /dev/null +++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs @@ -0,0 +1,116 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; +using Microsoft.Win32; +using System.Diagnostics; +using System.Collections.Generic; + +namespace System.Diagnostics.Tracing +{ + internal sealed class EventPipeEventProvider : IEventProvider + { + // The EventPipeProvider handle. + private IntPtr m_provHandle = IntPtr.Zero; + + // Register an event provider. + unsafe uint IEventProvider.EventRegister( + ref Guid providerId, + UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback, + void* callbackContext, + ref long registrationHandle) + { + uint returnStatus = 0; + m_provHandle = EventPipeInternal.CreateProvider(providerId, enableCallback); + if(m_provHandle != IntPtr.Zero) + { + // Fixed registration handle because a new EventPipeEventProvider + // will be created for each new EventSource. + registrationHandle = 1; + } + else + { + // Unable to create the provider. + returnStatus = 1; + } + + return returnStatus; + } + + // Unregister an event provider. + uint IEventProvider.EventUnregister(long registrationHandle) + { + EventPipeInternal.DeleteProvider(m_provHandle); + return 0; + } + + // Write an event. + unsafe int IEventProvider.EventWriteTransferWrapper( + long registrationHandle, + ref EventDescriptor eventDescriptor, + IntPtr eventHandle, + Guid* activityId, + Guid* relatedActivityId, + int userDataCount, + EventProvider.EventData* userData) + { + uint eventID = (uint)eventDescriptor.EventId; + if(eventID != 0 && eventHandle != IntPtr.Zero) + { + if (userDataCount == 0) + { + EventPipeInternal.WriteEvent(eventHandle, eventID, null, 0, activityId, relatedActivityId); + return 0; + } + + uint length = 0; + for (int i = 0; i < userDataCount; i++) + { + length += userData[i].Size; + } + + byte[] data = new byte[length]; + fixed (byte *pData = data) + { + uint offset = 0; + for (int i = 0; i < userDataCount; i++) + { + byte * singleUserDataPtr = (byte *)(userData[i].Ptr); + uint singleUserDataSize = userData[i].Size; + WriteToBuffer(pData, length, ref offset, singleUserDataPtr, singleUserDataSize); + } + EventPipeInternal.WriteEvent(eventHandle, eventID, pData, length, activityId, relatedActivityId); + } + } + return 0; + } + + // Get or set the per-thread activity ID. + int IEventProvider.EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.ActivityControl ControlCode, ref Guid ActivityId) + { + return 0; + } + + // Define an EventPipeEvent handle. + unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength) + { + IntPtr eventHandlePtr = EventPipeInternal.DefineEvent(m_provHandle, eventID, keywords, eventVersion, level, pMetadata, metadataLength); + return eventHandlePtr; + } + + // Copy src to buffer and modify the offset. + // Note: We know the buffer size ahead of time to make sure no buffer overflow. + private static unsafe void WriteToBuffer(byte *buffer, uint bufferLength, ref uint offset, byte *src, uint srcLength) + { + Debug.Assert(bufferLength >= (offset + srcLength)); + for (int i = 0; i < srcLength; i++) + { + *(byte *)(buffer + offset + i) = *(byte *)(src + i); + } + offset += srcLength; + } + } +} diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs index b691dd38b9..01aac72cf6 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs @@ -11,6 +11,13 @@ namespace System.Diagnostics.Tracing { public partial class EventSource { +#if FEATURE_MANAGED_ETW && FEATURE_PERFTRACING + // For non-Windows, we use a thread-local variable to hold the activity ID. + // On Windows, ETW has it's own thread-local variable and we participate in its use. + [ThreadStatic] + private static Guid s_currentThreadActivityId; +#endif // FEATURE_MANAGED_ETW && FEATURE_PERFTRACING + // ActivityID support (see also WriteEventWithRelatedActivityIdCore) /// <summary> /// When a thread starts work that is on behalf of 'something else' (typically another @@ -40,9 +47,13 @@ namespace System.Diagnostics.Tracing // We ignore errors to keep with the convention that EventSources do not throw errors. // Note we can't access m_throwOnWrites because this is a static method. +#if FEATURE_PERFTRACING + s_currentThreadActivityId = activityId; +#elif PLATFORM_WINDOWS if (UnsafeNativeMethods.ManifestEtw.EventActivityIdControl( UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref activityId) == 0) +#endif // FEATURE_PERFTRACING { #if FEATURE_ACTIVITYSAMPLING var activityDying = s_activityDying; @@ -86,9 +97,14 @@ namespace System.Diagnostics.Tracing // We ignore errors to keep with the convention that EventSources do not throw errors. // Note we can't access m_throwOnWrites because this is a static method. +#if FEATURE_PERFTRACING + oldActivityThatWillContinue = s_currentThreadActivityId; + s_currentThreadActivityId = activityId; +#elif PLATFORM_WINDOWS UnsafeNativeMethods.ManifestEtw.EventActivityIdControl( UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref oldActivityThatWillContinue); +#endif // FEATURE_PERFTRACING #endif // FEATURE_MANAGED_ETW // We don't call the activityDying callback here because the caller has declared that @@ -108,9 +124,13 @@ namespace System.Diagnostics.Tracing // errors. Note we can't access m_throwOnWrites because this is a static method. Guid retVal = new Guid(); #if FEATURE_MANAGED_ETW +#if FEATURE_PERFTRACING + retVal = s_currentThreadActivityId; +#elif PLATFORM_WINDOWS UnsafeNativeMethods.ManifestEtw.EventActivityIdControl( UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID, ref retVal); +#endif // FEATURE_PERFTRACING #endif // FEATURE_MANAGED_ETW return retVal; } diff --git a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs index 29d6a1d4e6..d3994d48b8 100644 --- a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs +++ b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs @@ -11,7 +11,6 @@ using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics { - [Serializable] internal class LogSwitch { // ! WARNING ! diff --git a/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs b/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs index 6b5ea85ee1..22d6c95a97 100644 --- a/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs +++ b/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs @@ -21,7 +21,6 @@ namespace System.Diagnostics // Constants representing the importance level of messages to be logged. // This level can be used to organize messages, and also to filter which // messages are displayed. - [Serializable] internal enum LoggingLevels { TraceLevel0 = 0, diff --git a/src/mscorlib/src/System/Diagnostics/Stackframe.cs b/src/mscorlib/src/System/Diagnostics/Stackframe.cs index b555a609e7..a6a7067af3 100644 --- a/src/mscorlib/src/System/Diagnostics/Stackframe.cs +++ b/src/mscorlib/src/System/Diagnostics/Stackframe.cs @@ -12,7 +12,6 @@ using System.Diagnostics.Contracts; namespace System.Diagnostics { // There is no good reason for the methods of this class to be virtual. - [Serializable] public class StackFrame { private MethodBase method; diff --git a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs index cdedb66ed8..6a138de327 100644 --- a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs +++ b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs @@ -22,7 +22,6 @@ namespace System.Diagnostics // Modifying the order or fields of this object may require other changes // to the unmanaged definition of the StackFrameHelper class, in // VM\DebugDebugger.h. The binder will catch some of these layout problems. - [Serializable] internal class StackFrameHelper : IDisposable { [NonSerialized] @@ -251,7 +250,6 @@ namespace System.Diagnostics // In order to ensure trusted code can trust the data it gets from a // StackTrace, we use an InheritanceDemand to prevent partially-trusted // subclasses. - [Serializable] public class StackTrace { private StackFrame[] frames; diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs index c4c1ede525..15b3c7f4f7 100644 --- a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs +++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs @@ -17,7 +17,6 @@ using System; namespace System.Diagnostics.SymbolStore { - [Serializable] internal enum SymAddressKind { // ILOffset: addr1 = IL local var or param index. diff --git a/src/mscorlib/src/System/Diagnostics/log.cs b/src/mscorlib/src/System/Diagnostics/log.cs index b62ea493e7..5ed3a3e502 100644 --- a/src/mscorlib/src/System/Diagnostics/log.cs +++ b/src/mscorlib/src/System/Diagnostics/log.cs @@ -4,7 +4,6 @@ namespace System.Diagnostics { - using System.Runtime.Remoting; using System; using System.IO; using System.Collections; @@ -20,7 +19,6 @@ namespace System.Diagnostics // NOTE: These are NOT triggered when the log switch setting is changed from the // attached debugger. // - [Serializable] internal delegate void LogSwitchLevelHandler(LogSwitch ls, LoggingLevels newLevel); diff --git a/src/mscorlib/src/System/Double.cs b/src/mscorlib/src/System/Double.cs index f2c5cec219..30fa1a58b3 100644 --- a/src/mscorlib/src/System/Double.cs +++ b/src/mscorlib/src/System/Double.cs @@ -26,7 +26,7 @@ namespace System public struct Double : IComparable, IFormattable, IConvertible , IComparable<Double>, IEquatable<Double> { - internal double m_value; + private double m_value; // Do not rename (binary serialization) // // Public Constants diff --git a/src/mscorlib/src/System/Empty.cs b/src/mscorlib/src/System/Empty.cs index 502e8dfea7..2b585b3141 100644 --- a/src/mscorlib/src/System/Empty.cs +++ b/src/mscorlib/src/System/Empty.cs @@ -9,12 +9,10 @@ using System.Diagnostics.Contracts; using System; -using System.Runtime.Remoting; using System.Runtime.Serialization; namespace System { - [Serializable] internal sealed class Empty : ISerializable { private Empty() @@ -30,12 +28,7 @@ namespace System public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); - UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.EmptyUnity, null, null); + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/Environment.cs b/src/mscorlib/src/System/Environment.cs index dddbdc242d..257deb27eb 100644 --- a/src/mscorlib/src/System/Environment.cs +++ b/src/mscorlib/src/System/Environment.cs @@ -77,9 +77,6 @@ namespace System } } - - private static volatile OperatingSystem m_os; // Cached OperatingSystem value - /*==================================TickCount=================================== **Action: Gets the number of ticks since the system was started. **Returns: The number of ticks since the system was started. diff --git a/src/mscorlib/src/System/Exception.cs b/src/mscorlib/src/System/Exception.cs index 263b6b3c65..8d01b4c461 100644 --- a/src/mscorlib/src/System/Exception.cs +++ b/src/mscorlib/src/System/Exception.cs @@ -83,8 +83,7 @@ namespace System _stackTraceString = info.GetString("StackTraceString"); _remoteStackTraceString = info.GetString("RemoteStackTraceString"); _remoteStackIndex = info.GetInt32("RemoteStackIndex"); - - _exceptionMethodString = (String)(info.GetValue("ExceptionMethod", typeof(String))); + HResult = info.GetInt32("HResult"); _source = info.GetString("Source"); @@ -293,15 +292,8 @@ namespace System { return null; } - - if (_exceptionMethodString != null) - { - _exceptionMethod = GetExceptionMethodFromString(); - } - else - { - _exceptionMethod = GetExceptionMethodFromStackTrace(); - } + + _exceptionMethod = GetExceptionMethodFromStackTrace(); return _exceptionMethod; } @@ -434,90 +426,6 @@ namespace System return s; } - private String GetExceptionMethodString() - { - MethodBase methBase = GetTargetSiteInternal(); - if (methBase == null) - { - return null; - } - if (methBase is System.Reflection.Emit.DynamicMethod.RTDynamicMethod) - { - // DynamicMethods cannot be serialized - return null; - } - - // Note that the newline separator is only a separator, chosen such that - // it won't (generally) occur in a method name. This string is used - // only for serialization of the Exception Method. - char separator = '\n'; - StringBuilder result = new StringBuilder(); - if (methBase is ConstructorInfo) - { - RuntimeConstructorInfo rci = (RuntimeConstructorInfo)methBase; - Type t = rci.ReflectedType; - result.Append((int)MemberTypes.Constructor); - result.Append(separator); - result.Append(rci.Name); - if (t != null) - { - result.Append(separator); - result.Append(t.Assembly.FullName); - result.Append(separator); - result.Append(t.FullName); - } - result.Append(separator); - result.Append(rci.ToString()); - } - else - { - Debug.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo"); - RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase; - Type t = rmi.DeclaringType; - result.Append((int)MemberTypes.Method); - result.Append(separator); - result.Append(rmi.Name); - result.Append(separator); - result.Append(rmi.Module.Assembly.FullName); - result.Append(separator); - if (t != null) - { - result.Append(t.FullName); - result.Append(separator); - } - result.Append(rmi.ToString()); - } - - return result.ToString(); - } - - private MethodBase GetExceptionMethodFromString() - { - Debug.Assert(_exceptionMethodString != null, "Method string cannot be NULL!"); - String[] args = _exceptionMethodString.Split(new char[] { '\0', '\n' }); - if (args.Length != 5) - { - throw new SerializationException(); - } - SerializationInfo si = new SerializationInfo(typeof(MemberInfoSerializationHolder), new FormatterConverter()); - si.AddValue("MemberType", (int)Int32.Parse(args[0], CultureInfo.InvariantCulture), typeof(Int32)); - si.AddValue("Name", args[1], typeof(String)); - si.AddValue("AssemblyName", args[2], typeof(String)); - si.AddValue("ClassName", args[3]); - si.AddValue("Signature", args[4]); - MethodBase result; - StreamingContext sc = new StreamingContext(StreamingContextStates.All); - try - { - result = (MethodBase)new MemberInfoSerializationHolder(si, sc).GetRealObject(sc); - } - catch (SerializationException) - { - result = null; - } - return result; - } - protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState { add { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); } @@ -559,7 +467,7 @@ namespace System info.AddValue("StackTraceString", tempStackTraceString, typeof(String)); info.AddValue("RemoteStackTraceString", _remoteStackTraceString, typeof(String)); info.AddValue("RemoteStackIndex", _remoteStackIndex, typeof(Int32)); - info.AddValue("ExceptionMethod", GetExceptionMethodString(), typeof(String)); + info.AddValue("ExceptionMethod", null, typeof(String)); info.AddValue("HResult", HResult); info.AddValue("Source", _source, typeof(String)); @@ -748,7 +656,7 @@ namespace System private String _className; //Needed for serialization. private MethodBase _exceptionMethod; //Needed for serialization. - private String _exceptionMethodString; //Needed for serialization. + private String _exceptionMethodString; //Needed for serialization. internal String _message; private IDictionary _data; private Exception _innerException; diff --git a/src/mscorlib/src/System/GC.cs b/src/mscorlib/src/System/GC.cs index aeb0ca5196..11ae8bf32e 100644 --- a/src/mscorlib/src/System/GC.cs +++ b/src/mscorlib/src/System/GC.cs @@ -28,7 +28,6 @@ using System.Diagnostics.Contracts; namespace System { - [Serializable] public enum GCCollectionMode { Default = 0, @@ -39,7 +38,6 @@ namespace System // !!!!!!!!!!!!!!!!!!!!!!! // make sure you change the def in vm\gc.h // if you change this! - [Serializable] internal enum InternalGCCollectionMode { NonBlocking = 0x00000001, @@ -51,7 +49,6 @@ namespace System // !!!!!!!!!!!!!!!!!!!!!!! // make sure you change the def in vm\gc.h // if you change this! - [Serializable] public enum GCNotificationStatus { Succeeded = 0, diff --git a/src/mscorlib/src/System/Globalization/BidiCategory.cs b/src/mscorlib/src/System/Globalization/BidiCategory.cs index f37c44b385..9d767c673b 100644 --- a/src/mscorlib/src/System/Globalization/BidiCategory.cs +++ b/src/mscorlib/src/System/Globalization/BidiCategory.cs @@ -12,7 +12,6 @@ namespace System.Globalization { - [Serializable] internal enum BidiCategory { LeftToRight = 0, diff --git a/src/mscorlib/src/System/Globalization/Calendar.cs b/src/mscorlib/src/System/Globalization/Calendar.cs index c23e1088c1..86782c1f3b 100644 --- a/src/mscorlib/src/System/Globalization/Calendar.cs +++ b/src/mscorlib/src/System/Globalization/Calendar.cs @@ -28,7 +28,6 @@ namespace System.Globalization // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar, // since most of the calendars (or all?) have the same way of calcuating hour/minute/second. - [Serializable] public abstract partial class Calendar : ICloneable { // Number of 100ns (10E-7 second) ticks per time unit diff --git a/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs b/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs index 51a2727c7d..89de24d9d7 100644 --- a/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs +++ b/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs @@ -157,20 +157,9 @@ namespace System.Globalization } } - GCHandle contextHandle = GCHandle.Alloc(data); - try - { - // Now call the enumeration API. Work is done by our callback function -#if CORECLR - Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, (IntPtr)contextHandle); -#else - IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarsCallback); - Interop.Kernel32.EnumCalendarInfoExEx(callback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, (IntPtr)contextHandle); -#endif - } - finally + unsafe { - contextHandle.Free(); + Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, Unsafe.AsPointer(ref data)); } // Copy to the output array @@ -300,15 +289,13 @@ namespace System.Globalization } // EnumCalendarInfoExEx callback itself. -#if !CORECLR - [NativeCallable(CallingConvention = CallingConvention.StdCall)] -#endif - private static unsafe Interop.BOOL EnumCalendarInfoCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr pReserved, IntPtr lParam) + // [NativeCallable(CallingConvention = CallingConvention.StdCall)] + private static unsafe Interop.BOOL EnumCalendarInfoCallback(char* lpCalendarInfoString, uint calendar, IntPtr pReserved, void* lParam) { - EnumData context = (EnumData)((GCHandle)lParam).Target; + ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam); try { - string calendarInfo = new string((char*)lpCalendarInfoString); + string calendarInfo = new string(lpCalendarInfoString); // If we had a user override, check to make sure this differs if (context.userOverride != calendarInfo) @@ -343,7 +330,7 @@ namespace System.Globalization string res = CultureData.GetLocaleInfoEx(localeName, lcType); // if it succeeded remember the override for the later callers - if (res != "") + if (res != null) { // Remember this was the override (so we can look for duplicates later in the enum function) context.userOverride = res; @@ -354,20 +341,10 @@ namespace System.Globalization } } - GCHandle contextHandle = GCHandle.Alloc(context); - try + unsafe { -#if CORECLR - Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, (IntPtr)contextHandle); -#else // Now call the enumeration API. Work is done by our callback function - IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarInfoCallback); - Interop.Kernel32.EnumCalendarInfoExEx(callback, localeName, (uint)calendar, null, calType, (IntPtr)contextHandle); -#endif // CORECLR - } - finally - { - contextHandle.Free(); + Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, Unsafe.AsPointer(ref context)); } // Now we have a list of data, fail if we didn't find anything. @@ -464,12 +441,10 @@ namespace System.Globalization public IntList calendars; // list of calendars found so far } -#if !CORECLR - [NativeCallable(CallingConvention = CallingConvention.StdCall)] -#endif - private static Interop.BOOL EnumCalendarsCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr reserved, IntPtr lParam) + // [NativeCallable(CallingConvention = CallingConvention.StdCall)] + private static unsafe Interop.BOOL EnumCalendarsCallback(char* lpCalendarInfoString, uint calendar, IntPtr reserved, void* lParam) { - EnumCalendarsData context = (EnumCalendarsData)((GCHandle)lParam).Target; + ref EnumCalendarsData context = ref Unsafe.As<byte, EnumCalendarsData>(ref *(byte*)lParam); try { // If we had a user override, check to make sure this differs diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs index d20bb9f9f3..eb4dc5613e 100644 --- a/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs +++ b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs @@ -16,7 +16,7 @@ namespace System.Globalization { _sortName = culture.SortName; - _name = culture._name; + m_name = culture._name; _sortName = culture.SortName; if (_invariantMode) @@ -199,7 +199,7 @@ namespace System.Globalization { if (matchLengthPtr != null) *matchLengthPtr = 0; - return 0; + return startIndex; } if (source.Length == 0) diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/mscorlib/src/System/Globalization/CompareInfo.cs index b2c2208db7..593e86415d 100644 --- a/src/mscorlib/src/System/Globalization/CompareInfo.cs +++ b/src/mscorlib/src/System/Globalization/CompareInfo.cs @@ -20,7 +20,6 @@ using System.Runtime.Serialization; namespace System.Globalization { [Flags] - [Serializable] public enum CompareOptions { None = 0x00000000, @@ -64,20 +63,21 @@ namespace System.Globalization // locale, which is what SCOMPAREINFO does. [OptionalField(VersionAdded = 2)] - private string _name; // The name used to construct this CompareInfo - [NonSerialized] - private string _sortName; // The name that defines our behavior + private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization) + + [NonSerialized] + private string _sortName; // The name that defines our behavior. [OptionalField(VersionAdded = 3)] - private SortVersion _sortVersion; + private SortVersion m_sortVersion; // Do not rename (binary serialization) // _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant - [NonSerialized] + [NonSerialized] private readonly bool _invariantMode = GlobalizationMode.Invariant; internal CompareInfo(CultureInfo culture) { - _name = culture._name; + m_name = culture._name; InitSort(culture); } @@ -217,7 +217,7 @@ namespace System.Globalization [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { - _name = null; + m_name = null; } void IDeserializationCallback.OnDeserialization(Object sender) @@ -233,9 +233,9 @@ namespace System.Globalization private void OnDeserialized() { - if (_name != null) + if (m_name != null) { - InitSort(CultureInfo.GetCultureInfo(_name)); + InitSort(CultureInfo.GetCultureInfo(m_name)); } } @@ -259,10 +259,10 @@ namespace System.Globalization { get { - Debug.Assert(_name != null, "CompareInfo.Name Expected _name to be set"); - if (_name == "zh-CHT" || _name == "zh-CHS") + Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set"); + if (m_name == "zh-CHT" || m_name == "zh-CHS") { - return _name; + return m_name; } return _sortName; @@ -1208,11 +1208,11 @@ namespace System.Globalization { get { - if (_sortVersion == null) + if (m_sortVersion == null) { if (_invariantMode) { - _sortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0, + m_sortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0, (byte) (CultureInfo.LOCALE_INVARIANT >> 24), (byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16), (byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8), @@ -1220,11 +1220,11 @@ namespace System.Globalization } else { - _sortVersion = GetSortVersion(); + m_sortVersion = GetSortVersion(); } } - return _sortVersion; + return m_sortVersion; } } diff --git a/src/mscorlib/src/System/Globalization/CultureData.Windows.cs b/src/mscorlib/src/System/Globalization/CultureData.Windows.cs index 6d2678b550..c39327e9e7 100644 --- a/src/mscorlib/src/System/Globalization/CultureData.Windows.cs +++ b/src/mscorlib/src/System/Globalization/CultureData.Windows.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; @@ -179,7 +180,7 @@ namespace System.Globalization return new String(pBuffer); } - return ""; + return null; } internal static unsafe int GetLocaleInfoExInt(String localeName, uint field) @@ -195,7 +196,7 @@ namespace System.Globalization { Debug.Assert(!GlobalizationMode.Invariant); - return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, (IntPtr)lpLCData, cchData); + return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, lpLCData, cchData); } private string GetLocaleInfo(LocaleStringData type) @@ -284,19 +285,9 @@ namespace System.Globalization context.cultureName = null; context.regionName = regionName; - GCHandle contextHandle = GCHandle.Alloc(context); - try + unsafe { -#if CORECLR - Interop.Kernel32.EnumSystemLocalesEx(EnumSystemLocalesProc, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, (IntPtr)contextHandle, IntPtr.Zero); -#else - IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumSystemLocalesProc); - Interop.Kernel32.EnumSystemLocalesEx(callback, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, (IntPtr)contextHandle, IntPtr.Zero); -#endif - } - finally - { - contextHandle.Free(); + Interop.Kernel32.EnumSystemLocalesEx(EnumSystemLocalesProc, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, Unsafe.AsPointer(ref context), IntPtr.Zero); } if (context.cultureName != null) @@ -543,15 +534,13 @@ namespace System.Globalization } // EnumSystemLocaleEx callback. -#if !CORECLR - [NativeCallable(CallingConvention = CallingConvention.StdCall)] -#endif - private static unsafe Interop.BOOL EnumSystemLocalesProc(IntPtr lpLocaleString, uint flags, IntPtr contextHandle) + // [NativeCallable(CallingConvention = CallingConvention.StdCall)] + private static unsafe Interop.BOOL EnumSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { - EnumLocaleData context = (EnumLocaleData)((GCHandle)contextHandle).Target; + ref EnumLocaleData context = ref Unsafe.As<byte, EnumLocaleData>(ref *(byte*)contextHandle); try { - string cultureName = new string((char*)lpLocaleString); + string cultureName = new string(lpLocaleString); string regionName = GetLocaleInfoEx(cultureName, LOCALE_SISO3166CTRYNAME); if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase)) { @@ -568,15 +557,13 @@ namespace System.Globalization } // EnumSystemLocaleEx callback. -#if !CORECLR - [NativeCallable(CallingConvention = CallingConvention.StdCall)] -#endif - private static unsafe Interop.BOOL EnumAllSystemLocalesProc(IntPtr lpLocaleString, uint flags, IntPtr contextHandle) + // [NativeCallable(CallingConvention = CallingConvention.StdCall)] + private static unsafe Interop.BOOL EnumAllSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { - EnumData context = (EnumData)((GCHandle)contextHandle).Target; + ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)contextHandle); try { - context.strings.Add(new string((char*)lpLocaleString)); + context.strings.Add(new string(lpLocaleString)); return Interop.BOOL.TRUE; } catch (Exception) @@ -592,16 +579,13 @@ namespace System.Globalization } // EnumTimeFormatsEx callback itself. -#if !CORECLR - [NativeCallable(CallingConvention = CallingConvention.StdCall)] -#endif - private static unsafe Interop.BOOL EnumTimeCallback(IntPtr lpTimeFormatString, IntPtr lParam) + // [NativeCallable(CallingConvention = CallingConvention.StdCall)] + private static unsafe Interop.BOOL EnumTimeCallback(char* lpTimeFormatString, void* lParam) { - EnumData context = (EnumData)((GCHandle)lParam).Target; - + ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam); try { - context.strings.Add(new string((char*)lpTimeFormatString)); + context.strings.Add(new string(lpTimeFormatString)); return Interop.BOOL.TRUE; } catch (Exception) @@ -617,21 +601,9 @@ namespace System.Globalization EnumData data = new EnumData(); data.strings = new StringList(); - GCHandle dataHandle = GCHandle.Alloc(data); - try - { -#if CORECLR - Interop.Kernel32.EnumTimeFormatsEx(EnumTimeCallback, localeName, (uint)dwFlags, (IntPtr)dataHandle); -#else - // Now call the enumeration API. Work is done by our callback function - IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, IntPtr, Interop.BOOL>>(EnumTimeCallback); - Interop.Kernel32.EnumTimeFormatsEx(callback, localeName, (uint)dwFlags, (IntPtr)dataHandle); -#endif - } - finally - { - dataHandle.Free(); - } + + // Now call the enumeration API. Work is done by our callback function + Interop.Kernel32.EnumTimeFormatsEx(EnumTimeCallback, localeName, (uint)dwFlags, Unsafe.AsPointer(ref data)); if (data.strings.Count > 0) { @@ -757,19 +729,10 @@ namespace System.Globalization EnumData context = new EnumData(); context.strings = new StringList(); - GCHandle contextHandle = GCHandle.Alloc(context); - try - { -#if CORECLR - Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, flags, (IntPtr)contextHandle, IntPtr.Zero); -#else - IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumAllSystemLocalesProc); - Interop.Kernel32.EnumSystemLocalesEx(callback, flags, (IntPtr)contextHandle, IntPtr.Zero); -#endif - } - finally + + unsafe { - contextHandle.Free(); + Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, flags, Unsafe.AsPointer(ref context), IntPtr.Zero); } CultureInfo [] cultures = new CultureInfo[context.strings.Count]; @@ -802,19 +765,10 @@ namespace System.Globalization { EnumData context = new EnumData(); context.strings = new StringList(); - GCHandle contextHandle = GCHandle.Alloc(context); - try - { -#if CORECLR - Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, Interop.Kernel32.LOCALE_REPLACEMENT, (IntPtr)contextHandle, IntPtr.Zero); -#else - IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumAllSystemLocalesProc); - Interop.Kernel32.EnumSystemLocalesEx(callback, Interop.Kernel32.LOCALE_REPLACEMENT, (IntPtr)contextHandle, IntPtr.Zero); -#endif - } - finally + + unsafe { - contextHandle.Free(); + Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, Interop.Kernel32.LOCALE_REPLACEMENT, Unsafe.AsPointer(ref context), IntPtr.Zero); } for (int i=0; i<context.strings.Count; i++) diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs index 60938defac..16e2d291a1 100644 --- a/src/mscorlib/src/System/Globalization/CultureInfo.cs +++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs @@ -44,7 +44,6 @@ namespace System.Globalization using StringLcidDictionary = LowLevelDictionary<int, CultureInfo>; #endif - [Serializable] public partial class CultureInfo : IFormatProvider, ICloneable { //--------------------------------------------------------------------// diff --git a/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs b/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs index ffb2d46a9e..ccf9993453 100644 --- a/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs +++ b/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs @@ -4,7 +4,6 @@ namespace System.Globalization { - [Serializable] internal class CodePageDataItem { private readonly int _codePage; diff --git a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs index b049eaf45d..00081016c3 100644 --- a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs +++ b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text; -using System.Runtime.Remoting; using System; using System.Security; @@ -18,7 +17,6 @@ namespace System.Globalization // immediately because they don't require creating an object. Creating any of the string // names is delayed until somebody actually asks for them and the names are then cached. - [Serializable] internal class CodePageDataItem { internal int m_dataIndex; diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs index 6dbf5b2786..9115b12bd0 100644 --- a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs +++ b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs @@ -13,9 +13,6 @@ namespace System.Globalization // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) - - [Serializable] - public class GregorianCalendar : Calendar { /* diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs index bdc35f0734..1367e0d0ac 100644 --- a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs +++ b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs @@ -10,7 +10,6 @@ using System.Threading; namespace System.Globalization { // Gregorian Calendars use Era Info - [Serializable] internal class EraInfo { internal int era; // The value of the era. @@ -55,7 +54,6 @@ namespace System.Globalization // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) - [Serializable] internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second diff --git a/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/mscorlib/src/System/Globalization/RegionInfo.cs index c3d5e659ca..ab52002fdc 100644 --- a/src/mscorlib/src/System/Globalization/RegionInfo.cs +++ b/src/mscorlib/src/System/Globalization/RegionInfo.cs @@ -20,7 +20,6 @@ using System.Runtime.Serialization; namespace System.Globalization { - [Serializable] public class RegionInfo { //--------------------------------------------------------------------// diff --git a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs index 464897b03f..a875b70463 100644 --- a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs +++ b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs @@ -20,7 +20,6 @@ namespace System.Globalization // This is public because GetTextElement() is public. // - [Serializable] public class TextElementEnumerator : IEnumerator { private String _str; diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs index fecd2b2970..dd542579d9 100644 --- a/src/mscorlib/src/System/Globalization/TextInfo.cs +++ b/src/mscorlib/src/System/Globalization/TextInfo.cs @@ -19,7 +19,6 @@ using System.Text; namespace System.Globalization { - [Serializable] public partial class TextInfo : ICloneable, IDeserializationCallback { ////--------------------------------------------------------------------// @@ -93,38 +92,9 @@ namespace System.Globalization FinishInitialization(_textInfoName); } - [OnSerializing] - private void OnSerializing(StreamingContext ctx) { } - - [OnDeserializing] - private void OnDeserializing(StreamingContext ctx) - { - // Clear these so we can check if we've fixed them yet - _cultureData = null; - _cultureName = null; - } - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - OnDeserialized(); - } - void IDeserializationCallback.OnDeserialization(Object sender) { - OnDeserialized(); - } - - private void OnDeserialized() - { - // this method will be called twice because of the support of IDeserializationCallback - if (_cultureData == null) - { - // Get the text info name belonging to that culture - _cultureData = CultureInfo.GetCultureInfo(_cultureName)._cultureData; - _textInfoName = _cultureData.STEXTINFO; - FinishInitialization(_textInfoName); - } + throw new PlatformNotSupportedException(); } // diff --git a/src/mscorlib/src/System/IO/BinaryWriter.cs b/src/mscorlib/src/System/IO/BinaryWriter.cs index 3d9839f46e..644226fa79 100644 --- a/src/mscorlib/src/System/IO/BinaryWriter.cs +++ b/src/mscorlib/src/System/IO/BinaryWriter.cs @@ -27,7 +27,6 @@ namespace System.IO // primitives to an arbitrary stream. A subclass can override methods to // give unique encodings. // - [Serializable] public class BinaryWriter : IDisposable { public static readonly BinaryWriter Null = new BinaryWriter(); diff --git a/src/mscorlib/src/System/IO/DriveNotFoundException.cs b/src/mscorlib/src/System/IO/DriveNotFoundException.cs index 27b6f9015d..7e9b0c9f36 100644 --- a/src/mscorlib/src/System/IO/DriveNotFoundException.cs +++ b/src/mscorlib/src/System/IO/DriveNotFoundException.cs @@ -17,7 +17,6 @@ using System.Runtime.Serialization; namespace System.IO { //Thrown when trying to access a drive that is not availabe. - [Serializable] internal class DriveNotFoundException : IOException { public DriveNotFoundException() @@ -34,6 +33,7 @@ namespace System.IO protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/IO/File.cs b/src/mscorlib/src/System/IO/File.cs index 4aba1488ec..da962f6feb 100644 --- a/src/mscorlib/src/System/IO/File.cs +++ b/src/mscorlib/src/System/IO/File.cs @@ -150,13 +150,16 @@ namespace System.IO // Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error String tempPath = path.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); +#if !PLATFORM_UNIX // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. - // SetErrorMode will let us disable this, but we should set the error + // SetThreadErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. - int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); + uint oldMode; + bool errorModeSuccess = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { +#endif bool error = false; SafeFindHandle handle = Win32Native.FindFirstFile(tempPath, findData); try @@ -197,31 +200,41 @@ namespace System.IO } } } +#if !PLATFORM_UNIX } finally { - Win32Native.SetErrorMode(oldMode); + if (errorModeSuccess) + Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } +#endif // Copy the information to data data.PopulateFrom(findData); } else { + bool success = false; + +#if !PLATFORM_UNIX // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. - // SetErrorMode will let us disable this, but we should set the error + // SetThreadErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. - bool success = false; - int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); + uint oldMode; + bool errorModeSuccess = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { +#endif success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data); +#if !PLATFORM_UNIX } finally { - Win32Native.SetErrorMode(oldMode); + if (errorModeSuccess) + Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } +#endif if (!success) { diff --git a/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs index f6415670e3..d4ce9a9ab9 100644 --- a/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs +++ b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs @@ -27,7 +27,10 @@ namespace System.IO GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format)); string message = null; - GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message)); + if (hResult == System.__HResults.COR_E_BADEXEFORMAT) + message = SR.Arg_BadImageFormatException; + else + GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message)); return string.Format(CultureInfo.CurrentCulture, format, fileName, message); } diff --git a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs index 0316de0f93..5e19fbed36 100644 --- a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs +++ b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs @@ -146,8 +146,10 @@ namespace System.IO private SearchOption searchOption; private String fullPath; private String normalizedSearchPath; - private int oldMode; - +#if !PLATFORM_UNIX + private int _oldMode; + private bool _setBackOldMode; +#endif internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler<TSource> resultHandler, bool checkHost) { Contract.Requires(path != null); @@ -156,7 +158,9 @@ namespace System.IO Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Requires(resultHandler != null); - oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); +#if !PLATFORM_UNIX + _setBackOldMode = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out _oldMode); +#endif searchStack = new List<Directory.SearchData>(); @@ -284,7 +288,14 @@ namespace System.IO } finally { - Win32Native.SetErrorMode(oldMode); +#if !PLATFORM_UNIX + if (_setBackOldMode) + { + uint _ignore; + Interop.Kernel32.SetThreadErrorMode(_oldMode, out _ignore); + } +#endif + base.Dispose(disposing); } } diff --git a/src/mscorlib/src/System/IO/IOException.cs b/src/mscorlib/src/System/IO/IOException.cs index 2628f7b652..65504de863 100644 --- a/src/mscorlib/src/System/IO/IOException.cs +++ b/src/mscorlib/src/System/IO/IOException.cs @@ -18,7 +18,6 @@ using System.Runtime.Serialization; namespace System.IO { - [Serializable] public class IOException : SystemException { // For debugging purposes, store the complete path in the IOException @@ -68,6 +67,7 @@ namespace System.IO protected IOException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/IO/MemoryStream.cs b/src/mscorlib/src/System/IO/MemoryStream.cs index 3d5668d774..daf09d1274 100644 --- a/src/mscorlib/src/System/IO/MemoryStream.cs +++ b/src/mscorlib/src/System/IO/MemoryStream.cs @@ -34,7 +34,6 @@ namespace System.IO // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. - [Serializable] public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. diff --git a/src/mscorlib/src/System/IO/SearchOption.cs b/src/mscorlib/src/System/IO/SearchOption.cs index 75909d7499..c2f7e0db6e 100644 --- a/src/mscorlib/src/System/IO/SearchOption.cs +++ b/src/mscorlib/src/System/IO/SearchOption.cs @@ -20,7 +20,6 @@ using System; namespace System.IO { - [Serializable] internal enum SearchOption { // Include only the current directory in the search operation diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs index 65cc4ddcb9..786dfedef9 100644 --- a/src/mscorlib/src/System/IO/Stream.cs +++ b/src/mscorlib/src/System/IO/Stream.cs @@ -30,7 +30,6 @@ using System.Reflection; namespace System.IO { - [Serializable] public abstract class Stream : MarshalByRefObject, IDisposable { public static readonly Stream Null = new NullStream(); @@ -854,7 +853,6 @@ namespace System.IO SynchronousAsyncResult.EndWrite(asyncResult); } - [Serializable] private sealed class NullStream : Stream { internal NullStream() { } @@ -1093,7 +1091,6 @@ namespace System.IO // SyncStream is a wrapper around a stream that takes // a lock for every operation making it thread safe. - [Serializable] internal sealed class SyncStream : Stream, IDisposable { private Stream _stream; diff --git a/src/mscorlib/src/System/IO/StreamReader.cs b/src/mscorlib/src/System/IO/StreamReader.cs index dfb928c85d..1fc72bffd1 100644 --- a/src/mscorlib/src/System/IO/StreamReader.cs +++ b/src/mscorlib/src/System/IO/StreamReader.cs @@ -16,7 +16,6 @@ namespace System.IO // This is designed for character input in a particular Encoding, // whereas the Stream class is designed for byte input and output. // - [Serializable] internal class StreamReader : TextReader { // StreamReader.Null is threadsafe. diff --git a/src/mscorlib/src/System/IO/TextReader.cs b/src/mscorlib/src/System/IO/TextReader.cs index 3da68591b0..2531778d6d 100644 --- a/src/mscorlib/src/System/IO/TextReader.cs +++ b/src/mscorlib/src/System/IO/TextReader.cs @@ -30,7 +30,6 @@ namespace System.IO { // // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. - [Serializable] internal abstract class TextReader : MarshalByRefObject, IDisposable { public static readonly TextReader Null = new NullTextReader(); @@ -263,7 +262,6 @@ namespace System.IO { return new SyncTextReader(reader); } - [Serializable] private sealed class NullTextReader : TextReader { public NullTextReader(){} @@ -280,7 +278,6 @@ namespace System.IO { } } - [Serializable] internal sealed class SyncTextReader : TextReader { internal TextReader _in; diff --git a/src/mscorlib/src/System/IO/__Error.cs b/src/mscorlib/src/System/IO/__Error.cs index 70f83261ed..1af195ef77 100644 --- a/src/mscorlib/src/System/IO/__Error.cs +++ b/src/mscorlib/src/System/IO/__Error.cs @@ -206,11 +206,5 @@ namespace System.IO { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } - - // From WinError.h - internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND; - internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND; - internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED; - internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER; } } diff --git a/src/mscorlib/src/System/InsufficientMemoryException.cs b/src/mscorlib/src/System/InsufficientMemoryException.cs index eb5e4d7430..8f7aa96ff7 100644 --- a/src/mscorlib/src/System/InsufficientMemoryException.cs +++ b/src/mscorlib/src/System/InsufficientMemoryException.cs @@ -22,7 +22,6 @@ using System.Runtime.Serialization; namespace System { - [Serializable] public sealed class InsufficientMemoryException : OutOfMemoryException { public InsufficientMemoryException() @@ -42,9 +41,5 @@ namespace System { HResult = __HResults.COR_E_INSUFFICIENTMEMORY; } - - private InsufficientMemoryException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } } } diff --git a/src/mscorlib/src/System/Int16.cs b/src/mscorlib/src/System/Int16.cs index 69f71af278..aced05df6d 100644 --- a/src/mscorlib/src/System/Int16.cs +++ b/src/mscorlib/src/System/Int16.cs @@ -25,7 +25,7 @@ namespace System public struct Int16 : IComparable, IFormattable, IConvertible , IComparable<Int16>, IEquatable<Int16> { - internal short m_value; + private short m_value; // Do not rename (binary serialization) public const short MaxValue = (short)0x7FFF; public const short MinValue = unchecked((short)0x8000); diff --git a/src/mscorlib/src/System/Int32.cs b/src/mscorlib/src/System/Int32.cs index 90b70a9554..afee0e42d7 100644 --- a/src/mscorlib/src/System/Int32.cs +++ b/src/mscorlib/src/System/Int32.cs @@ -25,7 +25,7 @@ namespace System public struct Int32 : IComparable, IFormattable, IConvertible , IComparable<Int32>, IEquatable<Int32> { - internal int m_value; + private int m_value; // Do not rename (binary serialization) public const int MaxValue = 0x7fffffff; public const int MinValue = unchecked((int)0x80000000); diff --git a/src/mscorlib/src/System/Int64.cs b/src/mscorlib/src/System/Int64.cs index 3d64362e30..619bf7e5d7 100644 --- a/src/mscorlib/src/System/Int64.cs +++ b/src/mscorlib/src/System/Int64.cs @@ -24,7 +24,7 @@ namespace System public struct Int64 : IComparable, IFormattable, IConvertible , IComparable<Int64>, IEquatable<Int64> { - internal long m_value; + private long m_value; // Do not rename (binary serialization) public const long MaxValue = 0x7fffffffffffffffL; public const long MinValue = unchecked((long)0x8000000000000000L); diff --git a/src/mscorlib/src/System/IntPtr.cs b/src/mscorlib/src/System/IntPtr.cs index 28f1b1baa8..55c86e3795 100644 --- a/src/mscorlib/src/System/IntPtr.cs +++ b/src/mscorlib/src/System/IntPtr.cs @@ -25,7 +25,7 @@ namespace System [Serializable] public struct IntPtr : IEquatable<IntPtr>, ISerializable { - unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior + unsafe private void* _value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior public static readonly IntPtr Zero; @@ -33,16 +33,16 @@ namespace System [Pure] internal unsafe bool IsNull() { - return (m_value == null); + return (_value == null); } [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(int value) { #if BIT64 - m_value = (void*)(long)value; + _value = (void*)(long)value; #else // !BIT64 (32) - m_value = (void *)value; + _value = (void *)value; #endif } @@ -50,9 +50,9 @@ namespace System public unsafe IntPtr(long value) { #if BIT64 - m_value = (void*)value; + _value = (void*)value; #else // !BIT64 (32) - m_value = (void *)checked((int)value); + _value = (void *)checked((int)value); #endif } @@ -60,7 +60,7 @@ namespace System [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(void* value) { - m_value = value; + _value = value; } private unsafe IntPtr(SerializationInfo info, StreamingContext context) @@ -72,7 +72,7 @@ namespace System throw new ArgumentException(SR.Serialization_InvalidPtrValue); } - m_value = (void*)l; + _value = (void*)l; } unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) @@ -83,9 +83,9 @@ namespace System } Contract.EndContractBlock(); #if BIT64 - info.AddValue("value", (long)(m_value)); + info.AddValue("value", (long)(_value)); #else // !BIT64 (32) - info.AddValue("value", (long)((int)m_value)); + info.AddValue("value", (long)((int)_value)); #endif } @@ -93,23 +93,23 @@ namespace System { if (obj is IntPtr) { - return (m_value == ((IntPtr)obj).m_value); + return (_value == ((IntPtr)obj)._value); } return false; } unsafe bool IEquatable<IntPtr>.Equals(IntPtr other) { - return m_value == other.m_value; + return _value == other._value; } public unsafe override int GetHashCode() { #if BIT64 - long l = (long)m_value; + long l = (long)_value; return (unchecked((int)l) ^ (int)(l >> 32)); #else // !BIT64 (32) - return unchecked((int)m_value); + return unchecked((int)_value); #endif } @@ -117,10 +117,10 @@ namespace System public unsafe int ToInt32() { #if BIT64 - long l = (long)m_value; + long l = (long)_value; return checked((int)l); #else // !BIT64 (32) - return (int)m_value; + return (int)_value; #endif } @@ -128,18 +128,18 @@ namespace System public unsafe long ToInt64() { #if BIT64 - return (long)m_value; + return (long)_value; #else // !BIT64 (32) - return (long)(int)m_value; + return (long)(int)_value; #endif } public unsafe override String ToString() { #if BIT64 - return ((long)m_value).ToString(CultureInfo.InvariantCulture); + return ((long)_value).ToString(CultureInfo.InvariantCulture); #else // !BIT64 (32) - return ((int)m_value).ToString(CultureInfo.InvariantCulture); + return ((int)_value).ToString(CultureInfo.InvariantCulture); #endif } @@ -148,9 +148,9 @@ namespace System Contract.Ensures(Contract.Result<String>() != null); #if BIT64 - return ((long)m_value).ToString(format, CultureInfo.InvariantCulture); + return ((long)_value).ToString(format, CultureInfo.InvariantCulture); #else // !BIT64 (32) - return ((int)m_value).ToString(format, CultureInfo.InvariantCulture); + return ((int)_value).ToString(format, CultureInfo.InvariantCulture); #endif } @@ -178,17 +178,17 @@ namespace System [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator void* (IntPtr value) { - return value.m_value; + return value._value; } [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator int(IntPtr value) { #if BIT64 - long l = (long)value.m_value; + long l = (long)value._value; return checked((int)l); #else // !BIT64 (32) - return (int)value.m_value; + return (int)value._value; #endif } @@ -196,22 +196,22 @@ namespace System public unsafe static explicit operator long(IntPtr value) { #if BIT64 - return (long)value.m_value; + return (long)value._value; #else // !BIT64 (32) - return (long)(int)value.m_value; + return (long)(int)value._value; #endif } [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator ==(IntPtr value1, IntPtr value2) { - return value1.m_value == value2.m_value; + return value1._value == value2._value; } [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator !=(IntPtr value1, IntPtr value2) { - return value1.m_value != value2.m_value; + return value1._value != value2._value; } [System.Runtime.Versioning.NonVersionable] @@ -265,7 +265,7 @@ namespace System [System.Runtime.Versioning.NonVersionable] public unsafe void* ToPointer() { - return m_value; + return _value; } } } diff --git a/src/mscorlib/src/System/MissingFieldException.cs b/src/mscorlib/src/System/MissingFieldException.cs index 5668f9e9b3..668d5f2a31 100644 --- a/src/mscorlib/src/System/MissingFieldException.cs +++ b/src/mscorlib/src/System/MissingFieldException.cs @@ -11,14 +11,12 @@ using System; -using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Globalization; namespace System { - [Serializable] public class MissingFieldException : MissingMemberException, ISerializable { public MissingFieldException() @@ -41,6 +39,7 @@ namespace System protected MissingFieldException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } public override String Message diff --git a/src/mscorlib/src/System/MissingMemberException.cs b/src/mscorlib/src/System/MissingMemberException.cs index 51150e113c..1fb0c55e40 100644 --- a/src/mscorlib/src/System/MissingMemberException.cs +++ b/src/mscorlib/src/System/MissingMemberException.cs @@ -13,7 +13,6 @@ using System; -using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Globalization; @@ -22,7 +21,6 @@ using System.Diagnostics.Contracts; namespace System { - [Serializable] public class MissingMemberException : MemberAccessException, ISerializable { public MissingMemberException() @@ -45,9 +43,7 @@ namespace System protected MissingMemberException(SerializationInfo info, StreamingContext context) : base(info, context) { - ClassName = (String)info.GetString("MMClassName"); - MemberName = (String)info.GetString("MMMemberName"); - Signature = (byte[])info.GetValue("MMSignature", typeof(byte[])); + throw new PlatformNotSupportedException(); } public override String Message @@ -78,15 +74,7 @@ namespace System public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); base.GetObjectData(info, context); - info.AddValue("MMClassName", ClassName, typeof(String)); - info.AddValue("MMMemberName", MemberName, typeof(String)); - info.AddValue("MMSignature", Signature, typeof(byte[])); } diff --git a/src/mscorlib/src/System/MulticastDelegate.cs b/src/mscorlib/src/System/MulticastDelegate.cs index 440c9a60bc..988bf2bb60 100644 --- a/src/mscorlib/src/System/MulticastDelegate.cs +++ b/src/mscorlib/src/System/MulticastDelegate.cs @@ -13,7 +13,6 @@ using System.Reflection.Emit; namespace System { - [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class MulticastDelegate : Delegate { @@ -50,49 +49,7 @@ namespace System public override void GetObjectData(SerializationInfo info, StreamingContext context) { - int targetIndex = 0; - Object[] invocationList = _invocationList as Object[]; - if (invocationList == null) - { - MethodInfo method = Method; - // A MethodInfo object can be a RuntimeMethodInfo, a RefEmit method (MethodBuilder, etc), or a DynamicMethod - // One can only create delegates on RuntimeMethodInfo and DynamicMethod. - // If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, throw - if (!(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr()) - throw new SerializationException(SR.Serialization_InvalidDelegateType); - - // We can't deal with secure delegates either. - if (!InvocationListLogicallyNull() && !_invocationCount.IsNull() && !_methodPtrAux.IsNull()) - throw new SerializationException(SR.Serialization_InvalidDelegateType); - - DelegateSerializationHolder.GetDelegateSerializationInfo(info, this.GetType(), Target, method, targetIndex); - } - else - { - DelegateSerializationHolder.DelegateEntry nextDe = null; - int invocationCount = (int)_invocationCount; - for (int i = invocationCount; --i >= 0;) - { - MulticastDelegate d = (MulticastDelegate)invocationList[i]; - MethodInfo method = d.Method; - // If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, skip - if (!(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr()) - continue; - - // We can't deal with secure delegates either. - if (!d.InvocationListLogicallyNull() && !d._invocationCount.IsNull() && !d._methodPtrAux.IsNull()) - continue; - - DelegateSerializationHolder.DelegateEntry de = DelegateSerializationHolder.GetDelegateSerializationInfo(info, d.GetType(), d.Target, method, targetIndex++); - if (nextDe != null) - nextDe.Entry = de; - - nextDe = de; - } - // if nothing was serialized it is a delegate over a DynamicMethod, so just throw - if (nextDe == null) - throw new SerializationException(SR.Serialization_InvalidDelegateType); - } + throw new SerializationException(SR.Serialization_DelegatesNotSupported); } // equals returns true IIF the delegate is not null and has the diff --git a/src/mscorlib/src/System/Object.cs b/src/mscorlib/src/System/Object.cs index 3c304422ac..a476557911 100644 --- a/src/mscorlib/src/System/Object.cs +++ b/src/mscorlib/src/System/Object.cs @@ -201,7 +201,6 @@ namespace System // The name "__Canon" will never been seen by users but it will appear a lot in debugger stack traces // involving generics so it is kept deliberately short as to avoid being a nuisance. - [Serializable] [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] internal class __Canon diff --git a/src/mscorlib/src/System/OleAutBinder.cs b/src/mscorlib/src/System/OleAutBinder.cs index 1db61bb30e..3a9f03c5f0 100644 --- a/src/mscorlib/src/System/OleAutBinder.cs +++ b/src/mscorlib/src/System/OleAutBinder.cs @@ -15,7 +15,6 @@ namespace System using CultureInfo = System.Globalization.CultureInfo; // Made serializable in anticipation of this class eventually having state. - [Serializable] internal class OleAutBinder : DefaultBinder { // ChangeType diff --git a/src/mscorlib/src/System/OperatingSystem.cs b/src/mscorlib/src/System/OperatingSystem.cs deleted file mode 100644 index 5eb1253fa5..0000000000 --- a/src/mscorlib/src/System/OperatingSystem.cs +++ /dev/null @@ -1,154 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** Purpose: -** -** -===========================================================*/ - -using System.Runtime.Serialization; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Diagnostics.Contracts; - -namespace System -{ - [Serializable] - internal sealed class OperatingSystem : ICloneable, ISerializable - { - private Version _version; - private PlatformID _platform; - private string _servicePack; - private string _versionString; - - private OperatingSystem() - { - } - - internal OperatingSystem(PlatformID platform, Version version, string servicePack) - { - if (platform < PlatformID.Win32S || platform > PlatformID.MacOSX) - { - throw new ArgumentException( - SR.Format(SR.Arg_EnumIllegalVal, (int)platform), - nameof(platform)); - } - - if ((Object)version == null) - throw new ArgumentNullException(nameof(version)); - Contract.EndContractBlock(); - - _platform = platform; - _version = (Version)version.Clone(); - _servicePack = servicePack; - } - - private OperatingSystem(SerializationInfo info, StreamingContext context) - { - SerializationInfoEnumerator enumerator = info.GetEnumerator(); - while (enumerator.MoveNext()) - { - switch (enumerator.Name) - { - case "_version": - _version = (Version)info.GetValue("_version", typeof(Version)); - break; - case "_platform": - _platform = (PlatformID)info.GetValue("_platform", typeof(PlatformID)); - break; - case "_servicePack": - _servicePack = info.GetString("_servicePack"); - break; - } - } - - if (_version == null) - { - throw new SerializationException(SR.Format(SR.Serialization_MissField, "_version")); - } - } - - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); - - info.AddValue("_version", _version); - info.AddValue("_platform", _platform); - info.AddValue("_servicePack", _servicePack); - } - - public Version Version - { - get { return _version; } - } - - public Object Clone() - { - return new OperatingSystem(_platform, - _version, _servicePack); - } - - public override String ToString() - { - return VersionString; - } - - public String VersionString - { - get - { - if (_versionString != null) - { - return _versionString; - } - - String os; - switch (_platform) - { - case PlatformID.Win32NT: - os = "Microsoft Windows NT "; - break; - case PlatformID.Win32Windows: - if ((_version.Major > 4) || - ((_version.Major == 4) && (_version.Minor > 0))) - os = "Microsoft Windows 98 "; - else - os = "Microsoft Windows 95 "; - break; - case PlatformID.Win32S: - os = "Microsoft Win32S "; - break; - case PlatformID.WinCE: - os = "Microsoft Windows CE "; - break; - case PlatformID.MacOSX: - os = "Mac OS X "; - break; - default: - os = "<unknown> "; - break; - } - - if (String.IsNullOrEmpty(_servicePack)) - { - _versionString = os + _version.ToString(); - } - else - { - _versionString = os + _version.ToString(3) + " " + _servicePack; - } - - return _versionString; - } - } - } -} diff --git a/src/mscorlib/src/System/OutOfMemoryException.cs b/src/mscorlib/src/System/OutOfMemoryException.cs index 154d0f92e2..3bec542077 100644 --- a/src/mscorlib/src/System/OutOfMemoryException.cs +++ b/src/mscorlib/src/System/OutOfMemoryException.cs @@ -17,7 +17,6 @@ using System.Runtime.Serialization; namespace System { - [Serializable] public class OutOfMemoryException : SystemException { public OutOfMemoryException() @@ -40,6 +39,7 @@ namespace System protected OutOfMemoryException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/PlatformID.cs b/src/mscorlib/src/System/PlatformID.cs deleted file mode 100644 index dfab2175ab..0000000000 --- a/src/mscorlib/src/System/PlatformID.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** Purpose: Defines IDs for supported platforms -** -** -===========================================================*/ - -namespace System -{ - [Serializable] - internal enum PlatformID - { - Win32S = 0, - Win32Windows = 1, - Win32NT = 2, - WinCE = 3, - Unix = 4, - Xbox = 5, - MacOSX = 6 - } -} diff --git a/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs b/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs index 708f79b64f..9d34b48177 100644 --- a/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs +++ b/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs @@ -15,34 +15,78 @@ namespace System.Reflection { public abstract partial class Assembly : ICustomAttributeProvider, ISerializable { + private static volatile bool s_LoadFromResolveHandlerSetup = false; + private static object s_syncRootLoadFrom = new object(); + private static List<string> s_LoadFromAssemblyList = new List<string>(); + private static object s_syncLoadFromAssemblyList = new object(); + + private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs args) + { + Assembly requestingAssembly = args.RequestingAssembly; + + // Requesting assembly for LoadFrom is always loaded in defaultContext - proceed only if that + // is the case. + if (AssemblyLoadContext.Default != AssemblyLoadContext.GetLoadContext(requestingAssembly)) + return null; + + // Get the path where requesting assembly lives and check if it is in the list + // of assemblies for which LoadFrom was invoked. + bool fRequestorLoadedViaLoadFrom = false; + string requestorPath = Path.GetFullPath(requestingAssembly.Location); + if (string.IsNullOrEmpty(requestorPath)) + return null; + + lock(s_syncLoadFromAssemblyList) + { + fRequestorLoadedViaLoadFrom = s_LoadFromAssemblyList.Contains(requestorPath); + } + + // If the requestor assembly was not loaded using LoadFrom, exit. + if (!fRequestorLoadedViaLoadFrom) + return null; + + // Requestor assembly was loaded using loadFrom, so look for its dependencies + // in the same folder as it. + // Form the name of the assembly using the path of the assembly that requested its load. + AssemblyName requestedAssemblyName = new AssemblyName(args.Name); + string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath), requestedAssemblyName.Name+".dll"); + + // Load the dependency via LoadFrom so that it goes through the same path of being in the LoadFrom list. + return Assembly.LoadFrom(requestedAssemblyPath); + } + public static Assembly LoadFrom(String assemblyFile) { if (assemblyFile == null) throw new ArgumentNullException(nameof(assemblyFile)); + string fullPath = Path.GetFullPath(assemblyFile); - return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath); - } - // Evidence is protected in Assembly.Load() - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - internal static Assembly LoadFrom(String assemblyFile, - Evidence securityEvidence) - { - Contract.Ensures(Contract.Result<Assembly>() != null); + if (!s_LoadFromResolveHandlerSetup) + { + lock (s_syncRootLoadFrom) + { + if (!s_LoadFromResolveHandlerSetup) + { + AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromResolveHandler); + s_LoadFromResolveHandlerSetup = true; + } + } + } - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + // Add the path to the LoadFrom path list which we will consult + // before handling the resolves in our handler. + lock(s_syncLoadFromAssemblyList) + { + if (!s_LoadFromAssemblyList.Contains(fullPath)) + { + s_LoadFromAssemblyList.Add(fullPath); + } + } - return RuntimeAssembly.InternalLoadFrom( - assemblyFile, - securityEvidence, - null, // hashValue - AssemblyHashAlgorithm.None, - false,// forIntrospection); - ref stackMark); + return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath); } - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly LoadFrom(String assemblyFile, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm) diff --git a/src/mscorlib/src/System/Reflection/AssemblyName.cs b/src/mscorlib/src/System/Reflection/AssemblyName.cs index 80fdf5d162..6bfc5b7496 100644 --- a/src/mscorlib/src/System/Reflection/AssemblyName.cs +++ b/src/mscorlib/src/System/Reflection/AssemblyName.cs @@ -27,7 +27,6 @@ namespace System.Reflection using System.Diagnostics.Contracts; using System.Text; - [Serializable] public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback { // @@ -279,7 +278,11 @@ namespace System.Reflection { get { - return nToString(); + if (this.Name == null) + return string.Empty; + // Do not call GetPublicKeyToken() here - that latches the result into AssemblyName which isn't a side effect we want. + byte[] pkt = _PublicKeyToken ?? nGetPublicKeyToken(); + return AssemblyNameFormatter.ComputeDisplayName(Name, Version, CultureName, pkt, Flags, ContentType); } } @@ -295,68 +298,12 @@ namespace System.Reflection public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - //Allocate the serialization info and serialize our static data. - info.AddValue("_Name", _Name); - info.AddValue("_PublicKey", _PublicKey, typeof(byte[])); - info.AddValue("_PublicKeyToken", _PublicKeyToken, typeof(byte[])); -#if FEATURE_USE_LCID - info.AddValue("_CultureInfo", (_CultureInfo == null) ? -1 : _CultureInfo.LCID); -#endif - info.AddValue("_CodeBase", _CodeBase); - info.AddValue("_Version", _Version); - info.AddValue("_HashAlgorithm", _HashAlgorithm, typeof(AssemblyHashAlgorithm)); - info.AddValue("_HashAlgorithmForControl", _HashAlgorithmForControl, typeof(AssemblyHashAlgorithm)); - info.AddValue("_StrongNameKeyPair", _StrongNameKeyPair, typeof(StrongNameKeyPair)); - info.AddValue("_VersionCompatibility", _VersionCompatibility, typeof(AssemblyVersionCompatibility)); - info.AddValue("_Flags", _Flags, typeof(AssemblyNameFlags)); - info.AddValue("_HashForControl", _HashForControl, typeof(byte[])); + throw new PlatformNotSupportedException(); } public void OnDeserialization(Object sender) { - // Deserialization has already been performed - if (m_siInfo == null) - return; - - _Name = m_siInfo.GetString("_Name"); - _PublicKey = (byte[])m_siInfo.GetValue("_PublicKey", typeof(byte[])); - _PublicKeyToken = (byte[])m_siInfo.GetValue("_PublicKeyToken", typeof(byte[])); -#if FEATURE_USE_LCID - int lcid = (int)m_siInfo.GetInt32("_CultureInfo"); - if (lcid != -1) - _CultureInfo = new CultureInfo(lcid); -#endif - - _CodeBase = m_siInfo.GetString("_CodeBase"); - _Version = (Version)m_siInfo.GetValue("_Version", typeof(Version)); - _HashAlgorithm = (AssemblyHashAlgorithm)m_siInfo.GetValue("_HashAlgorithm", typeof(AssemblyHashAlgorithm)); - _StrongNameKeyPair = (StrongNameKeyPair)m_siInfo.GetValue("_StrongNameKeyPair", typeof(StrongNameKeyPair)); - _VersionCompatibility = (AssemblyVersionCompatibility)m_siInfo.GetValue("_VersionCompatibility", typeof(AssemblyVersionCompatibility)); - _Flags = (AssemblyNameFlags)m_siInfo.GetValue("_Flags", typeof(AssemblyNameFlags)); - - try - { - _HashAlgorithmForControl = (AssemblyHashAlgorithm)m_siInfo.GetValue("_HashAlgorithmForControl", typeof(AssemblyHashAlgorithm)); - _HashForControl = (byte[])m_siInfo.GetValue("_HashForControl", typeof(byte[])); - } - catch (SerializationException) - { // RTM did not have these defined - _HashAlgorithmForControl = AssemblyHashAlgorithm.None; - _HashForControl = null; - } - - m_siInfo = null; - } - - // Constructs a new AssemblyName during deserialization. - internal AssemblyName(SerializationInfo info, StreamingContext context) - { - //The graph is not valid until OnDeserialization() has been called. - m_siInfo = info; + throw new PlatformNotSupportedException(); } public AssemblyName(String assemblyName) diff --git a/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs index 96eb45f3e4..1cf00f17d8 100644 --- a/src/mscorlib/src/System/Reflection/CustomAttribute.cs +++ b/src/mscorlib/src/System/Reflection/CustomAttribute.cs @@ -20,7 +20,6 @@ using System.Diagnostics.Contracts; namespace System.Reflection { - [Serializable] public class CustomAttributeData { #region Public Static Members @@ -570,7 +569,6 @@ namespace System.Reflection #endregion } - [Serializable] public struct CustomAttributeNamedArgument { #region Public Static Members @@ -659,7 +657,6 @@ namespace System.Reflection } - [Serializable] public struct CustomAttributeTypedArgument { #region Public Static Members @@ -958,14 +955,12 @@ namespace System.Reflection #endregion } - [Serializable] internal struct CustomAttributeRecord { internal ConstArray blob; internal MetadataToken tkCtor; } - [Serializable] internal enum CustomAttributeEncoding : int { Undefined = 0, @@ -990,7 +985,6 @@ namespace System.Reflection Enum = 0x55 } - [Serializable] [StructLayout(LayoutKind.Auto)] internal struct CustomAttributeEncodedArgument { @@ -1045,7 +1039,6 @@ namespace System.Reflection #endregion } - [Serializable] [StructLayout(LayoutKind.Auto)] internal struct CustomAttributeNamedParameter { @@ -1077,7 +1070,6 @@ namespace System.Reflection #endregion } - [Serializable] [StructLayout(LayoutKind.Auto)] internal struct CustomAttributeCtorParameter { @@ -1099,7 +1091,6 @@ namespace System.Reflection #endregion } - [Serializable] [StructLayout(LayoutKind.Auto)] internal struct CustomAttributeType { @@ -2040,7 +2031,7 @@ namespace System.Reflection count = 0; bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType)) + if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType)) return Array.Empty<Attribute>(); List<Attribute> pcas = new List<Attribute>(); @@ -2078,7 +2069,7 @@ namespace System.Reflection internal static bool IsDefined(RuntimeType type, RuntimeType caType) { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType)) + if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType)) return false; if (all || caType == (RuntimeType)typeof(SerializableAttribute)) @@ -2107,7 +2098,7 @@ namespace System.Reflection count = 0; bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType)) + if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType)) return Array.Empty<Attribute>(); List<Attribute> pcas = new List<Attribute>(); @@ -2140,7 +2131,7 @@ namespace System.Reflection internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType) { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null) + if (!all && !s_pca.ContainsKey(caType)) return false; if (all || caType == (RuntimeType)typeof(DllImportAttribute)) @@ -2170,7 +2161,7 @@ namespace System.Reflection count = 0; bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null) + if (!all && !s_pca.ContainsKey(caType)) return null; Attribute[] pcas = new Attribute[s_pcasCount]; @@ -2201,7 +2192,7 @@ namespace System.Reflection internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType) { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null) + if (!all && !s_pca.ContainsKey(caType)) return false; @@ -2231,7 +2222,7 @@ namespace System.Reflection bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType)) + if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType)) return Array.Empty<Attribute>(); List<Attribute> pcas = new List<Attribute>(); @@ -2283,7 +2274,7 @@ namespace System.Reflection count = 0; bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null) + if (!all && !s_pca.ContainsKey(caType)) return null; Attribute[] pcas = new Attribute[s_pcasCount]; @@ -2309,7 +2300,7 @@ namespace System.Reflection internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType) { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null) + if (!all && !s_pca.ContainsKey(caType)) return false; if (all || caType == (RuntimeType)typeof(MarshalAsAttribute)) @@ -2334,7 +2325,7 @@ namespace System.Reflection bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType)) + if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType)) return Array.Empty<Attribute>(); List<Attribute> pcas = new List<Attribute>(); @@ -2357,7 +2348,7 @@ namespace System.Reflection { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); - if (!all && s_pca.GetValueOrDefault(caType) == null) + if (!all && !s_pca.ContainsKey(caType)) return false; if (all || IsSecurityAttribute(caType)) diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs index ead2fafcef..b096960406 100644 --- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs +++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs @@ -9,7 +9,6 @@ using System; namespace System.Reflection.Emit { - [Serializable] [Flags] public enum AssemblyBuilderAccess { diff --git a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs index 55aa5c5a8f..a36882b036 100644 --- a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs @@ -242,6 +242,8 @@ namespace System.Reflection.Emit return m_typeBuilder.Attributes; } + public override bool IsTypeDefinition => true; + public override bool IsSZArray => false; protected override bool IsArrayImpl() diff --git a/src/mscorlib/src/System/Reflection/Emit/EventToken.cs b/src/mscorlib/src/System/Reflection/Emit/EventToken.cs index 18ec630b5f..e44dc3d0ce 100644 --- a/src/mscorlib/src/System/Reflection/Emit/EventToken.cs +++ b/src/mscorlib/src/System/Reflection/Emit/EventToken.cs @@ -18,7 +18,6 @@ using System.Reflection; namespace System.Reflection.Emit { - [Serializable] public struct EventToken { public static readonly EventToken Empty = new EventToken(); diff --git a/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs b/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs index 6c5d778d8f..c7450ca301 100644 --- a/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs +++ b/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs @@ -22,7 +22,6 @@ namespace System.Reflection.Emit // by the Metadata to represent the field. FieldTokens are generated by // Module.GetFieldToken(). There are no meaningful accessors on this class, // but it can be passed to ILGenerator which understands it's internals. - [Serializable] public struct FieldToken { public static readonly FieldToken Empty = new FieldToken(); diff --git a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs index fb8564652f..531d229a5c 100644 --- a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs +++ b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs @@ -16,7 +16,6 @@ using System; namespace System.Reflection.Emit { - [Serializable] public enum FlowControl { Branch = 0, diff --git a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs index dd5ffa92a9..75e4acc903 100644 --- a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs @@ -154,6 +154,8 @@ namespace System.Reflection.Emit protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; } + public override bool IsTypeDefinition => false; + public override bool IsSZArray => false; protected override bool IsArrayImpl() { return false; } diff --git a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs index 4021410a33..fa31d66f6c 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs @@ -1605,7 +1605,6 @@ namespace System.Reflection.Emit * takes place. * ***************************/ - [Serializable] internal enum ScopeAction { Open = 0x0, diff --git a/src/mscorlib/src/System/Reflection/Emit/Label.cs b/src/mscorlib/src/System/Reflection/Emit/Label.cs index f6315a67d2..d67c0e6a19 100644 --- a/src/mscorlib/src/System/Reflection/Emit/Label.cs +++ b/src/mscorlib/src/System/Reflection/Emit/Label.cs @@ -26,7 +26,6 @@ namespace System.Reflection.Emit // is passed to the MethodWriter. // Labels are created by using ILGenerator.CreateLabel and their position is set // by using ILGenerator.MarkLabel. - [Serializable] public struct Label { internal int m_label; diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs b/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs index 0905ac922a..9698b07333 100644 --- a/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs +++ b/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs @@ -18,7 +18,6 @@ using System.Reflection; namespace System.Reflection.Emit { - [Serializable] public struct MethodToken { public static readonly MethodToken Empty = new MethodToken(); diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs index 4f1b8eb713..4a9b774d15 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs @@ -19,7 +19,6 @@ namespace System.Reflection.Emit // This is a package private class. This class hold all of the managed // data member for ModuleBuilder. Note that what ever data members added to // this class cannot be accessed from the EE. - [Serializable] internal class ModuleBuilderData { internal ModuleBuilderData(ModuleBuilder module, String strModuleName, String strFileName, int tkFile) diff --git a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs index 2363d607fc..db7fa2f209 100644 --- a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs +++ b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs @@ -17,7 +17,6 @@ using System; namespace System.Reflection.Emit { - [Serializable] public enum OpCodeType { [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] diff --git a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs index 033539b999..db113b1725 100644 --- a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs +++ b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs @@ -17,7 +17,6 @@ using System; namespace System.Reflection.Emit { - [Serializable] public enum OperandType { InlineBrTarget = 0, diff --git a/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs b/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs index f9246fce6d..f6606c477a 100644 --- a/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs +++ b/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs @@ -8,7 +8,6 @@ using System; namespace System.Reflection.Emit { // This Enum matchs the CorFieldAttr defined in CorHdr.h - [Serializable] public enum PEFileKinds { Dll = 0x0001, diff --git a/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs b/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs index 42f85af464..067bc2d010 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs @@ -20,7 +20,6 @@ namespace System.Reflection.Emit { // The ParameterToken class is an opaque representation of the Token returned // by the Metadata to represent the parameter. - [Serializable] public struct ParameterToken { public static readonly ParameterToken Empty = new ParameterToken(); diff --git a/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs b/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs index b450b198d2..02f34881f4 100644 --- a/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs +++ b/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs @@ -18,7 +18,6 @@ using System.Reflection; namespace System.Reflection.Emit { - [Serializable] public struct PropertyToken { public static readonly PropertyToken Empty = new PropertyToken(); diff --git a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs index afcf2ddf0a..b9054b709e 100644 --- a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs +++ b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs @@ -17,7 +17,6 @@ using System; namespace System.Reflection.Emit { - [Serializable] public enum StackBehaviour { Pop0 = 0, diff --git a/src/mscorlib/src/System/Reflection/Emit/StringToken.cs b/src/mscorlib/src/System/Reflection/Emit/StringToken.cs index 1d90816fc6..cc5b734ae8 100644 --- a/src/mscorlib/src/System/Reflection/Emit/StringToken.cs +++ b/src/mscorlib/src/System/Reflection/Emit/StringToken.cs @@ -18,7 +18,6 @@ using System.Reflection; namespace System.Reflection.Emit { - [Serializable] public struct StringToken { internal int m_string; diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs index 16848b43dd..ca2f7d9d6e 100644 --- a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs +++ b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs @@ -12,7 +12,6 @@ namespace System.Reflection.Emit using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; - [Serializable] internal enum TypeKind { IsArray = 1, @@ -271,6 +270,9 @@ namespace System.Reflection.Emit #endregion #region Type Overrides + + public override bool IsTypeDefinition => false; + public override bool IsSZArray => m_cRank <= 1 && m_isSzArray; public override Type MakePointerType() diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs index a98af2bdcf..2f550a4e40 100644 --- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs @@ -20,7 +20,6 @@ namespace System.Reflection.Emit using System.Diagnostics.Contracts; - [Serializable] public enum PackingSize { Unspecified = 0, @@ -1109,6 +1108,8 @@ namespace System.Reflection.Emit return m_iAttr; } + public override bool IsTypeDefinition => true; + public override bool IsSZArray => false; protected override bool IsArrayImpl() diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs index 6d46362f91..64a38b0995 100644 --- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs +++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs @@ -189,6 +189,7 @@ namespace System.Reflection.Emit public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); } protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; } + public override bool IsTypeDefinition => false; public override bool IsSZArray => false; protected override bool IsArrayImpl() { return false; } diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs b/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs index 4f0c1b3dac..15a0816a50 100644 --- a/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs +++ b/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs @@ -19,7 +19,6 @@ using System.Threading; namespace System.Reflection.Emit { - [Serializable] public struct TypeToken { public static readonly TypeToken Empty = new TypeToken(); diff --git a/src/mscorlib/src/System/Reflection/MdFieldInfo.cs b/src/mscorlib/src/System/Reflection/MdFieldInfo.cs index 41ee4d9297..9645b7fef2 100644 --- a/src/mscorlib/src/System/Reflection/MdFieldInfo.cs +++ b/src/mscorlib/src/System/Reflection/MdFieldInfo.cs @@ -9,7 +9,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection { - [Serializable] internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable { #region Private Data Members diff --git a/src/mscorlib/src/System/Reflection/MdImport.cs b/src/mscorlib/src/System/Reflection/MdImport.cs index a224a50513..9230ffa9ef 100644 --- a/src/mscorlib/src/System/Reflection/MdImport.cs +++ b/src/mscorlib/src/System/Reflection/MdImport.cs @@ -20,7 +20,6 @@ using System.Diagnostics.Contracts; namespace System.Reflection { - [Serializable] internal enum CorElementType : byte { End = 0x00, @@ -61,7 +60,6 @@ namespace System.Reflection Pinned = 0x45, } - [Serializable] [Flags()] internal enum MdSigCallingConvention : byte { @@ -85,7 +83,6 @@ namespace System.Reflection } - [Serializable] [Flags()] internal enum PInvokeAttributes { @@ -122,7 +119,6 @@ namespace System.Reflection } - [Serializable] [Flags()] internal enum MethodSemanticsAttributes { @@ -135,7 +131,6 @@ namespace System.Reflection } - [Serializable] internal enum MetadataTokenType { Module = 0x00000000, @@ -166,7 +161,6 @@ namespace System.Reflection Invalid = 0x7FFFFFFF, } - [Serializable] internal struct ConstArray { public IntPtr Signature { get { return m_constArray; } } @@ -191,7 +185,6 @@ namespace System.Reflection internal IntPtr m_constArray; } - [Serializable] internal struct MetadataToken { #region Implicit Cast Operators diff --git a/src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs b/src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs deleted file mode 100644 index d25c746a85..0000000000 --- a/src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Text; -using System.Reflection; -using System.Diagnostics; -using System.Collections.Generic; - -namespace System -{ - internal static class MemberSerializationStringGenerator - { - // - // Generate the "Signature2" binary serialization string for PropertyInfos - // - // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing - // metadata prevents generating the string, this method throws a MissingMetadata exception. - // - public static string SerializationToString(this PropertyInfo property) => ((RuntimePropertyInfo)property).SerializationToString(); - - // - // Generate the "Signature2" binary serialization string for ConstructorInfos - // - // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing - // metadata prevents generating the string, this method throws a MissingMetadata exception. - // - public static string SerializationToString(this ConstructorInfo constructor) => ((RuntimeConstructorInfo)constructor).SerializationToString(); - - // - // Generate the "Signature2" binary serialization string for MethodInfos - // - // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing - // metadata prevents generating the string, this method throws a MissingMetadata exception. - // - public static string SerializationToString(this MethodInfo method) => ((RuntimeMethodInfo)method).SerializationToString(); - } -} diff --git a/src/mscorlib/src/System/Reflection/RtFieldInfo.cs b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs index 20d6e6392f..ddfc56b2aa 100644 --- a/src/mscorlib/src/System/Reflection/RtFieldInfo.cs +++ b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs @@ -11,7 +11,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection { - [Serializable] internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo { #region FCalls diff --git a/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs index 4632525453..6737190c1c 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs @@ -18,7 +18,6 @@ using System.Diagnostics.Contracts; namespace System.Reflection { - [Serializable] internal class RuntimeAssembly : Assembly { #if FEATURE_APPX @@ -261,15 +260,7 @@ namespace System.Reflection // ISerializable implementation public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - - Contract.EndContractBlock(); - - UnitySerializationHolder.GetUnitySerializationInfo(info, - UnitySerializationHolder.AssemblyUnity, - this.FullName, - this); + throw new PlatformNotSupportedException(); } public override Module ManifestModule @@ -320,26 +311,6 @@ namespace System.Reflection return CustomAttributeData.GetCustomAttributesInternal(this); } - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - internal static RuntimeAssembly InternalLoadFrom(String assemblyFile, - Evidence securityEvidence, - byte[] hashValue, - AssemblyHashAlgorithm hashAlgorithm, - bool forIntrospection, - ref StackCrawlMark stackMark) - { - if (assemblyFile == null) - throw new ArgumentNullException(nameof(assemblyFile)); - - Contract.EndContractBlock(); - - AssemblyName an = new AssemblyName(); - an.CodeBase = assemblyFile; - an.SetHashControl(hashValue, hashAlgorithm); - // The stack mark is used for MDA filtering - return InternalLoadAssemblyName(an, securityEvidence, null, ref stackMark, true /*thrownOnFileNotFound*/, forIntrospection); - } - // Wrapper function to wrap the typical use of InternalLoad. internal static RuntimeAssembly InternalLoad(String assemblyString, Evidence assemblySecurity, diff --git a/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs index 8c3b1fce98..e0fb3ec87d 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs @@ -11,7 +11,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection { - [Serializable] internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo { #region Private Data Members @@ -465,10 +464,7 @@ namespace System.Reflection #region ISerializable Implementation public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - MemberInfoSerializationHolder.GetSerializationInfo(info, this); + throw new PlatformNotSupportedException(); } internal string SerializationToString() diff --git a/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs index 930e1820bd..9e86867b6d 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs @@ -10,7 +10,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection { - [Serializable] internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable { #region Private Data Members @@ -159,11 +158,7 @@ namespace System.Reflection #region ISerializable public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - MemberInfoSerializationHolder.GetSerializationInfo(info, this); + throw new PlatformNotSupportedException(); } #endregion diff --git a/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs index 29cc97d225..e61c0922d7 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs @@ -9,7 +9,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection { - [Serializable] internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable { #region Private Data Members @@ -125,11 +124,7 @@ namespace System.Reflection #region ISerializable Implementation public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - MemberInfoSerializationHolder.GetSerializationInfo(info, this); + throw new PlatformNotSupportedException(); } #endregion } diff --git a/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs index b8a2341e4e..3b2a75b1b7 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs @@ -14,7 +14,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection { - [Serializable] internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo { #region Private Data Members @@ -772,14 +771,7 @@ namespace System.Reflection #region ISerializable Implementation public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - if (m_reflectedTypeCache.IsGlobal) - throw new NotSupportedException(SR.NotSupported_GlobalMethodSerialization); - - MemberInfoSerializationHolder.GetSerializationInfo(info, this); + throw new PlatformNotSupportedException(); } internal string SerializationToString() diff --git a/src/mscorlib/src/System/Reflection/RuntimeModule.cs b/src/mscorlib/src/System/Reflection/RuntimeModule.cs index 75809cba01..f9b733736d 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeModule.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeModule.cs @@ -12,7 +12,6 @@ using System.Diagnostics.Contracts; namespace System.Reflection { - [Serializable] internal class RuntimeModule : Module { internal RuntimeModule() { throw new NotSupportedException(); } @@ -448,12 +447,7 @@ namespace System.Reflection #region Public Virtuals public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); - UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly()); + throw new PlatformNotSupportedException(); } public override Type GetType(String className, bool throwOnError, bool ignoreCase) diff --git a/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs index addf68e75d..d21af03649 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs @@ -11,7 +11,6 @@ using MdToken = System.Reflection.MetadataToken; namespace System.Reflection { - [Serializable] internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable { #region Static Members @@ -164,35 +163,7 @@ namespace System.Reflection #region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints. public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // We could be serializing for consumption by a pre-Whidbey - // endpoint. Therefore we set up all the serialized fields to look - // just like a v1.0/v1.1 instance. - - // Need to set the type to ParameterInfo so that pre-Whidbey and Whidbey code - // can deserialize this. This is also why we cannot simply use [OnSerializing]. - info.SetType(typeof(ParameterInfo)); - - // Use the properties intead of the fields in case the fields haven't been et - // _importer, bExtraConstChecked, and m_cachedData don't need to be set - - // Now set the legacy fields that the current implementation doesn't - // use any more. Note that _importer is a raw pointer that should - // never have been serialized in V1. We set it to zero here; if the - // deserializer uses it (by calling GetCustomAttributes() on this - // instance) they'll AV, but at least it will be a well defined - // exception and not a random AV. - - info.AddValue("AttrsImpl", Attributes); - info.AddValue("ClassImpl", ParameterType); - info.AddValue("DefaultValueImpl", DefaultValue); - info.AddValue("MemberImpl", Member); - info.AddValue("NameImpl", Name); - info.AddValue("PositionImpl", Position); - info.AddValue("_token", m_tkParamDef); + throw new PlatformNotSupportedException(); } #endregion diff --git a/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs b/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs index b6a4792e4f..24f6de1e77 100644 --- a/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs @@ -12,7 +12,6 @@ using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection { - [Serializable] internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable { #region Private Data Members @@ -451,11 +450,7 @@ namespace System.Reflection #region ISerializable Implementation public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - MemberInfoSerializationHolder.GetSerializationInfo(info, this); + throw new PlatformNotSupportedException(); } internal string SerializationToString() diff --git a/src/mscorlib/src/System/Resources/ResourceManager.cs b/src/mscorlib/src/System/Resources/ResourceManager.cs index 993efddbfc..e3981481f7 100644 --- a/src/mscorlib/src/System/Resources/ResourceManager.cs +++ b/src/mscorlib/src/System/Resources/ResourceManager.cs @@ -149,7 +149,6 @@ namespace System.Resources // is one such example. // - [Serializable] public class ResourceManager { internal class CultureNameResourceSetPair diff --git a/src/mscorlib/src/System/Resources/ResourceSet.cs b/src/mscorlib/src/System/Resources/ResourceSet.cs index 8775f6411a..b4029a7e9c 100644 --- a/src/mscorlib/src/System/Resources/ResourceSet.cs +++ b/src/mscorlib/src/System/Resources/ResourceSet.cs @@ -13,25 +13,25 @@ ** ===========================================================*/ +using System; +using System.Collections; +using System.IO; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Versioning; +using System.Diagnostics.Contracts; +using System.Collections.Generic; + namespace System.Resources { - using System; - using System.Collections; - using System.IO; - using System.Globalization; - using System.Runtime.InteropServices; - using System.Reflection; - using System.Runtime.Serialization; - using System.Runtime.Versioning; - using System.Diagnostics.Contracts; - // A ResourceSet stores all the resources defined in one particular CultureInfo. // // The method used to load resources is straightforward - this class // enumerates over an IResourceReader, loading every name and value, and // stores them in a hash table. Custom IResourceReaders can be used. - // - [Serializable] + // public class ResourceSet : IDisposable, IEnumerable { [NonSerialized] protected IResourceReader Reader; @@ -39,11 +39,6 @@ namespace System.Resources private Hashtable _caseInsensitiveTable; // For case-insensitive lookups. -#if LOOSELY_LINKED_RESOURCE_REFERENCE - [OptionalField] - private Assembly _assembly; // For LooselyLinkedResourceReferences -#endif // LOOSELY_LINKED_RESOURCE_REFERENCE - protected ResourceSet() { // To not inconvenience people subclassing us, we should allocate a new @@ -68,16 +63,6 @@ namespace System.Resources ReadResources(); } -#if LOOSELY_LINKED_RESOURCE_REFERENCE - public ResourceSet(String fileName, Assembly assembly) - { - Reader = new ResourceReader(fileName); - CommonInit(); - _assembly = assembly; - ReadResources(); - } -#endif // LOOSELY_LINKED_RESOURCE_REFERENCE - // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to read from an open stream // of data. @@ -89,16 +74,6 @@ namespace System.Resources ReadResources(); } -#if LOOSELY_LINKED_RESOURCE_REFERENCE - public ResourceSet(Stream stream, Assembly assembly) - { - Reader = new ResourceReader(stream); - CommonInit(); - _assembly = assembly; - ReadResources(); - } -#endif // LOOSELY_LINKED_RESOURCE_REFERENCE - public ResourceSet(IResourceReader reader) { if (reader == null) @@ -109,19 +84,6 @@ namespace System.Resources ReadResources(); } -#if LOOSELY_LINKED_RESOURCE_REFERENCE - public ResourceSet(IResourceReader reader, Assembly assembly) - { - if (reader == null) - throw new ArgumentNullException(nameof(reader)); - Contract.EndContractBlock(); - Reader = reader; - CommonInit(); - _assembly = assembly; - ReadResources(); - } -#endif // LOOSELY_LINKED_RESOURCE_REFERENCE - private void CommonInit() { Table = new Hashtable(); @@ -156,15 +118,6 @@ namespace System.Resources Dispose(true); } -#if LOOSELY_LINKED_RESOURCE_REFERENCE - // Optional - used for resolving assembly manifest resource references. - // This can safely be null. - public Assembly Assembly { - get { return _assembly; } - /*protected*/ set { _assembly = value; } - } -#endif // LOOSELY_LINKED_RESOURCE_REFERENCE - // Returns the preferred IResourceReader class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. @@ -178,7 +131,8 @@ namespace System.Resources // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultWriter() { - return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, throwOnError: true); + Assembly resourceWriterAssembly = Assembly.Load("System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); + return resourceWriterAssembly.GetType("System.Resources.ResourceWriter", true); } public virtual IDictionaryEnumerator GetEnumerator() @@ -271,12 +225,6 @@ namespace System.Resources while (en.MoveNext()) { Object value = en.Value; -#if LOOSELY_LINKED_RESOURCE_REFERENCE - if (Assembly != null && value is LooselyLinkedResourceReference) { - LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value; - value = assRef.Resolve(Assembly); - } -#endif //LOOSELYLINKEDRESOURCEREFERENCE Table.Add(en.Key, value); } // While technically possible to close the Reader here, don't close it @@ -308,10 +256,6 @@ namespace System.Resources if (caseTable == null) { caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase); -#if _DEBUG - //Console.WriteLine("ResourceSet::GetObject loading up case-insensitive data"); - BCLDebug.Perf(false, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing " + name + " correctly in your source"); -#endif IDictionaryEnumerator en = copyOfTable.GetEnumerator(); while (en.MoveNext()) diff --git a/src/mscorlib/src/System/RtType.cs b/src/mscorlib/src/System/RtType.cs index ef3ba29787..68b9f5a75b 100644 --- a/src/mscorlib/src/System/RtType.cs +++ b/src/mscorlib/src/System/RtType.cs @@ -23,7 +23,6 @@ using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Security; using System.Text; -using System.Runtime.Remoting; using MdSigCallingConvention = System.Signature.MdSigCallingConvention; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; using System.Runtime.InteropServices; @@ -72,7 +71,6 @@ namespace System FullName, } - [Serializable] internal class RuntimeType : System.Reflection.TypeInfo, ISerializable, ICloneable { @@ -1200,7 +1198,7 @@ namespace System { string name = eventInfo.Name; - if (csEventInfos.GetValueOrDefault(name) != null) + if (csEventInfos.ContainsKey(name)) continue; csEventInfos[name] = eventInfo; @@ -1355,10 +1353,8 @@ namespace System if (csPropertyInfos != null) { string name = propertyInfo.Name; - - List<RuntimePropertyInfo> cache = csPropertyInfos.GetValueOrDefault(name); - - if (cache == null) + List<RuntimePropertyInfo> cache; + if (!csPropertyInfos.TryGetValue(name, out cache)) { cache = new List<RuntimePropertyInfo>(1); csPropertyInfos[name] = cache; @@ -3792,6 +3788,11 @@ namespace System #endregion #region Misc + public override bool IsTypeDefinition + { + get { return RuntimeTypeHandle.IsTypeDefinition(this); } + } + public override Type MakePointerType() { return new RuntimeTypeHandle(this).MakePointer(); } public override Type MakeByRefType() { return new RuntimeTypeHandle(this).MakeByRef(); } public override Type MakeArrayType() { return new RuntimeTypeHandle(this).MakeSZArray(); } @@ -4444,11 +4445,7 @@ namespace System #region ISerializable public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - UnitySerializationHolder.GetUnitySerializationInfo(info, this); + throw new PlatformNotSupportedException(); } #endregion @@ -4908,7 +4905,6 @@ namespace System // method (RuntimeType) and an instance of this type will work around the reason to have this type in the // first place. However given RuntimeType is not public all its methods are protected and require full trust // to be accessed - [Serializable] internal class ReflectionOnlyType : RuntimeType { private ReflectionOnlyType() { } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs index f32cc2b510..6c6f6ee472 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs @@ -651,16 +651,10 @@ namespace System.Runtime.CompilerServices int bucket = hashCode & (_buckets.Length - 1); for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next) { - if (_entries[entriesIndex].HashCode == hashCode) + if (_entries[entriesIndex].HashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out value) == key) { - object primary, secondary; - _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary); - if (primary == key) - { - GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. - value = secondary; - return entriesIndex; - } + GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. + return entriesIndex; } } @@ -677,7 +671,7 @@ namespace System.Runtime.CompilerServices if (index < _entries.Length) { object oKey, oValue; - _entries[index].depHnd.GetPrimaryAndSecondary(out oKey, out oValue); + oKey = _entries[index].depHnd.GetPrimaryAndSecondary(out oValue); GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. if (oKey != null) @@ -921,8 +915,8 @@ namespace System.Runtime.CompilerServices { for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next) { - object primary = null, secondary = null; - _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary); + object primary, secondary; + primary = _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out secondary); // Now that we've secured a strong reference to the secondary, must check the primary again // to ensure it didn't expire (otherwise, we open a race where TryGetValue misreports an @@ -951,7 +945,7 @@ namespace System.Runtime.CompilerServices } object thisKey, thisValue; - _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue); + thisKey = _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisValue); if (Equals(thisKey, key)) { GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. @@ -1069,10 +1063,8 @@ namespace System.Runtime.CompilerServices #region Constructors public DependentHandle(object primary, object secondary) { - IntPtr handle = (IntPtr)0; - nInitialize(primary, secondary, out handle); // no need to check for null result: nInitialize expected to throw OOM. - _handle = handle; + _handle = nInitialize(primary, secondary); } #endregion @@ -1084,14 +1076,12 @@ namespace System.Runtime.CompilerServices // primary. public object GetPrimary() { - object primary; - nGetPrimary(_handle, out primary); - return primary; + return nGetPrimary(_handle); } - public void GetPrimaryAndSecondary(out object primary, out object secondary) + public object GetPrimaryAndSecondary(out object secondary) { - nGetPrimaryAndSecondary(_handle, out primary, out secondary); + return nGetPrimaryAndSecondary(_handle, out secondary); } public void SetPrimary(object primary) @@ -1121,13 +1111,13 @@ namespace System.Runtime.CompilerServices #region Private Members [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void nInitialize(object primary, object secondary, out IntPtr dependentHandle); + private static extern IntPtr nInitialize(object primary, object secondary); [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void nGetPrimary(IntPtr dependentHandle, out object primary); + private static extern object nGetPrimary(IntPtr dependentHandle); [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void nGetPrimaryAndSecondary(IntPtr dependentHandle, out object primary, out object secondary); + private static extern object nGetPrimaryAndSecondary(IntPtr dependentHandle, out object secondary); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void nSetPrimary(IntPtr dependentHandle, object primary); diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs index 8f4c79cd94..7393bb2bcd 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs @@ -7,7 +7,6 @@ using System.Collections.Generic; namespace System.Runtime.CompilerServices { - [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public abstract class CustomConstantAttribute : Attribute { diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs index 7aca42b627..5155d0085d 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs @@ -7,7 +7,6 @@ using System.Diagnostics.Contracts; namespace System.Runtime.CompilerServices { - [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DateTimeConstantAttribute : CustomConstantAttribute { diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs index 0e2b6f8418..f5fd5a21a3 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs @@ -12,7 +12,6 @@ using System.Collections.Generic; namespace System.Runtime.CompilerServices { - [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DecimalConstantAttribute : Attribute { diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs index b24018cf78..3c19ee8863 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs @@ -12,7 +12,6 @@ namespace System.Runtime.CompilerServices // certain method properties. // Custom attribute to specify additional method properties. - [Serializable] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] sealed public class MethodImplAttribute : Attribute { diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs index c050000169..df52f301e4 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs @@ -13,12 +13,10 @@ using System; using System.Runtime.Serialization; -using System.Runtime.Remoting; using System.Diagnostics.Contracts; namespace System.Runtime.CompilerServices { - [Serializable] public sealed class RuntimeWrappedException : Exception { private RuntimeWrappedException(Object thrownObject) @@ -37,19 +35,7 @@ namespace System.Runtime.CompilerServices public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); base.GetObjectData(info, context); - info.AddValue("WrappedException", m_wrappedException, typeof(Object)); - } - - internal RuntimeWrappedException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - m_wrappedException = info.GetValue("WrappedException", typeof(Object)); } } } diff --git a/src/mscorlib/src/System/Runtime/GcSettings.cs b/src/mscorlib/src/System/Runtime/GcSettings.cs index 993a24f986..ecb28e6034 100644 --- a/src/mscorlib/src/System/Runtime/GcSettings.cs +++ b/src/mscorlib/src/System/Runtime/GcSettings.cs @@ -13,14 +13,12 @@ namespace System.Runtime // These settings are the same format as in clr\src\vm\gcpriv.h // make sure you change that file if you change this file! - [Serializable] public enum GCLargeObjectHeapCompactionMode { Default = 1, CompactOnce = 2 } - [Serializable] public enum GCLatencyMode { Batch = 0, diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs index c4beb024b1..e009db277f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs @@ -9,7 +9,6 @@ using System.Runtime.Versioning; namespace System.Runtime.InteropServices { - [Serializable] public struct ArrayWithOffset { //private ArrayWithOffset() diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs index ccba51e840..668358995b 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs @@ -46,7 +46,6 @@ namespace System.Runtime.InteropServices public int Value { get { return _val; } } } - [Serializable] public enum ComInterfaceType { InterfaceIsDual = 0, @@ -84,7 +83,6 @@ namespace System.Runtime.InteropServices public Type Value { get { return _val; } } } - [Serializable] public enum ClassInterfaceType { None = 0, diff --git a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs index 77c38139cd..586b03b366 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs @@ -17,7 +17,6 @@ using System.Security; namespace System.Runtime.InteropServices { - [Serializable] public sealed class BStrWrapper { public BStrWrapper(String value) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs index 889a74f6bc..8ee10ed349 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs @@ -22,7 +22,6 @@ namespace System.Runtime.InteropServices { // Exception for COM Interop errors where we don't recognize the HResult. // - [Serializable] public class COMException : ExternalException { public COMException() @@ -51,6 +50,7 @@ namespace System.Runtime.InteropServices protected COMException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } public override String ToString() diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs index 8198d9fd18..fe69f619fe 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs @@ -99,7 +99,6 @@ // code:ComEventsMethod.Invoke using System; -using System.Runtime.Remoting; namespace System.Runtime.InteropServices { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs index ea99781975..2de01465d3 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs @@ -9,7 +9,6 @@ using System; namespace System.Runtime.InteropServices { - [Serializable] public enum ComMemberType { Method = 0, diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs index 967746f379..ae403d138c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs @@ -15,7 +15,6 @@ using System; namespace System.Runtime.InteropServices.ComTypes { - [Serializable] public enum DESCKIND { DESCKIND_NONE = 0, diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs index 1857fdbb35..4cd102f76e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs @@ -15,7 +15,6 @@ using System; namespace System.Runtime.InteropServices.ComTypes { - [Serializable] public enum TYPEKIND { TKIND_ENUM = 0, @@ -29,7 +28,6 @@ namespace System.Runtime.InteropServices.ComTypes TKIND_MAX = TKIND_UNION + 1 } - [Serializable] [Flags()] public enum TYPEFLAGS : short { @@ -50,7 +48,6 @@ namespace System.Runtime.InteropServices.ComTypes TYPEFLAG_FPROXY = 0x4000 } - [Serializable] [Flags()] public enum IMPLTYPEFLAGS { @@ -106,7 +103,6 @@ namespace System.Runtime.InteropServices.ComTypes public Int16 wFuncFlags; //WORD wFuncFlags; } - [Serializable] [Flags()] public enum IDLFLAG : short { @@ -125,7 +121,6 @@ namespace System.Runtime.InteropServices.ComTypes public IDLFLAG wIDLFlags; } - [Serializable] [Flags()] public enum PARAMFLAG : short { @@ -173,7 +168,6 @@ namespace System.Runtime.InteropServices.ComTypes public DESCUNION desc; } - [Serializable] public enum VARKIND : int { VAR_PERINSTANCE = 0x0, @@ -231,7 +225,6 @@ namespace System.Runtime.InteropServices.ComTypes public Int32 scode; } - [Serializable] public enum FUNCKIND : int { FUNC_VIRTUAL = 0, @@ -241,7 +234,6 @@ namespace System.Runtime.InteropServices.ComTypes FUNC_DISPATCH = 4 } - [Serializable] [Flags] public enum INVOKEKIND : int { @@ -251,7 +243,6 @@ namespace System.Runtime.InteropServices.ComTypes INVOKE_PROPERTYPUTREF = 0x8 } - [Serializable] public enum CALLCONV : int { CC_CDECL = 1, @@ -266,7 +257,6 @@ namespace System.Runtime.InteropServices.ComTypes CC_MAX = 9 } - [Serializable] [Flags()] public enum FUNCFLAGS : short { @@ -285,7 +275,6 @@ namespace System.Runtime.InteropServices.ComTypes FUNCFLAG_FIMMEDIATEBIND = 0x1000 } - [Serializable] [Flags()] public enum VARFLAGS : short { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs index 3ed6e42d08..05a9e3f176 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs @@ -15,7 +15,6 @@ using System; namespace System.Runtime.InteropServices.ComTypes { - [Serializable] public enum SYSKIND { SYS_WIN16 = 0, @@ -24,7 +23,6 @@ namespace System.Runtime.InteropServices.ComTypes SYS_WIN64 = SYS_MAC + 1 } - [Serializable] [Flags()] public enum LIBFLAGS : short { @@ -35,7 +33,6 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - [Serializable] public struct TYPELIBATTR { public Guid guid; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs index 4b436825e8..590925aafe 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs @@ -16,7 +16,6 @@ using System; namespace System.Runtime.InteropServices { - [Serializable] public sealed class CurrencyWrapper { public CurrencyWrapper(Decimal obj) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs index 87ec4ed15e..5fb78c56ad 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs @@ -17,7 +17,6 @@ using System.Security; namespace System.Runtime.InteropServices { - [Serializable] public sealed class DispatchWrapper { public DispatchWrapper(Object obj) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs index 73be2c5777..34237d539a 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs @@ -16,7 +16,6 @@ using System; namespace System.Runtime.InteropServices { - [Serializable] public sealed class ErrorWrapper { public ErrorWrapper(int errorCode) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs index dcb9e24258..2ee81a9f5c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs @@ -18,7 +18,6 @@ namespace System.Runtime.InteropServices // IMPORTANT: These must match the definitions in ObjectHandle.h in the EE. // IMPORTANT: If new values are added to the enum the GCHandle::MaxHandleType // constant must be updated. - [Serializable] public enum GCHandleType { Weak = 0, diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs index 4f4b10bbf0..f0aa35e7dd 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs @@ -19,7 +19,6 @@ namespace System.Runtime.InteropServices //==================================================================== // The enum of the return value of IQuerable.GetInterface //==================================================================== - [Serializable] public enum CustomQueryInterfaceResult { Handled = 0, diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs index 2fae2b6e52..bf89df94bb 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs @@ -17,7 +17,6 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { - [Serializable] public class InvalidComObjectException : SystemException { public InvalidComObjectException() @@ -40,6 +39,7 @@ namespace System.Runtime.InteropServices protected InvalidComObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs index 5154a028ad..412853920e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs @@ -16,7 +16,6 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { - [Serializable] public class InvalidOleVariantTypeException : SystemException { public InvalidOleVariantTypeException() @@ -39,6 +38,7 @@ namespace System.Runtime.InteropServices protected InvalidOleVariantTypeException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs index 6fb631121b..03750bcb8b 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs @@ -15,13 +15,13 @@ namespace System.Runtime.InteropServices { using System; + using System.Runtime; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Security; using System.Text; using System.Threading; - using System.Runtime.Remoting; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.ConstrainedExecution; @@ -31,8 +31,8 @@ namespace System.Runtime.InteropServices using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices.ComTypes; + using System.StubHelpers; - [Serializable] public enum CustomQueryInterfaceMode { Ignore = 0, @@ -406,9 +406,9 @@ namespace System.Runtime.InteropServices //==================================================================== // Read from memory //==================================================================== - public static byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) + public static byte ReadByte(Object ptr, int ofs) { - throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 + return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadByte(nativeHome, offset)); } public static unsafe byte ReadByte(IntPtr ptr, int ofs) @@ -430,9 +430,9 @@ namespace System.Runtime.InteropServices return ReadByte(ptr, 0); } - public static short ReadInt16([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) + public static short ReadInt16(Object ptr, int ofs) { - throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 + return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt16(nativeHome, offset)); } public static unsafe short ReadInt16(IntPtr ptr, int ofs) @@ -467,9 +467,9 @@ namespace System.Runtime.InteropServices return ReadInt16(ptr, 0); } - public static int ReadInt32([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) + public static int ReadInt32(object ptr, int ofs) { - throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 + return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt32(nativeHome, offset)); } public static unsafe int ReadInt32(IntPtr ptr, int ofs) @@ -506,7 +506,7 @@ namespace System.Runtime.InteropServices return ReadInt32(ptr, 0); } - public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) + public static IntPtr ReadIntPtr(Object ptr, int ofs) { #if BIT64 return (IntPtr)ReadInt64(ptr, ofs); @@ -535,7 +535,7 @@ namespace System.Runtime.InteropServices public static long ReadInt64([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) { - throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 + return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt64(nativeHome, offset)); } public static unsafe long ReadInt64(IntPtr ptr, int ofs) @@ -576,6 +576,41 @@ namespace System.Runtime.InteropServices return ReadInt64(ptr, 0); } + //==================================================================== + // Read value from marshaled object (marshaled using AsAny) + // It's quite slow and can return back dangling pointers + // It's only there for backcompact + // I don't think we should spend time optimizing it + // People should really call the IntPtr overload instead + //==================================================================== + private static unsafe T ReadValueSlow<T>(object ptr, int ofs, Func<IntPtr, int, T> readValueHelper) + { + // We AV on desktop if passing NULL. So this is technically a breaking change but is an improvement + if (ptr == null) + throw new ArgumentNullException(nameof(ptr)); + + int dwFlags = + (int)AsAnyMarshaler.AsAnyFlags.In | + (int)AsAnyMarshaler.AsAnyFlags.IsAnsi | + (int)AsAnyMarshaler.AsAnyFlags.IsBestFit; + + MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState(); + AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState)); + + IntPtr pNativeHome = IntPtr.Zero; + + try + { + pNativeHome = marshaler.ConvertToNative(ptr, dwFlags); + return readValueHelper(pNativeHome, ofs); + } + finally + { + marshaler.ClearNative(pNativeHome); + } + } + + //==================================================================== // Write to memory @@ -594,9 +629,9 @@ namespace System.Runtime.InteropServices } } - public static void WriteByte([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, byte val) + public static void WriteByte(Object ptr, int ofs, byte val) { - throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 + WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, byte value) => Marshal.WriteByte(nativeHome, offset, value)); } public static void WriteByte(IntPtr ptr, byte val) @@ -629,9 +664,9 @@ namespace System.Runtime.InteropServices } } - public static void WriteInt16([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, short val) + public static void WriteInt16(Object ptr, int ofs, short val) { - throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 + WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, short value) => Marshal.WriteInt16(nativeHome, offset, value)); } public static void WriteInt16(IntPtr ptr, short val) @@ -681,9 +716,9 @@ namespace System.Runtime.InteropServices } } - public static void WriteInt32([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, int val) + public static void WriteInt32(Object ptr, int ofs, int val) { - throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 + WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, int value) => Marshal.WriteInt32(nativeHome, offset, value)); } public static void WriteInt32(IntPtr ptr, int val) @@ -700,7 +735,7 @@ namespace System.Runtime.InteropServices #endif } - public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, IntPtr val) + public static void WriteIntPtr(Object ptr, int ofs, IntPtr val) { #if BIT64 WriteInt64(ptr, ofs, (long)val); @@ -749,9 +784,9 @@ namespace System.Runtime.InteropServices } } - public static void WriteInt64([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, long val) + public static void WriteInt64(Object ptr, int ofs, long val) { - throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442 + WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, long value) => Marshal.WriteInt64(nativeHome, offset, value)); } public static void WriteInt64(IntPtr ptr, long val) @@ -759,6 +794,41 @@ namespace System.Runtime.InteropServices WriteInt64(ptr, 0, val); } + //==================================================================== + // Write value into marshaled object (marshaled using AsAny) and + // propagate the value back + // It's quite slow and is only there for backcompact + // I don't think we should spend time optimizing it + // People should really call the IntPtr overload instead + //==================================================================== + private static unsafe void WriteValueSlow<T>(object ptr, int ofs, T val, Action<IntPtr, int, T> writeValueHelper) + { + // We AV on desktop if passing NULL. So this is technically a breaking change but is an improvement + if (ptr == null) + throw new ArgumentNullException(nameof(ptr)); + + int dwFlags = + (int)AsAnyMarshaler.AsAnyFlags.In | + (int)AsAnyMarshaler.AsAnyFlags.Out | + (int)AsAnyMarshaler.AsAnyFlags.IsAnsi | + (int)AsAnyMarshaler.AsAnyFlags.IsBestFit; + + MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState(); + AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState)); + + IntPtr pNativeHome = IntPtr.Zero; + + try + { + pNativeHome = marshaler.ConvertToNative(ptr, dwFlags); + writeValueHelper(pNativeHome, ofs, val); + marshaler.ConvertToManaged(ptr, pNativeHome); + } + finally + { + marshaler.ClearNative(pNativeHome); + } + } //==================================================================== // GetLastWin32Error @@ -1772,11 +1842,7 @@ namespace System.Runtime.InteropServices } Contract.EndContractBlock(); -#if FEATURE_COMINTEROP return s.MarshalToBSTR(); -#else - throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10443 -#endif } public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) @@ -1800,30 +1866,28 @@ namespace System.Runtime.InteropServices return s.MarshalToString(globalAlloc: false, unicode: true); } - -#if FEATURE_COMINTEROP + public static void ZeroFreeBSTR(IntPtr s) { - Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2)); + RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2)); FreeBSTR(s); } -#endif public static void ZeroFreeCoTaskMemAnsi(IntPtr s) { - Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s))); + RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s))); FreeCoTaskMem(s); } public static void ZeroFreeCoTaskMemUnicode(IntPtr s) { - Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2)); + RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2)); FreeCoTaskMem(s); } unsafe public static void ZeroFreeCoTaskMemUTF8(IntPtr s) { - Win32Native.ZeroMemory(s, (UIntPtr)System.StubHelpers.StubHelpers.strlen((sbyte*)s)); + RuntimeImports.RhZeroMemory(s, (UIntPtr)System.StubHelpers.StubHelpers.strlen((sbyte*)s)); FreeCoTaskMem(s); } @@ -1851,13 +1915,13 @@ namespace System.Runtime.InteropServices public static void ZeroFreeGlobalAllocAnsi(IntPtr s) { - Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s))); + RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s))); FreeHGlobal(s); } public static void ZeroFreeGlobalAllocUnicode(IntPtr s) { - Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2)); + RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2)); FreeHGlobal(s); } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs index 6fe7574e26..75b291af30 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs @@ -17,7 +17,6 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { - [Serializable] public class MarshalDirectiveException : SystemException { public MarshalDirectiveException() @@ -40,6 +39,7 @@ namespace System.Runtime.InteropServices protected MarshalDirectiveException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs index 7b7c5efb90..c79af8b459 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs @@ -171,11 +171,6 @@ namespace System.Runtime.InteropServices { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - - public static void ZeroFreeBSTR(System.IntPtr s) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); - } } public class DispatchWrapper diff --git a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs index ed289fd14b..33f1b5f09c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs @@ -16,7 +16,6 @@ using System; namespace System.Runtime.InteropServices { // This Enum matchs the CorPinvokeMap defined in CorHdr.h - [Serializable] internal enum PInvokeMap { NoMangle = 0x0001, // Pinvoke is to use the member name as specified. diff --git a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMarshal.cs new file mode 100644 index 0000000000..9eb60bdce7 --- /dev/null +++ b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMarshal.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32; + +namespace System.Runtime.InteropServices +{ + internal static class PInvokeMarshal + { + public static IntPtr AllocBSTR(int length) + { + IntPtr bstr = Win32Native.SysAllocStringLen(null, length); + if (bstr == IntPtr.Zero) + throw new OutOfMemoryException(); + return bstr; + } + + public static void FreeBSTR(IntPtr ptr) + { + Win32Native.SysFreeString(ptr); + } + } +} diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs index 5595fadc43..d61e79757c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs @@ -19,7 +19,6 @@ namespace System.Runtime.InteropServices { // Exception for Structured Exception Handler exceptions. // - [Serializable] public class SEHException : ExternalException { public SEHException() @@ -42,6 +41,7 @@ namespace System.Runtime.InteropServices protected SEHException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } // Exceptions can be resumable, meaning a filtered exception diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs index f39f1f3a41..9df858f0b1 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs @@ -16,7 +16,6 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { - [Serializable] public class SafeArrayRankMismatchException : SystemException { public SafeArrayRankMismatchException() @@ -39,6 +38,7 @@ namespace System.Runtime.InteropServices protected SafeArrayRankMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs index 2283263422..4b03691e82 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs @@ -17,7 +17,6 @@ using System.Runtime.Serialization; namespace System.Runtime.InteropServices { - [Serializable] public class SafeArrayTypeMismatchException : SystemException { public SafeArrayTypeMismatchException() @@ -40,6 +39,7 @@ namespace System.Runtime.InteropServices protected SafeArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs index c758ae1b4f..de06cbf1a8 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs @@ -16,7 +16,6 @@ using System; namespace System.Runtime.InteropServices { - [Serializable] public sealed class UnknownWrapper { public UnknownWrapper(Object obj) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs index 50689e08f8..455f0759fe 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs @@ -16,8 +16,6 @@ using System; namespace System.Runtime.InteropServices { - [Serializable] - public sealed class VariantWrapper { public VariantWrapper(Object obj) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs index 4549a407e0..0ed0bb3f7b 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs @@ -21,7 +21,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// </summary> /// <typeparam name="TKey">Type of objects that act as keys.</typeparam> /// <typeparam name="TValue">Type of objects that act as entries / values.</typeparam> - [Serializable] [DebuggerDisplay("Count = {Count}")] internal sealed class ConstantSplittableMap<TKey, TValue> : IMapView<TKey, TValue> { @@ -169,7 +168,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime #region IKeyValuePair Enumerator - [Serializable] internal struct IKeyValuePairEnumerator : IEnumerator<IKeyValuePair<TKey, TValue>> { private KeyValuePair<TKey, TValue>[] _array; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs index 2a34aba717..f2434ce91d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs @@ -9,7 +9,6 @@ using System.Diagnostics; namespace System.Runtime.InteropServices.WindowsRuntime { - [Serializable] [DebuggerDisplay("Count = {Count}")] internal sealed class DictionaryKeyCollection<TKey, TValue> : ICollection<TKey> { @@ -83,7 +82,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // public class DictionaryKeyCollection<TKey, TValue> - [Serializable] internal sealed class DictionaryKeyEnumerator<TKey, TValue> : IEnumerator<TKey> { private readonly IDictionary<TKey, TValue> dictionary; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs index 083b0ffcb1..6be0ddd9f0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs @@ -13,7 +13,6 @@ using System.Runtime.InteropServices.WindowsRuntime; namespace System.Runtime.InteropServices.WindowsRuntime { - [Serializable] [DebuggerDisplay("Count = {Count}")] internal sealed class DictionaryValueCollection<TKey, TValue> : ICollection<TValue> { @@ -91,7 +90,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // public class DictionaryValueCollection<TKey, TValue> - [Serializable] internal sealed class DictionaryValueEnumerator<TKey, TValue> : IEnumerator<TValue> { private readonly IDictionary<TKey, TValue> dictionary; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs index e06364dcae..0900012338 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs @@ -123,7 +123,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // Note: One day we may make these return IReadOnlyCollection<T> - [Serializable] [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryKeyCollection<TKey, TValue> : IEnumerable<TKey> { @@ -178,7 +177,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // public class ReadOnlyDictionaryKeyCollection<TKey, TValue> - [Serializable] internal sealed class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> : IEnumerator<TKey> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; @@ -220,7 +218,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> - [Serializable] [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryValueCollection<TKey, TValue> : IEnumerable<TValue> { @@ -279,7 +276,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // public class ReadOnlyDictionaryValueCollection<TKey, TValue> - [Serializable] internal sealed class ReadOnlyDictionaryValueEnumerator<TKey, TValue> : IEnumerator<TValue> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; diff --git a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs index de8137f1ec..a7bf871a39 100644 --- a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs +++ b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs @@ -71,15 +71,9 @@ namespace System.Runtime.Loader [SuppressUnmanagedCodeSecurity] private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly); - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetLoadedAssembliesInternal(ObjectHandleOnStack assemblies); - public static Assembly[] GetLoadedAssemblies() { - Assembly[] assemblies = null; - GetLoadedAssembliesInternal(JitHelpers.GetObjectHandleOnStack(ref assemblies)); - return assemblies; + return AppDomain.CurrentDomain.GetAssemblies(false); } // These are helpers that can be used by AssemblyLoadContext derivations. diff --git a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs deleted file mode 100644 index e76882d6df..0000000000 --- a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** ObjectHandle wraps object references. A Handle allows a -** marshal by value object to be returned through an -** indirection allowing the caller to control when the -** object is loaded into their domain. -** -** -===========================================================*/ - -using System; -using System.Runtime.InteropServices; - -namespace System.Runtime.Remoting -{ - public class ObjectHandle - { - private Object WrappedObject; - - private ObjectHandle() - { - } - - internal ObjectHandle(Object o) - { - WrappedObject = o; - } - - internal Object Unwrap() - { - return WrappedObject; - } - } -} diff --git a/src/mscorlib/src/System/Runtime/RuntimeImports.cs b/src/mscorlib/src/System/Runtime/RuntimeImports.cs index 16d41d3951..ed0c556575 100644 --- a/src/mscorlib/src/System/Runtime/RuntimeImports.cs +++ b/src/mscorlib/src/System/Runtime/RuntimeImports.cs @@ -8,7 +8,7 @@ using System.Runtime.InteropServices; #if BIT64 using nuint = System.UInt64; #else - using nuint = System.UInt32; +using nuint = System.UInt32; #endif namespace System.Runtime @@ -26,8 +26,13 @@ namespace System.Runtime } } + internal unsafe static void RhZeroMemory(IntPtr p, UIntPtr byteLength) + { + RhZeroMemory((void*)p, (nuint)byteLength); + } + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - extern private unsafe static void RhZeroMemory(byte* b, nuint byteLength); + extern private unsafe static void RhZeroMemory(void* b, nuint byteLength); [MethodImpl(MethodImplOptions.InternalCall)] internal extern unsafe static void RhBulkMoveWithWriteBarrier(ref byte destination, ref byte source, nuint byteCount); diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs index 18139324a3..b49b372b4b 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs @@ -17,7 +17,6 @@ using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Security; -using System.Runtime.Remoting; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs index 7fc3ce27d9..8fb54c79a7 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; using System.Reflection; -using System.Runtime.Remoting; using System.Globalization; using System.Diagnostics; using System.Diagnostics.Contracts; diff --git a/src/mscorlib/src/System/RuntimeHandles.cs b/src/mscorlib/src/System/RuntimeHandles.cs index ab125e741e..ceda5abfee 100644 --- a/src/mscorlib/src/System/RuntimeHandles.cs +++ b/src/mscorlib/src/System/RuntimeHandles.cs @@ -23,7 +23,6 @@ namespace System using System.Diagnostics.Contracts; using StackCrawlMark = System.Threading.StackCrawlMark; - [Serializable] public unsafe struct RuntimeTypeHandle : ISerializable { // Returns handle for interop with EE. The handle is guaranteed to be non-null. @@ -127,6 +126,24 @@ namespace System m_type = type; } + internal static bool IsTypeDefinition(RuntimeType type) + { + CorElementType corElemType = GetCorElementType(type); + if (!((corElemType >= CorElementType.Void && corElemType < CorElementType.Ptr) || + corElemType == CorElementType.ValueType || + corElemType == CorElementType.Class || + corElemType == CorElementType.TypedByRef || + corElemType == CorElementType.I || + corElemType == CorElementType.U || + corElemType == CorElementType.Object)) + return false; + + if (HasInstantiation(type) && !IsGenericTypeDefinition(type)) + return false; + + return true; + } + internal static bool IsPrimitive(RuntimeType type) { CorElementType corElemType = GetCorElementType(type); @@ -653,30 +670,9 @@ namespace System return new MetadataImport(_GetMetadataImport(type), type); } - private RuntimeTypeHandle(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - RuntimeType m = (RuntimeType)info.GetValue("TypeObj", typeof(RuntimeType)); - - m_type = m; - - if (m_type == null) - throw new SerializationException(SR.Serialization_InsufficientState); - } - public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - if (m_type == null) - throw new SerializationException(SR.Serialization_InvalidFieldState); - - info.AddValue("TypeObj", m_type, typeof(RuntimeType)); + throw new PlatformNotSupportedException(); } } @@ -766,7 +762,6 @@ namespace System } } - [Serializable] public unsafe struct RuntimeMethodHandle : ISerializable { // Returns handle for interop with EE. The handle is guaranteed to be non-null. @@ -796,33 +791,9 @@ namespace System } // ISerializable interface - private RuntimeMethodHandle(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - MethodBase m = (MethodBase)info.GetValue("MethodObj", typeof(MethodBase)); - - m_value = m.MethodHandle.m_value; - - if (m_value == null) - throw new SerializationException(SR.Serialization_InsufficientState); - } - public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - if (m_value == null) - throw new SerializationException(SR.Serialization_InvalidFieldState); - - // This is either a RuntimeMethodInfo or a RuntimeConstructorInfo - MethodBase methodInfo = RuntimeType.GetMethodBase(m_value); - - info.AddValue("MethodObj", methodInfo, typeof(MethodBase)); + throw new PlatformNotSupportedException(); } public IntPtr Value @@ -1149,7 +1120,6 @@ namespace System } } - [Serializable] public unsafe struct RuntimeFieldHandle : ISerializable { // Returns handle for interop with EE. The handle is guaranteed to be non-null. @@ -1297,35 +1267,9 @@ namespace System internal static extern void CheckAttributeAccess(RuntimeFieldHandle fieldHandle, RuntimeModule decoratedTarget); // ISerializable interface - private RuntimeFieldHandle(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - FieldInfo f = (RuntimeFieldInfo)info.GetValue("FieldObj", typeof(RuntimeFieldInfo)); - - if (f == null) - throw new SerializationException(SR.Serialization_InsufficientState); - - m_ptr = f.FieldHandle.m_ptr; - - if (m_ptr == null) - throw new SerializationException(SR.Serialization_InsufficientState); - } - public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - if (m_ptr == null) - throw new SerializationException(SR.Serialization_InvalidFieldState); - - RuntimeFieldInfo fldInfo = (RuntimeFieldInfo)RuntimeType.GetFieldInfo(this.GetRuntimeFieldInfo()); - - info.AddValue("FieldObj", fldInfo, typeof(RuntimeFieldInfo)); + throw new PlatformNotSupportedException(); } } diff --git a/src/mscorlib/src/System/SByte.cs b/src/mscorlib/src/System/SByte.cs index 2f1b2da947..9e550936fe 100644 --- a/src/mscorlib/src/System/SByte.cs +++ b/src/mscorlib/src/System/SByte.cs @@ -24,7 +24,7 @@ namespace System public struct SByte : IComparable, IFormattable, IConvertible , IComparable<SByte>, IEquatable<SByte> { - private sbyte m_value; + private sbyte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 127. public const sbyte MaxValue = (sbyte)0x7F; diff --git a/src/mscorlib/src/System/SharedStatics.cs b/src/mscorlib/src/System/SharedStatics.cs index a6a04d9614..5c37f25446 100644 --- a/src/mscorlib/src/System/SharedStatics.cs +++ b/src/mscorlib/src/System/SharedStatics.cs @@ -12,7 +12,6 @@ =============================================================================*/ using System.Threading; -using System.Runtime.Remoting; using System.Security; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; diff --git a/src/mscorlib/src/System/Single.cs b/src/mscorlib/src/System/Single.cs index 1c39df7d94..24e6839be6 100644 --- a/src/mscorlib/src/System/Single.cs +++ b/src/mscorlib/src/System/Single.cs @@ -25,7 +25,7 @@ namespace System public struct Single : IComparable, IFormattable, IConvertible , IComparable<Single>, IEquatable<Single> { - internal float m_value; + private float m_value; // Do not rename (binary serialization) // // Public constants diff --git a/src/mscorlib/src/System/StubHelpers.cs b/src/mscorlib/src/System/StubHelpers.cs index f584ece6fc..716fa06a41 100644 --- a/src/mscorlib/src/System/StubHelpers.cs +++ b/src/mscorlib/src/System/StubHelpers.cs @@ -700,6 +700,17 @@ namespace System.StubHelpers internal static class MngdNativeArrayMarshaler { + // Needs to match exactly with MngdNativeArrayMarshaler in ilmarshalers.h + internal struct MarshalerState + { + IntPtr m_pElementMT; + IntPtr m_Array; + int m_NativeDataValid; + int m_BestFitMap; + int m_ThrowOnUnmappableChar; + short m_vt; + } + [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags); @@ -949,11 +960,21 @@ namespace System.StubHelpers // Cleanup list to be destroyed when clearing the native view (for layouts with SafeHandles). private CleanupWorkList cleanupWorkList; - private static bool IsIn(int dwFlags) { return ((dwFlags & 0x10000000) != 0); } - private static bool IsOut(int dwFlags) { return ((dwFlags & 0x20000000) != 0); } - private static bool IsAnsi(int dwFlags) { return ((dwFlags & 0x00FF0000) != 0); } - private static bool IsThrowOn(int dwFlags) { return ((dwFlags & 0x0000FF00) != 0); } - private static bool IsBestFit(int dwFlags) { return ((dwFlags & 0x000000FF) != 0); } + [Flags] + internal enum AsAnyFlags + { + In = 0x10000000, + Out = 0x20000000, + IsAnsi = 0x00FF0000, + IsThrowOn = 0x0000FF00, + IsBestFit = 0x000000FF + } + + private static bool IsIn(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.In) != 0); } + private static bool IsOut(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.Out) != 0); } + private static bool IsAnsi(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.IsAnsi) != 0); } + private static bool IsThrowOn(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.IsThrowOn) != 0); } + private static bool IsBestFit(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.IsBestFit) != 0); } internal AsAnyMarshaler(IntPtr pvArrayMarshaler) { diff --git a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs index ad88ef4400..f70213f8d6 100644 --- a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs @@ -14,7 +14,6 @@ using System.Diagnostics.Contracts; namespace System.Text { - [Serializable] internal sealed class InternalDecoderBestFitFallback : DecoderFallback { // Our variables diff --git a/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs b/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs index b98ef74ed2..7a8db572d0 100644 --- a/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs @@ -8,7 +8,6 @@ using System.Globalization; namespace System.Text { - [Serializable] public sealed class DecoderExceptionFallback : DecoderFallback { // Construction @@ -99,7 +98,6 @@ namespace System.Text } // Exception for decoding unknown byte sequences. - [Serializable] public sealed class DecoderFallbackException : ArgumentException { private byte[] bytesUnknown = null; @@ -125,6 +123,7 @@ namespace System.Text internal DecoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } public DecoderFallbackException( diff --git a/src/mscorlib/src/System/Text/DecoderFallback.cs b/src/mscorlib/src/System/Text/DecoderFallback.cs index 9311cda585..2a56706b98 100644 --- a/src/mscorlib/src/System/Text/DecoderFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderFallback.cs @@ -13,7 +13,6 @@ using System.Diagnostics.Contracts; namespace System.Text { - [Serializable] public abstract class DecoderFallback { internal bool bIsMicrosoftBestFitFallback = false; diff --git a/src/mscorlib/src/System/Text/DecoderNLS.cs b/src/mscorlib/src/System/Text/DecoderNLS.cs index 6fcfc79140..c2791e9227 100644 --- a/src/mscorlib/src/System/Text/DecoderNLS.cs +++ b/src/mscorlib/src/System/Text/DecoderNLS.cs @@ -21,7 +21,6 @@ namespace System.Text // of Encoding objects. // - [Serializable] internal class DecoderNLS : Decoder, ISerializable { // Remember our encoding @@ -32,21 +31,10 @@ namespace System.Text #region Serialization - // Constructor called by serialization. called during deserialization. - internal DecoderNLS(SerializationInfo info, StreamingContext context) - { - throw new NotSupportedException( - String.Format( - System.Globalization.CultureInfo.CurrentCulture, - SR.NotSupported_TypeCannotDeserialized, this.GetType())); - } - - // ISerializable implementation. called during serialization. + // ISerializable implementation. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - SerializeDecoder(info); - info.AddValue("encoding", this.m_encoding); - info.SetType(typeof(Encoding.DefaultDecoder)); + throw new PlatformNotSupportedException(); } #endregion Serialization diff --git a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs index b27469156d..0eaca3de40 100644 --- a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs @@ -8,7 +8,6 @@ using System.Diagnostics.Contracts; namespace System.Text { - [Serializable] public sealed class DecoderReplacementFallback : DecoderFallback { // Our variables diff --git a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs index eb3165526b..b007f57efe 100644 --- a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs @@ -15,7 +15,6 @@ using System.Diagnostics.Contracts; namespace System.Text { - [Serializable] internal sealed class InternalEncoderBestFitFallback : EncoderFallback { // Our variables diff --git a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs index b75847d1e7..192ab78670 100644 --- a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs @@ -8,7 +8,6 @@ using System.Diagnostics.Contracts; namespace System.Text { - [Serializable] public sealed class EncoderExceptionFallback : EncoderFallback { // Construction @@ -99,7 +98,6 @@ namespace System.Text } } - [Serializable] public sealed class EncoderFallbackException : ArgumentException { private char charUnknown; @@ -125,10 +123,6 @@ namespace System.Text HResult = __HResults.COR_E_ARGUMENT; } - internal EncoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - internal EncoderFallbackException( String message, char charUnknown, int index) : base(message) { diff --git a/src/mscorlib/src/System/Text/EncoderFallback.cs b/src/mscorlib/src/System/Text/EncoderFallback.cs index 410b6f5016..c3b9f47284 100644 --- a/src/mscorlib/src/System/Text/EncoderFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderFallback.cs @@ -10,7 +10,6 @@ using System.Diagnostics.Contracts; namespace System.Text { - [Serializable] public abstract class EncoderFallback { // disable csharp compiler warning #0414: field assigned unused value diff --git a/src/mscorlib/src/System/Text/EncoderNLS.cs b/src/mscorlib/src/System/Text/EncoderNLS.cs index 99a26ca575..8a8c31ee2f 100644 --- a/src/mscorlib/src/System/Text/EncoderNLS.cs +++ b/src/mscorlib/src/System/Text/EncoderNLS.cs @@ -21,7 +21,6 @@ namespace System.Text // of Encoding objects. // - [Serializable] internal class EncoderNLS : Encoder, ISerializable { // Need a place for the last left over character, most of our encodings use this @@ -35,22 +34,10 @@ namespace System.Text #region Serialization - // Constructor called by serialization. called during deserialization. - internal EncoderNLS(SerializationInfo info, StreamingContext context) - { - throw new NotSupportedException( - String.Format( - System.Globalization.CultureInfo.CurrentCulture, - SR.NotSupported_TypeCannotDeserialized, this.GetType())); - } - - // ISerializable implementation. called during serialization. + // ISerializable implementation. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - SerializeEncoder(info); - info.AddValue("encoding", this.m_encoding); - info.AddValue("charLeftOver", this.charLeftOver); - info.SetType(typeof(Encoding.DefaultEncoder)); + throw new PlatformNotSupportedException(); } #endregion Serialization diff --git a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs index 65b807c1bd..a9ce9c10ef 100644 --- a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs @@ -9,7 +9,6 @@ using System.Diagnostics.Contracts; namespace System.Text { - [Serializable] public sealed class EncoderReplacementFallback : EncoderFallback { // Our variables diff --git a/src/mscorlib/src/System/Text/Encoding.cs b/src/mscorlib/src/System/Text/Encoding.cs index 159123495b..88eeb19d24 100644 --- a/src/mscorlib/src/System/Text/Encoding.cs +++ b/src/mscorlib/src/System/Text/Encoding.cs @@ -8,7 +8,6 @@ namespace System.Text using System.Collections; using System.Collections.Generic; using System.Runtime; - using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Globalization; using System.Security; @@ -82,7 +81,6 @@ namespace System.Text // generally executes faster. // - [Serializable] public abstract class Encoding : ICloneable { // For netcore we use UTF8 as default encoding since ANSI isn't available @@ -1409,7 +1407,6 @@ namespace System.Text decoder.ClearMustFlush(); } - [Serializable] internal sealed class DefaultEncoder : Encoder, IObjectReference, ISerializable { private Encoding m_encoding; @@ -1422,60 +1419,16 @@ namespace System.Text m_encoding = encoding; m_hasInitializedEncoding = true; } - - // Constructor called by serialization, have to handle deserializing from Everett - internal DefaultEncoder(SerializationInfo info, StreamingContext context) - { - if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // All we have is our encoding - m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding)); - - try - { - this.m_fallback = (EncoderFallback)info.GetValue("m_fallback", typeof(EncoderFallback)); - this.charLeftOver = (Char)info.GetValue("charLeftOver", typeof(Char)); - } - catch (SerializationException) - { - } - } - - // Just get it from GetEncoding + public Object GetRealObject(StreamingContext context) { - // upon deserialization since the DefaultEncoder implement IObjectReference the - // serialization code tries to do the fixup. The fixup returns another - // IObjectReference (the DefaultEncoder) class and hence so on and on. - // Finally the deserialization logics fails after following maximum references - // unless we short circuit with the following - if (m_hasInitializedEncoding) - { - return this; - } - - Encoder encoder = m_encoding.GetEncoder(); - if (m_fallback != null) - encoder.m_fallback = m_fallback; - if (charLeftOver != (char)0) - { - EncoderNLS encoderNls = encoder as EncoderNLS; - if (encoderNls != null) - encoderNls.charLeftOver = charLeftOver; - } - return encoder; + throw new PlatformNotSupportedException(); } // ISerializable implementation, get data for this object void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - // Any info? - if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // All we have is our encoding - info.AddValue("encoding", m_encoding); + throw new PlatformNotSupportedException(); } // Returns the number of bytes the next call to GetBytes will @@ -1531,7 +1484,6 @@ namespace System.Text } } - [Serializable] internal sealed class DefaultDecoder : Decoder, IObjectReference, ISerializable { private Encoding m_encoding; @@ -1544,55 +1496,15 @@ namespace System.Text m_hasInitializedEncoding = true; } - // Constructor called by serialization, have to handle deserializing from Everett - internal DefaultDecoder(SerializationInfo info, StreamingContext context) - { - // Any info? - if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // All we have is our encoding - m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding)); - - try - { - this.m_fallback = (DecoderFallback)info.GetValue("m_fallback", typeof(DecoderFallback)); - } - catch (SerializationException) - { - m_fallback = null; - } - } - - // Just get it from GetEncoding public Object GetRealObject(StreamingContext context) { - // upon deserialization since the DefaultEncoder implement IObjectReference the - // serialization code tries to do the fixup. The fixup returns another - // IObjectReference (the DefaultEncoder) class and hence so on and on. - // Finally the deserialization logics fails after following maximum references - // unless we short circuit with the following - if (m_hasInitializedEncoding) - { - return this; - } - - Decoder decoder = m_encoding.GetDecoder(); - if (m_fallback != null) - decoder.m_fallback = m_fallback; - - return decoder; + throw new PlatformNotSupportedException(); } - // ISerializable implementation, get data for this object + // ISerializable implementation void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - // Any info? - if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // All we have is our encoding - info.AddValue("encoding", m_encoding); + throw new PlatformNotSupportedException(); } // Returns the number of characters the next call to GetChars will diff --git a/src/mscorlib/src/System/Text/Latin1Encoding.cs b/src/mscorlib/src/System/Text/Latin1Encoding.cs index e456b8533d..3f040b29ad 100644 --- a/src/mscorlib/src/System/Text/Latin1Encoding.cs +++ b/src/mscorlib/src/System/Text/Latin1Encoding.cs @@ -18,7 +18,6 @@ namespace System.Text // Latin1Encoding is a simple override to optimize the GetString version of Latin1Encoding. // because of the best fit cases we can't do this when encoding the string, only when decoding // - [Serializable] internal class Latin1Encoding : EncodingNLS, ISerializable { // Used by Encoding.Latin1 for lazy initialization @@ -30,30 +29,10 @@ namespace System.Text { } - // Constructor called by serialization. - // Note: We use the base GetObjectData however - internal Latin1Encoding(SerializationInfo info, StreamingContext context) : - base(Encoding.ISO_8859_1) - { - // Set up our base, also throws if info was empty - DeserializeEncoding(info, context); - - // Nothing unique to Whidbey for Latin1 - } - - // ISerializable implementation, serialize it as a CodePageEncoding + // ISerializable implementation void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - // Make sure to get the base stuff too This throws if info is null - SerializeEncoding(info, context); - Debug.Assert(info != null, "[Latin1Encoding.GetObjectData] Expected null info to throw"); - - // In Everett this is a CodePageEncoding, so it needs maxCharSize - info.AddValue("CodePageEncoding+maxCharSize", 1); - - // And extras for Everett's wierdness - info.AddValue("CodePageEncoding+m_codePage", this.CodePage); - info.AddValue("CodePageEncoding+dataItem", null); + throw new PlatformNotSupportedException(); } // GetByteCount diff --git a/src/mscorlib/src/System/Text/UTF7Encoding.cs b/src/mscorlib/src/System/Text/UTF7Encoding.cs index 372af0da37..0ac3b66889 100644 --- a/src/mscorlib/src/System/Text/UTF7Encoding.cs +++ b/src/mscorlib/src/System/Text/UTF7Encoding.cs @@ -13,7 +13,6 @@ using System.Diagnostics.Contracts; namespace System.Text { - [Serializable] public class UTF7Encoding : Encoding { private const String base64Chars = @@ -832,7 +831,6 @@ namespace System.Text return charCount; } - [Serializable] // Of all the amazing things... This MUST be Decoder so that our com name // for System.Text.Decoder doesn't change private sealed class Decoder : DecoderNLS, ISerializable @@ -849,32 +847,10 @@ namespace System.Text // base calls reset } - // Constructor called by serialization, have to handle deserializing from Everett - internal Decoder(SerializationInfo info, StreamingContext context) - { - // Any info? - if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // Get common info - this.bits = (int)info.GetValue("bits", typeof(int)); - this.bitCount = (int)info.GetValue("bitCount", typeof(int)); - this.firstByte = (bool)info.GetValue("firstByte", typeof(bool)); - this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding)); - } - // ISerializable implementation, get data for this object void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - // Any info? - if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // Save Whidbey data - info.AddValue("encoding", this.m_encoding); - info.AddValue("bits", this.bits); - info.AddValue("bitCount", this.bitCount); - info.AddValue("firstByte", this.firstByte); + throw new PlatformNotSupportedException(); } public override void Reset() @@ -898,7 +874,6 @@ namespace System.Text } } - [Serializable] // Of all the amazing things... This MUST be Encoder so that our com name // for System.Text.Encoder doesn't change private sealed class Encoder : EncoderNLS, ISerializable @@ -913,30 +888,10 @@ namespace System.Text // base calls reset } - // Constructor called by serialization, have to handle deserializing from Everett - internal Encoder(SerializationInfo info, StreamingContext context) - { - // Any info? - if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // Get common info - this.bits = (int)info.GetValue("bits", typeof(int)); - this.bitCount = (int)info.GetValue("bitCount", typeof(int)); - this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding)); - } - - // ISerializable implementation, get data for this object + // ISerializable implementation void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - // Any info? - if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // Save Whidbey data - info.AddValue("encoding", this.m_encoding); - info.AddValue("bits", this.bits); - info.AddValue("bitCount", this.bitCount); + throw new PlatformNotSupportedException(); } public override void Reset() @@ -959,7 +914,6 @@ namespace System.Text // Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char // and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback. - [Serializable] private sealed class DecoderUTF7Fallback : DecoderFallback { // Construction. Default replacement fallback uses no best fit and ? replacement string diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Unix.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Unix.cs new file mode 100644 index 0000000000..b7cdaa801c --- /dev/null +++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Unix.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace System.Threading +{ + public sealed partial class ThreadPoolBoundHandle + { + private static ThreadPoolBoundHandle BindHandleCore(SafeHandle handle) + { + Debug.Assert(handle != null); + Debug.Assert(!handle.IsClosed); + Debug.Assert(!handle.IsInvalid); + + throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); + } + } +} diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs new file mode 100644 index 0000000000..21c1c5f4a4 --- /dev/null +++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs @@ -0,0 +1,42 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace System.Threading +{ + public sealed partial class ThreadPoolBoundHandle + { + private static ThreadPoolBoundHandle BindHandleCore(SafeHandle handle) + { + Debug.Assert(handle != null); + Debug.Assert(!handle.IsClosed); + Debug.Assert(!handle.IsInvalid); + + try + { + // ThreadPool.BindHandle will always return true, otherwise, it throws. See the underlying FCall + // implementation in ThreadPoolNative::CorBindIoCompletionCallback to see the implementation. + bool succeeded = ThreadPool.BindHandle(handle); + Debug.Assert(succeeded); + } + catch (Exception ex) + { // BindHandle throws ApplicationException on full CLR and Exception on CoreCLR. + // We do not let either of these leak and convert them to ArgumentException to + // indicate that the specified handles are invalid. + + if (ex.HResult == System.HResults.E_HANDLE) // Bad handle + throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); + + if (ex.HResult == System.HResults.E_INVALIDARG) // Handle already bound or sync handle + throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle)); + + throw; + } + + return new ThreadPoolBoundHandle(handle); + } + } +} diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs index d0cc5afbae..a4a3b980cf 100644 --- a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs +++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs @@ -83,28 +83,7 @@ namespace System.Threading if (handle.IsClosed || handle.IsInvalid) throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); - try - { - // ThreadPool.BindHandle will always return true, otherwise, it throws. See the underlying FCall - // implementation in ThreadPoolNative::CorBindIoCompletionCallback to see the implementation. - bool succeeded = ThreadPool.BindHandle(handle); - Debug.Assert(succeeded); - } - catch (Exception ex) - { // BindHandle throws ApplicationException on full CLR and Exception on CoreCLR. - // We do not let either of these leak and convert them to ArgumentException to - // indicate that the specified handles are invalid. - - if (ex.HResult == System.HResults.E_HANDLE) // Bad handle - throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); - - if (ex.HResult == System.HResults.E_INVALIDARG) // Handle already bound or sync handle - throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle)); - - throw; - } - - return new ThreadPoolBoundHandle(handle); + return BindHandleCore(handle); } /// <summary> diff --git a/src/mscorlib/src/System/Threading/Monitor.cs b/src/mscorlib/src/System/Threading/Monitor.cs index 3ace3335aa..0df64a5e5c 100644 --- a/src/mscorlib/src/System/Threading/Monitor.cs +++ b/src/mscorlib/src/System/Threading/Monitor.cs @@ -17,7 +17,6 @@ using System; using System.Runtime; -using System.Runtime.Remoting; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; diff --git a/src/mscorlib/Common/PinnableBufferCache.cs b/src/mscorlib/src/System/Threading/PinnableBufferCache.cs index 3f7853ce59..3f7853ce59 100644 --- a/src/mscorlib/Common/PinnableBufferCache.cs +++ b/src/mscorlib/src/System/Threading/PinnableBufferCache.cs diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs index 0a9248cba8..07d126179c 100644 --- a/src/mscorlib/src/System/Threading/Tasks/Task.cs +++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs @@ -6254,7 +6254,6 @@ namespace System.Threading.Tasks // NOTE: These options are a subset of TaskContinuationsOptions, thus before adding a flag check it is // not already in use. [Flags] - [Serializable] public enum TaskCreationOptions { /// <summary> @@ -6306,7 +6305,6 @@ namespace System.Threading.Tasks /// Task creation flags which are only used internally. /// </summary> [Flags] - [Serializable] internal enum InternalTaskOptions { /// <summary> Specifies "No internal task options" </summary> @@ -6338,7 +6336,6 @@ namespace System.Threading.Tasks /// Specifies flags that control optional behavior for the creation and execution of continuation tasks. /// </summary> [Flags] - [Serializable] public enum TaskContinuationOptions { /// <summary> diff --git a/src/mscorlib/src/System/Threading/Thread.cs b/src/mscorlib/src/System/Threading/Thread.cs index 70a5d06f7a..fab6c9e187 100644 --- a/src/mscorlib/src/System/Threading/Thread.cs +++ b/src/mscorlib/src/System/Threading/Thread.cs @@ -555,7 +555,6 @@ namespace System.Threading // declaring a local var of this enum type and passing it by ref into a function that needs to do a // stack crawl will both prevent inlining of the calle and pass an ESP point to stack crawl to // Declaring these in EH clauses is illegal; they must declared in the main method body - [Serializable] internal enum StackCrawlMark { LookForMe = 0, diff --git a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs index 9122df0d3e..fb72110fdc 100644 --- a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs +++ b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs @@ -19,7 +19,6 @@ using System.Runtime.Serialization; namespace System.Threading { - [Serializable] public class ThreadInterruptedException : SystemException { public ThreadInterruptedException() @@ -42,6 +41,7 @@ namespace System.Threading protected ThreadInterruptedException(SerializationInfo info, StreamingContext context) : base(info, context) { + throw new PlatformNotSupportedException(); } } } diff --git a/src/mscorlib/src/System/Threading/Timer.cs b/src/mscorlib/src/System/Threading/Timer.cs index 960f815d64..a5c7945864 100644 --- a/src/mscorlib/src/System/Threading/Timer.cs +++ b/src/mscorlib/src/System/Threading/Timer.cs @@ -265,7 +265,19 @@ namespace System.Threading if (timer.m_period != Timeout.UnsignedInfinite) { timer.m_startTicks = nowTicks; - timer.m_dueTime = timer.m_period; + uint elapsedForNextDueTime = elapsed - timer.m_dueTime; + if (elapsedForNextDueTime < timer.m_period) + { + // Discount the extra amount of time that has elapsed since the previous firing time to + // prevent timer ticks from drifting + timer.m_dueTime = timer.m_period - elapsedForNextDueTime; + } + else + { + // Enough time has elapsed to fire the timer yet again. The timer is not able to keep up + // with the short period, have it fire 1 ms from now to avoid spinning without a delay. + timer.m_dueTime = 1; + } // // This is a repeating timer; schedule it to run again. diff --git a/src/mscorlib/src/System/Threading/WaitHandle.cs b/src/mscorlib/src/System/Threading/WaitHandle.cs index f3412d264f..da4856ee96 100644 --- a/src/mscorlib/src/System/Threading/WaitHandle.cs +++ b/src/mscorlib/src/System/Threading/WaitHandle.cs @@ -15,7 +15,6 @@ namespace System.Threading { using System.Threading; - using System.Runtime.Remoting; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/mscorlib/src/System/TypeLoadException.cs b/src/mscorlib/src/System/TypeLoadException.cs index 85e1da5920..5e748a6c58 100644 --- a/src/mscorlib/src/System/TypeLoadException.cs +++ b/src/mscorlib/src/System/TypeLoadException.cs @@ -13,7 +13,6 @@ using System; using System.Globalization; -using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -23,7 +22,6 @@ using System.Diagnostics.Contracts; namespace System { - [Serializable] public class TypeLoadException : SystemException, ISerializable { public TypeLoadException() @@ -106,33 +104,16 @@ namespace System protected TypeLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - ClassName = info.GetString("TypeLoadClassName"); - AssemblyName = info.GetString("TypeLoadAssemblyName"); - MessageArg = info.GetString("TypeLoadMessageArg"); - ResourceId = info.GetInt32("TypeLoadResourceID"); + throw new PlatformNotSupportedException(); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetTypeLoadExceptionMessage(int resourceId, StringHandleOnStack retString); - //We can rely on the serialization mechanism on Exception to handle most of our needs, but - //we need to add a few fields of our own. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - base.GetObjectData(info, context); - info.AddValue("TypeLoadClassName", ClassName, typeof(String)); - info.AddValue("TypeLoadAssemblyName", AssemblyName, typeof(String)); - info.AddValue("TypeLoadMessageArg", MessageArg, typeof(String)); - info.AddValue("TypeLoadResourceID", ResourceId); } // If ClassName != null, GetMessage will construct on the fly using it diff --git a/src/mscorlib/src/System/UInt16.cs b/src/mscorlib/src/System/UInt16.cs index e4a6837ae2..c7be2e9a1f 100644 --- a/src/mscorlib/src/System/UInt16.cs +++ b/src/mscorlib/src/System/UInt16.cs @@ -24,7 +24,7 @@ namespace System public struct UInt16 : IComparable, IFormattable, IConvertible , IComparable<UInt16>, IEquatable<UInt16> { - private ushort m_value; + private ushort m_value; // Do not rename (binary serialization) public const ushort MaxValue = (ushort)0xFFFF; public const ushort MinValue = 0; diff --git a/src/mscorlib/src/System/UInt32.cs b/src/mscorlib/src/System/UInt32.cs index 7c27efef39..2731047e06 100644 --- a/src/mscorlib/src/System/UInt32.cs +++ b/src/mscorlib/src/System/UInt32.cs @@ -26,7 +26,7 @@ namespace System public struct UInt32 : IComparable, IFormattable, IConvertible , IComparable<UInt32>, IEquatable<UInt32> { - private uint m_value; + private uint m_value; // Do not rename (binary serialization) public const uint MaxValue = (uint)0xffffffff; public const uint MinValue = 0U; diff --git a/src/mscorlib/src/System/UInt64.cs b/src/mscorlib/src/System/UInt64.cs index 0b79b6a7d8..a54bb69ba4 100644 --- a/src/mscorlib/src/System/UInt64.cs +++ b/src/mscorlib/src/System/UInt64.cs @@ -24,7 +24,7 @@ namespace System public struct UInt64 : IComparable, IFormattable, IConvertible , IComparable<UInt64>, IEquatable<UInt64> { - private ulong m_value; + private ulong m_value; // Do not rename (binary serialization) public const ulong MaxValue = (ulong)0xffffffffffffffffL; public const ulong MinValue = 0x0; diff --git a/src/mscorlib/src/System/UIntPtr.cs b/src/mscorlib/src/System/UIntPtr.cs index 09b7e51e89..08e494297b 100644 --- a/src/mscorlib/src/System/UIntPtr.cs +++ b/src/mscorlib/src/System/UIntPtr.cs @@ -23,7 +23,7 @@ namespace System [CLSCompliant(false)] public struct UIntPtr : IEquatable<UIntPtr>, ISerializable { - unsafe private void* m_value; + unsafe private void* _value; public static readonly UIntPtr Zero; @@ -31,16 +31,16 @@ namespace System [System.Runtime.Versioning.NonVersionable] public unsafe UIntPtr(uint value) { - m_value = (void*)value; + _value = (void*)value; } [System.Runtime.Versioning.NonVersionable] public unsafe UIntPtr(ulong value) { #if BIT64 - m_value = (void*)value; + _value = (void*)value; #else // 32 - m_value = (void*)checked((uint)value); + _value = (void*)checked((uint)value); #endif } @@ -48,7 +48,7 @@ namespace System [System.Runtime.Versioning.NonVersionable] public unsafe UIntPtr(void* value) { - m_value = value; + _value = value; } private unsafe UIntPtr(SerializationInfo info, StreamingContext context) @@ -60,7 +60,7 @@ namespace System throw new ArgumentException(SR.Serialization_InvalidPtrValue); } - m_value = (void*)l; + _value = (void*)l; } unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) @@ -70,30 +70,30 @@ namespace System throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); - info.AddValue("value", (ulong)m_value); + info.AddValue("value", (ulong)_value); } public unsafe override bool Equals(Object obj) { if (obj is UIntPtr) { - return (m_value == ((UIntPtr)obj).m_value); + return (_value == ((UIntPtr)obj)._value); } return false; } unsafe bool IEquatable<UIntPtr>.Equals(UIntPtr other) { - return m_value == other.m_value; + return _value == other._value; } public unsafe override int GetHashCode() { #if BIT64 - ulong l = (ulong)m_value; + ulong l = (ulong)_value; return (unchecked((int)l) ^ (int)(l >> 32)); #else // 32 - return unchecked((int)m_value); + return unchecked((int)_value); #endif } @@ -101,16 +101,16 @@ namespace System public unsafe uint ToUInt32() { #if BIT64 - return checked((uint)m_value); + return checked((uint)_value); #else // 32 - return (uint)m_value; + return (uint)_value; #endif } [System.Runtime.Versioning.NonVersionable] public unsafe ulong ToUInt64() { - return (ulong)m_value; + return (ulong)_value; } public unsafe override String ToString() @@ -118,9 +118,9 @@ namespace System Contract.Ensures(Contract.Result<String>() != null); #if BIT64 - return ((ulong)m_value).ToString(CultureInfo.InvariantCulture); + return ((ulong)_value).ToString(CultureInfo.InvariantCulture); #else // 32 - return ((uint)m_value).ToString(CultureInfo.InvariantCulture); + return ((uint)_value).ToString(CultureInfo.InvariantCulture); #endif } @@ -140,16 +140,16 @@ namespace System public unsafe static explicit operator uint(UIntPtr value) { #if BIT64 - return checked((uint)value.m_value); + return checked((uint)value._value); #else // 32 - return (uint)value.m_value; + return (uint)value._value; #endif } [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator ulong(UIntPtr value) { - return (ulong)value.m_value; + return (ulong)value._value; } [CLSCompliant(false)] @@ -163,21 +163,21 @@ namespace System [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator void* (UIntPtr value) { - return value.m_value; + return value._value; } [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator ==(UIntPtr value1, UIntPtr value2) { - return value1.m_value == value2.m_value; + return value1._value == value2._value; } [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator !=(UIntPtr value1, UIntPtr value2) { - return value1.m_value != value2.m_value; + return value1._value != value2._value; } [System.Runtime.Versioning.NonVersionable] @@ -229,7 +229,7 @@ namespace System [System.Runtime.Versioning.NonVersionable] public unsafe void* ToPointer() { - return m_value; + return _value; } } } diff --git a/src/mscorlib/src/System/Variant.cs b/src/mscorlib/src/System/Variant.cs index cae5bdade4..b468ab2f98 100644 --- a/src/mscorlib/src/System/Variant.cs +++ b/src/mscorlib/src/System/Variant.cs @@ -23,7 +23,6 @@ using System.Diagnostics.Contracts; namespace System { - [Serializable] [StructLayout(LayoutKind.Sequential)] internal struct Variant { diff --git a/src/mscorlib/src/System/__HResults.cs b/src/mscorlib/src/System/__HResults.cs index e4183f637a..0592d814ef 100644 --- a/src/mscorlib/src/System/__HResults.cs +++ b/src/mscorlib/src/System/__HResults.cs @@ -44,6 +44,7 @@ namespace System internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216); internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503); internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B); + internal const int COR_E_BADEXEFORMAT = unchecked((int)0x800700C1); internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013); internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015); internal const int COR_E_COMEMULATE = unchecked((int)0x80131535); |