Merge pull request #8560 from AlexRadch/Deconstruction
authorWes Haggard <weshaggard@users.noreply.github.com>
Tue, 13 Dec 2016 21:34:16 +0000 (13:34 -0800)
committerGitHub <noreply@github.com>
Tue, 13 Dec 2016 21:34:16 +0000 (13:34 -0800)
Supporting C# 7 deconstruction of KeyValuePair and DictionaryEntry

790 files changed:
Documentation/project-docs/glossary.md
README.md
build.sh
clrdefinitions.cmake
dependencies.props
perf.groovy
src/.nuget/Microsoft.NETCore.ILAsm/Microsoft.NETCore.ILAsm.builds
src/.nuget/Microsoft.NETCore.ILAsm/Microsoft.NETCore.ILAsm.pkgproj
src/.nuget/Microsoft.NETCore.ILAsm/ubuntu/14.04/Microsoft.NETCore.ILAsm.pkgproj
src/.nuget/Microsoft.NETCore.ILAsm/ubuntu/16.04/Microsoft.NETCore.ILAsm.pkgproj
src/.nuget/Microsoft.NETCore.ILDAsm/Microsoft.NETCore.ILDAsm.builds
src/.nuget/Microsoft.NETCore.ILDAsm/Microsoft.NETCore.ILDAsm.pkgproj
src/.nuget/Microsoft.NETCore.ILDAsm/ubuntu/14.04/Microsoft.NETCore.ILDAsm.pkgproj
src/.nuget/Microsoft.NETCore.ILDAsm/ubuntu/16.04/Microsoft.NETCore.ILDAsm.pkgproj
src/.nuget/Microsoft.NETCore.Jit/Microsoft.NETCore.Jit.builds
src/.nuget/Microsoft.NETCore.Jit/Microsoft.NETCore.Jit.pkgproj
src/.nuget/Microsoft.NETCore.Jit/ubuntu/14.04/Microsoft.NETCore.Jit.pkgproj
src/.nuget/Microsoft.NETCore.Jit/ubuntu/16.04/Microsoft.NETCore.Jit.pkgproj
src/.nuget/Microsoft.NETCore.Runtime.CoreCLR/Microsoft.NETCore.Runtime.CoreCLR.builds
src/.nuget/Microsoft.NETCore.Runtime.CoreCLR/Microsoft.NETCore.Runtime.CoreCLR.pkgproj
src/.nuget/Microsoft.NETCore.Runtime.CoreCLR/ubuntu/14.04/Microsoft.NETCore.Runtime.CoreCLR.pkgproj
src/.nuget/Microsoft.NETCore.Runtime.CoreCLR/ubuntu/16.04/Microsoft.NETCore.Runtime.CoreCLR.pkgproj
src/.nuget/Microsoft.NETCore.Runtime.CoreCLR/win/Microsoft.NETCore.Runtime.CoreCLR.pkgproj
src/.nuget/Microsoft.NETCore.TestHost/Microsoft.NETCore.TestHost.builds
src/.nuget/Microsoft.NETCore.TestHost/Microsoft.NETCore.TestHost.pkgproj
src/.nuget/Microsoft.NETCore.TestHost/ubuntu/14.04/Microsoft.NETCore.TestHost.pkgproj
src/.nuget/Microsoft.NETCore.TestHost/ubuntu/16.04/Microsoft.NETCore.TestHost.pkgproj
src/ToolBox/SOS/NETCore/SymbolReader.cs
src/ToolBox/SOS/Strike/sos_stacktrace.h
src/ToolBox/SOS/Strike/util.cpp
src/ToolBox/SOS/Strike/util.h
src/ToolBox/superpmi/superpmi-shared/mclist.cpp
src/ToolBox/superpmi/superpmi/methodstatsemitter.cpp
src/ToolBox/superpmi/superpmi/parallelsuperpmi.cpp
src/debug/ee/debugger.cpp
src/dlls/mscordac/mscordac_unixexports.src
src/gc/env/gcenv.ee.h
src/gc/gc.cpp
src/gc/gc.h
src/gc/gccommon.cpp
src/gc/gcenv.ee.standalone.inl
src/gc/gcinterface.ee.h
src/gc/gcinterface.h
src/gc/gcpriv.h
src/gc/sample/GCSample.cpp
src/gc/sample/gcenv.ee.cpp
src/gcdump/gcdump.cpp
src/gcdump/i386/gcdumpx86.cpp
src/ilasm/prebuilt/asmparse.cpp
src/ildasm/dis.cpp
src/ildasm/dres.cpp
src/ildasm/gui.cpp
src/jit/codegenarm.cpp
src/jit/codegenarm64.cpp
src/jit/codegenxarch.cpp
src/jit/flowgraph.cpp
src/jit/gentree.h
src/jit/inlinepolicy.cpp
src/jit/lowerarm.cpp
src/jit/lowerxarch.cpp
src/jit/lsra.cpp
src/jit/unwindamd64.cpp
src/jit/utils.cpp
src/mscorlib/Common/PinnableBufferCache.cs
src/mscorlib/corefx/Interop/Windows/mincore/Interop.SafeCreateFile.cs
src/mscorlib/corefx/Interop/Windows/mincore/Interop.UnsafeCreateFile.cs
src/mscorlib/corefx/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs
src/mscorlib/corefx/System/Globalization/Calendar.cs
src/mscorlib/corefx/System/Globalization/CalendarData.Unix.cs
src/mscorlib/corefx/System/Globalization/CalendarData.cs
src/mscorlib/corefx/System/Globalization/CalendricalCalculationsHelper.cs
src/mscorlib/corefx/System/Globalization/CharUnicodeInfo.cs
src/mscorlib/corefx/System/Globalization/CompareInfo.Unix.cs
src/mscorlib/corefx/System/Globalization/CompareInfo.Windows.cs
src/mscorlib/corefx/System/Globalization/CompareInfo.cs
src/mscorlib/corefx/System/Globalization/CultureData.Unix.cs
src/mscorlib/corefx/System/Globalization/CultureData.Windows.cs
src/mscorlib/corefx/System/Globalization/CultureData.cs
src/mscorlib/corefx/System/Globalization/CultureInfo.Windows.cs
src/mscorlib/corefx/System/Globalization/CultureInfo.cs
src/mscorlib/corefx/System/Globalization/DateTimeFormatInfo.cs
src/mscorlib/corefx/System/Globalization/DayLightTime.cs
src/mscorlib/corefx/System/Globalization/HebrewCalendar.cs
src/mscorlib/corefx/System/Globalization/HebrewNumber.cs
src/mscorlib/corefx/System/Globalization/HijriCalendar.Win32.cs [new file with mode: 0644]
src/mscorlib/corefx/System/Globalization/HijriCalendar.WinRT.cs [moved from src/mscorlib/corefx/System/Globalization/HijriCalendar.Windows.cs with 89% similarity]
src/mscorlib/corefx/System/Globalization/JapaneseCalendar.Unix.cs
src/mscorlib/corefx/System/Globalization/JapaneseCalendar.Win32.cs [new file with mode: 0644]
src/mscorlib/corefx/System/Globalization/JapaneseCalendar.WinRT.cs [moved from src/mscorlib/corefx/System/Globalization/JapaneseCalendar.Windows.cs with 100% similarity]
src/mscorlib/corefx/System/Globalization/JapaneseCalendar.cs
src/mscorlib/corefx/System/Globalization/LocaleData.Unix.cs
src/mscorlib/corefx/System/Globalization/NumberFormatInfo.cs
src/mscorlib/corefx/System/Globalization/PersianCalendar.cs
src/mscorlib/corefx/System/Globalization/RegionInfo.cs
src/mscorlib/corefx/System/Globalization/SortKey.cs
src/mscorlib/corefx/System/Globalization/StringInfo.cs
src/mscorlib/corefx/System/Globalization/TextElementEnumerator.cs
src/mscorlib/corefx/System/Globalization/TextInfo.Unix.cs
src/mscorlib/corefx/System/Globalization/TextInfo.Windows.cs
src/mscorlib/corefx/System/Globalization/TextInfo.cs
src/mscorlib/corefx/System/Globalization/UmAlQuraCalendar.cs
src/mscorlib/corefx/System/IO/FileStreamCompletionSource.Win32.cs
src/mscorlib/corefx/System/Runtime/InteropServices/StringBuffer.cs
src/mscorlib/model.xml
src/mscorlib/mscorlib.shared.sources.props
src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs
src/mscorlib/src/Microsoft/Win32/Registry.cs
src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs
src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs
src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs
src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.cs
src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
src/mscorlib/src/Microsoft/Win32/Win32Native.cs
src/mscorlib/src/System.Private.CoreLib.txt
src/mscorlib/src/System/Action.cs
src/mscorlib/src/System/Activator.cs
src/mscorlib/src/System/AggregateException.cs
src/mscorlib/src/System/AppContext/AppContext.cs
src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs
src/mscorlib/src/System/AppDomain.cs
src/mscorlib/src/System/AppDomainManager.cs
src/mscorlib/src/System/AppDomainSetup.cs
src/mscorlib/src/System/ArgIterator.cs
src/mscorlib/src/System/ArgumentException.cs
src/mscorlib/src/System/ArgumentNullException.cs
src/mscorlib/src/System/ArgumentOutOfRangeException.cs
src/mscorlib/src/System/Array.cs
src/mscorlib/src/System/ArraySegment.cs
src/mscorlib/src/System/Attribute.cs
src/mscorlib/src/System/BCLDebug.cs
src/mscorlib/src/System/BadImageFormatException.cs
src/mscorlib/src/System/BitConverter.cs
src/mscorlib/src/System/Buffer.cs
src/mscorlib/src/System/Byte.cs
src/mscorlib/src/System/CLRConfig.cs
src/mscorlib/src/System/CfgParser.cs
src/mscorlib/src/System/Char.cs
src/mscorlib/src/System/Collections/ArrayList.cs
src/mscorlib/src/System/Collections/Comparer.cs
src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs
src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs
src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs
src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
src/mscorlib/src/System/Collections/Generic/Comparer.cs
src/mscorlib/src/System/Collections/Generic/Dictionary.cs
src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
src/mscorlib/src/System/Collections/Generic/List.cs
src/mscorlib/src/System/Collections/Hashtable.cs
src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
src/mscorlib/src/System/Collections/SortedList.cs
src/mscorlib/src/System/Collections/Stack.cs
src/mscorlib/src/System/CompatibilitySwitches.cs
src/mscorlib/src/System/Convert.cs
src/mscorlib/src/System/Currency.cs
src/mscorlib/src/System/CurrentTimeZone.cs
src/mscorlib/src/System/DBNull.cs
src/mscorlib/src/System/DateTime.cs
src/mscorlib/src/System/DateTimeOffset.cs
src/mscorlib/src/System/Decimal.cs
src/mscorlib/src/System/DefaultBinder.cs
src/mscorlib/src/System/Delegate.cs
src/mscorlib/src/System/DelegateSerializationHolder.cs
src/mscorlib/src/System/Diagnostics/Assert.cs
src/mscorlib/src/System/Diagnostics/AssertFilter.cs
src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
src/mscorlib/src/System/Diagnostics/Debugger.cs
src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs
src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs
src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs
src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs
src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs
src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs
src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs
src/mscorlib/src/System/Diagnostics/LogSwitch.cs
src/mscorlib/src/System/Diagnostics/Stackframe.cs
src/mscorlib/src/System/Diagnostics/Stacktrace.cs
src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
src/mscorlib/src/System/Diagnostics/log.cs
src/mscorlib/src/System/Double.cs
src/mscorlib/src/System/Empty.cs
src/mscorlib/src/System/Enum.cs
src/mscorlib/src/System/Environment.Unix.cs [deleted file]
src/mscorlib/src/System/Environment.Win32.cs [deleted file]
src/mscorlib/src/System/Environment.cs
src/mscorlib/src/System/Exception.cs
src/mscorlib/src/System/GC.cs
src/mscorlib/src/System/Globalization/Calendar.cs
src/mscorlib/src/System/Globalization/CalendarData.cs
src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs
src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
src/mscorlib/src/System/Globalization/CompareInfo.cs
src/mscorlib/src/System/Globalization/CultureData.cs
src/mscorlib/src/System/Globalization/CultureInfo.cs
src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
src/mscorlib/src/System/Globalization/DateTimeFormat.cs
src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs
src/mscorlib/src/System/Globalization/DateTimeParse.cs
src/mscorlib/src/System/Globalization/EncodingDataItem.cs
src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs
src/mscorlib/src/System/Globalization/EncodingTable.cs
src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
src/mscorlib/src/System/Globalization/HebrewCalendar.cs
src/mscorlib/src/System/Globalization/HebrewNumber.cs
src/mscorlib/src/System/Globalization/HijriCalendar.cs
src/mscorlib/src/System/Globalization/IdnMapping.cs
src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
src/mscorlib/src/System/Globalization/PersianCalendar.cs
src/mscorlib/src/System/Globalization/RegionInfo.cs
src/mscorlib/src/System/Globalization/SortKey.cs
src/mscorlib/src/System/Globalization/StringInfo.cs
src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
src/mscorlib/src/System/Globalization/TextInfo.cs
src/mscorlib/src/System/Globalization/TimeSpanFormat.cs
src/mscorlib/src/System/Globalization/TimeSpanParse.cs
src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs
src/mscorlib/src/System/Guid.cs
src/mscorlib/src/System/IAppDomainPauseManager.cs
src/mscorlib/src/System/IO/BinaryReader.cs
src/mscorlib/src/System/IO/BinaryWriter.cs
src/mscorlib/src/System/IO/Directory.cs
src/mscorlib/src/System/IO/DirectoryInfo.cs
src/mscorlib/src/System/IO/DriveInfo.cs
src/mscorlib/src/System/IO/File.cs
src/mscorlib/src/System/IO/FileAttributes.cs
src/mscorlib/src/System/IO/FileInfo.cs
src/mscorlib/src/System/IO/FileLoadException.cs
src/mscorlib/src/System/IO/FileNotFoundException.cs
src/mscorlib/src/System/IO/FileSecurityState.cs
src/mscorlib/src/System/IO/FileSystemEnumerable.cs
src/mscorlib/src/System/IO/FileSystemInfo.cs
src/mscorlib/src/System/IO/MemoryStream.cs
src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
src/mscorlib/src/System/IO/Stream.cs
src/mscorlib/src/System/IO/StreamReader.cs
src/mscorlib/src/System/IO/StreamWriter.cs
src/mscorlib/src/System/IO/TextReader.cs
src/mscorlib/src/System/IO/TextWriter.cs
src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
src/mscorlib/src/System/IO/__Error.cs
src/mscorlib/src/System/Int16.cs
src/mscorlib/src/System/Int32.cs
src/mscorlib/src/System/Int64.cs
src/mscorlib/src/System/IntPtr.cs
src/mscorlib/src/System/Internal.cs
src/mscorlib/src/System/InvalidTimeZoneException.cs
src/mscorlib/src/System/Lazy.cs
src/mscorlib/src/System/LowLevelConsole.cs
src/mscorlib/src/System/MarshalByRefObject.cs
src/mscorlib/src/System/Math.cs
src/mscorlib/src/System/MathF.cs
src/mscorlib/src/System/MissingFieldException.cs
src/mscorlib/src/System/MissingMemberException.cs
src/mscorlib/src/System/MissingMethodException.cs
src/mscorlib/src/System/MulticastDelegate.cs
src/mscorlib/src/System/NotFiniteNumberException.cs
src/mscorlib/src/System/Number.cs
src/mscorlib/src/System/Object.cs
src/mscorlib/src/System/ObjectDisposedException.cs
src/mscorlib/src/System/OleAutBinder.cs
src/mscorlib/src/System/OperatingSystem.cs
src/mscorlib/src/System/ParseNumbers.cs
src/mscorlib/src/System/Progress.cs
src/mscorlib/src/System/Reflection/Assembly.cs
src/mscorlib/src/System/Reflection/AssemblyName.cs
src/mscorlib/src/System/Reflection/Associates.cs
src/mscorlib/src/System/Reflection/ComInterfaces.cs
src/mscorlib/src/System/Reflection/ConstructorInfo.cs
src/mscorlib/src/System/Reflection/CustomAttribute.cs
src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs
src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs
src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
src/mscorlib/src/System/Reflection/Emit/Opcode.cs
src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs
src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs
src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
src/mscorlib/src/System/Reflection/EventInfo.cs
src/mscorlib/src/System/Reflection/FieldInfo.cs
src/mscorlib/src/System/Reflection/LoaderAllocator.cs
src/mscorlib/src/System/Reflection/MdConstant.cs
src/mscorlib/src/System/Reflection/MdImport.cs
src/mscorlib/src/System/Reflection/MemberInfo.cs
src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs
src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs
src/mscorlib/src/System/Reflection/MethodBase.cs
src/mscorlib/src/System/Reflection/MethodBody.cs
src/mscorlib/src/System/Reflection/MethodInfo.cs
src/mscorlib/src/System/Reflection/Missing.cs
src/mscorlib/src/System/Reflection/Module.cs
src/mscorlib/src/System/Reflection/ParameterInfo.cs
src/mscorlib/src/System/Reflection/Pointer.cs
src/mscorlib/src/System/Reflection/PropertyInfo.cs
src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
src/mscorlib/src/System/Reflection/TypeDelegator.cs
src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
src/mscorlib/src/System/Resources/IResourceGroveler.cs
src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
src/mscorlib/src/System/Resources/ResourceFallbackManager.cs
src/mscorlib/src/System/Resources/ResourceManager.cs
src/mscorlib/src/System/Resources/ResourceReader.cs
src/mscorlib/src/System/Resources/ResourceSet.cs
src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
src/mscorlib/src/System/Resources/__FastResourceComparer.cs
src/mscorlib/src/System/RtType.cs
src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs
src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs
src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
src/mscorlib/src/System/Runtime/GcSettings.cs
src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs
src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs
src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
src/mscorlib/src/System/Runtime/InteropServices/IException.cs
src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs
src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs
src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs
src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs
src/mscorlib/src/System/Runtime/InteropServices/TypeLibConverter.cs [deleted file]
src/mscorlib/src/System/Runtime/InteropServices/Variant.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
src/mscorlib/src/System/Runtime/ProfileOptimization.cs
src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs
src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs
src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs
src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs
src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs
src/mscorlib/src/System/RuntimeHandles.cs
src/mscorlib/src/System/SByte.cs
src/mscorlib/src/System/Security/AccessControl/Enums.cs
src/mscorlib/src/System/Security/BuiltInPermissionSets.cs
src/mscorlib/src/System/Security/CodeAccessPermission.cs
src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs
src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs
src/mscorlib/src/System/Security/HostProtectionException.cs
src/mscorlib/src/System/Security/HostSecurityManager.cs
src/mscorlib/src/System/Security/IEvidenceFactory.cs
src/mscorlib/src/System/Security/ISecurityEncodable.cs
src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs
src/mscorlib/src/System/Security/NamedPermissionSet.cs
src/mscorlib/src/System/Security/PermissionListSet.cs
src/mscorlib/src/System/Security/PermissionSet.cs
src/mscorlib/src/System/Security/PermissionSetEnumerator.cs
src/mscorlib/src/System/Security/PermissionSetTriple.cs
src/mscorlib/src/System/Security/PermissionToken.cs
src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs
src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs
src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs
src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs
src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs
src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs
src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs
src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs
src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs
src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs
src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs
src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs
src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs
src/mscorlib/src/System/Security/Permissions/UIPermission.cs
src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs
src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs
src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs
src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs
src/mscorlib/src/System/Security/Policy/EvidenceBase.cs
src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs
src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs
src/mscorlib/src/System/Security/Policy/PolicyStatement.cs
src/mscorlib/src/System/Security/Policy/Site.cs
src/mscorlib/src/System/Security/Policy/StrongName.cs
src/mscorlib/src/System/Security/Policy/URL.cs
src/mscorlib/src/System/Security/Policy/Zone.cs
src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs
src/mscorlib/src/System/Security/SafeSecurityHandles.cs
src/mscorlib/src/System/Security/SecurityContext.cs
src/mscorlib/src/System/Security/SecurityElement.cs
src/mscorlib/src/System/Security/SecurityException.cs
src/mscorlib/src/System/Security/SecurityManager.cs
src/mscorlib/src/System/Security/SecurityRuntime.cs
src/mscorlib/src/System/Security/SecurityState.cs
src/mscorlib/src/System/Security/Util/Config.cs
src/mscorlib/src/System/Security/Util/StringExpressionSet.cs
src/mscorlib/src/System/Security/Util/TokenBasedSet.cs
src/mscorlib/src/System/Security/Util/URLString.cs
src/mscorlib/src/System/Security/Util/XMLUtil.cs
src/mscorlib/src/System/Security/securestring.cs
src/mscorlib/src/System/SharedStatics.cs
src/mscorlib/src/System/Single.cs
src/mscorlib/src/System/Span.cs
src/mscorlib/src/System/String.Comparison.cs
src/mscorlib/src/System/String.Manipulation.cs
src/mscorlib/src/System/String.Searching.cs
src/mscorlib/src/System/String.cs
src/mscorlib/src/System/StringComparer.cs
src/mscorlib/src/System/StubHelpers.cs
src/mscorlib/src/System/Text/ASCIIEncoding.cs
src/mscorlib/src/System/Text/BaseCodePageEncoding.cs
src/mscorlib/src/System/Text/CodePageEncoding.cs
src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs
src/mscorlib/src/System/Text/Decoder.cs
src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
src/mscorlib/src/System/Text/DecoderFallback.cs
src/mscorlib/src/System/Text/DecoderNLS.cs
src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
src/mscorlib/src/System/Text/EUCJPEncoding.cs
src/mscorlib/src/System/Text/Encoder.cs
src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
src/mscorlib/src/System/Text/EncoderFallback.cs
src/mscorlib/src/System/Text/EncoderNLS.cs
src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
src/mscorlib/src/System/Text/Encoding.cs
src/mscorlib/src/System/Text/EncodingForwarder.cs
src/mscorlib/src/System/Text/EncodingNLS.cs
src/mscorlib/src/System/Text/GB18030Encoding.cs
src/mscorlib/src/System/Text/ISCIIEncoding.cs
src/mscorlib/src/System/Text/ISO2022Encoding.cs
src/mscorlib/src/System/Text/Latin1Encoding.cs
src/mscorlib/src/System/Text/MLangCodePageEncoding.cs
src/mscorlib/src/System/Text/Normalization.Windows.cs
src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs
src/mscorlib/src/System/Text/StringBuilder.cs
src/mscorlib/src/System/Text/SurrogateEncoder.cs
src/mscorlib/src/System/Text/UTF32Encoding.cs
src/mscorlib/src/System/Text/UTF7Encoding.cs
src/mscorlib/src/System/Text/UTF8Encoding.cs
src/mscorlib/src/System/Text/UnicodeEncoding.cs
src/mscorlib/src/System/Threading/AsyncLocal.cs
src/mscorlib/src/System/Threading/AutoResetEvent.cs
src/mscorlib/src/System/Threading/CancellationToken.cs
src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
src/mscorlib/src/System/Threading/CancellationTokenSource.cs
src/mscorlib/src/System/Threading/CountdownEvent.cs
src/mscorlib/src/System/Threading/EventWaitHandle.cs
src/mscorlib/src/System/Threading/ExecutionContext.cs
src/mscorlib/src/System/Threading/Interlocked.cs
src/mscorlib/src/System/Threading/LazyInitializer.cs
src/mscorlib/src/System/Threading/LockRecursionException.cs
src/mscorlib/src/System/Threading/ManualResetEvent.cs
src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
src/mscorlib/src/System/Threading/Monitor.cs
src/mscorlib/src/System/Threading/Mutex.cs
src/mscorlib/src/System/Threading/Overlapped.cs
src/mscorlib/src/System/Threading/ReaderWriterLock.cs
src/mscorlib/src/System/Threading/Semaphore.cs
src/mscorlib/src/System/Threading/SemaphoreFullException.cs
src/mscorlib/src/System/Threading/SemaphoreSlim.cs
src/mscorlib/src/System/Threading/SpinLock.cs
src/mscorlib/src/System/Threading/SpinWait.cs
src/mscorlib/src/System/Threading/SynchronizationContext.cs
src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs
src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs
src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
src/mscorlib/src/System/Threading/Tasks/Parallel.cs
src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs
src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs
src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
src/mscorlib/src/System/Threading/Tasks/Task.cs
src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs
src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs
src/mscorlib/src/System/Threading/Tasks/future.cs
src/mscorlib/src/System/Threading/Thread.cs
src/mscorlib/src/System/Threading/ThreadAbortException.cs
src/mscorlib/src/System/Threading/ThreadLocal.cs
src/mscorlib/src/System/Threading/ThreadPool.cs
src/mscorlib/src/System/Threading/Timer.cs
src/mscorlib/src/System/Threading/Volatile.cs
src/mscorlib/src/System/Threading/WaitHandle.cs
src/mscorlib/src/System/ThrowHelper.cs
src/mscorlib/src/System/TimeSpan.cs
src/mscorlib/src/System/TimeZone.cs
src/mscorlib/src/System/TimeZoneInfo.cs
src/mscorlib/src/System/TimeZoneNotFoundException.cs
src/mscorlib/src/System/Tuple.cs
src/mscorlib/src/System/Type.cs
src/mscorlib/src/System/TypeInitializationException.cs
src/mscorlib/src/System/TypeLoadException.cs
src/mscorlib/src/System/TypeNameParser.cs
src/mscorlib/src/System/TypedReference.cs
src/mscorlib/src/System/UInt16.cs
src/mscorlib/src/System/UInt32.cs
src/mscorlib/src/System/UInt64.cs
src/mscorlib/src/System/UIntPtr.cs
src/mscorlib/src/System/UnhandledExceptionEventHandler.cs
src/mscorlib/src/System/UnitySerializationHolder.cs
src/mscorlib/src/System/ValueType.cs
src/mscorlib/src/System/Variant.cs
src/mscorlib/src/System/Version.cs
src/mscorlib/src/System/WeakReference.cs
src/mscorlib/src/System/WeakReferenceOfT.cs
src/mscorlib/src/System/_LocalDataStore.cs
src/mscorlib/src/System/_LocalDataStoreMgr.cs
src/mscorlib/src/System/__ComObject.cs
src/mscorlib/src/System/cominterfaces.cs
src/mscorlib/src/System/mda.cs
src/mscorlib/src/mscorlib.Friends.cs
src/pal/inc/pal.h
src/pal/inc/rt/palrt.h
src/pal/inc/unixasmmacrosx86.inc
src/pal/src/CMakeLists.txt
src/pal/src/arch/i386/context2.S
src/pal/src/cruntime/printf.cpp
src/pal/src/debug/debug.cpp
src/pal/src/exception/machmessage.h
src/pal/src/include/pal/context.h
src/pal/src/include/pal/palinternal.h
src/pal/src/safecrt/input.inl
src/pal/src/safecrt/mbusafecrt.cpp
src/pal/src/safecrt/sprintf_s.cpp [moved from src/pal/src/safecrt/sprintf.cpp with 98% similarity]
src/pal/src/safecrt/sscanf_s.cpp [moved from src/pal/src/safecrt/sscanf.cpp with 99% similarity]
src/pal/src/thread/context.cpp
src/pal/src/thread/process.cpp
src/pal/tests/palsuite/c_runtime/CMakeLists.txt
src/pal/tests/palsuite/c_runtime/sprintf/test5/CMakeLists.txt [deleted file]
src/pal/tests/palsuite/c_runtime/sprintf/test5/test5.cpp [deleted file]
src/pal/tests/palsuite/c_runtime/sprintf/test5/testinfo.dat [deleted file]
src/pal/tests/palsuite/c_runtime/sprintf_s/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/CMakeLists.txt with 95% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/sprintf_s.h [moved from src/pal/tests/palsuite/c_runtime/sprintf/sprintf.h with 86% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test1/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test1/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test1/test1.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test1/test1.cpp with 85% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test1/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test1/testinfo.dat with 71% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test10/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test10/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test10/test10.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test10/test10.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test10/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test10/testinfo.dat with 74% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test11/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test11/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test11/test11.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test11/test11.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test11/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test11/testinfo.dat with 74% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test12/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test12/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test12/test12.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test12/test12.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test12/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test12/testinfo.dat with 72% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test13/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test13/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test13/test13.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test13/test13.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test13/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test13/testinfo.dat with 72% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test14/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test14/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test14/test14.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test14/test14.cpp with 95% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test14/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test14/testinfo.dat with 70% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test15/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test15/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test15/test15.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test15/test15.cpp with 95% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test15/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test15/testinfo.dat with 70% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test16/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test16/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test16/test16.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test16/test16.cpp with 94% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test16/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test16/testinfo.dat with 71% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test17/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test17/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test17/test17.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test17/test17.cpp with 94% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test17/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test17/testinfo.dat with 70% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test18/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test18/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test18/test18.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test18/test18.cpp with 94% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test18/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test18/testinfo.dat with 70% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test19/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test19/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test19/test19.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test19/test19.cpp with 90% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test19/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test19/testinfo.dat with 71% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test2/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test2/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test2/test2.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test2/test2.cpp with 91% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test2/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test2/testinfo.dat with 75% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test3/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test3/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test3/test3.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test3/test3.cpp with 92% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test3/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test3/testinfo.dat with 74% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test4/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test4/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test4/test4.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test4/test4.cpp with 96% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test4/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test4/testinfo.dat with 75% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test6/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test6/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test6/test6.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test6/test6.cpp with 91% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test6/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test6/testinfo.dat with 75% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test7/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test7/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test7/test7.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test7/test7.cpp with 92% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test7/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test7/testinfo.dat with 74% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test8/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test8/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test8/test8.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test8/test8.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test8/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test8/testinfo.dat with 74% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test9/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sprintf/test9/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test9/test9.cpp [moved from src/pal/tests/palsuite/c_runtime/sprintf/test9/test9.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sprintf_s/test9/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test9/testinfo.dat with 74% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/sscanf_s.h [moved from src/pal/tests/palsuite/c_runtime/sscanf/sscanf.h with 80% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test1/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test1/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test1/test1.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test1/test1.cpp with 91% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test1/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test1/testinfo.dat with 77% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test10/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test10/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test10/test10.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test10/test10.cpp with 92% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test10/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test10/testinfo.dat with 75% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test11/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test11/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test11/test11.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test11/test11.cpp with 92% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test11/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test11/testinfo.dat with 76% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test12/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test12/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test12/test12.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test12/test12.cpp with 92% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test12/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test12/testinfo.dat with 75% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test13/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test13/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test13/test13.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test13/test13.cpp with 91% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test13/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test13/testinfo.dat with 73% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test14/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test14/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test14/test14.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test14/test14.cpp with 89% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test14/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test14/testinfo.dat with 70% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test15/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test15/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test15/test15.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test15/test15.cpp with 90% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test15/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test15/testinfo.dat with 70% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test16/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test16/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test16/test16.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test16/test16.cpp with 90% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test16/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test16/testinfo.dat with 70% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test17/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test17/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test17/test17.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test17/test17.cpp with 90% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test17/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test17/testinfo.dat with 70% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test2/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test2/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test2/test2.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test2/test2.cpp with 92% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test2/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test2/testinfo.dat with 71% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test3/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test3/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test3/test3.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test3/test3.cpp with 91% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test3/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test3/testinfo.dat with 73% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test4/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test4/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test4/test4.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test4/test4.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test4/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test4/testinfo.dat with 74% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test5/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test5/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test5/test5.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test5/test5.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test5/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test5/testinfo.dat with 74% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test6/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test6/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test6/test6.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test6/test6.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test6/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test6/testinfo.dat with 75% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test7/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test7/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test7/test7.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test7/test7.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test7/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test7/testinfo.dat with 73% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test8/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test8/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test8/test8.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test8/test8.cpp with 93% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test8/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sprintf/test8/testinfo.dat with 74% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test9/CMakeLists.txt [moved from src/pal/tests/palsuite/c_runtime/sscanf/test9/CMakeLists.txt with 100% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test9/test9.cpp [moved from src/pal/tests/palsuite/c_runtime/sscanf/test9/test9.cpp with 92% similarity]
src/pal/tests/palsuite/c_runtime/sscanf_s/test9/testinfo.dat [moved from src/pal/tests/palsuite/c_runtime/sscanf/test9/testinfo.dat with 75% similarity]
src/pal/tests/palsuite/c_runtime/swscanf/swscanf.h
src/pal/tests/palsuite/c_runtime/wcscat/test1/test1.cpp
src/pal/tests/palsuite/c_runtime/wcscpy/test1/test1.cpp
src/pal/tests/palsuite/common/palsuite.h
src/pal/tests/palsuite/debug_api/WriteProcessMemory/test1/test1.cpp
src/pal/tests/palsuite/debug_api/WriteProcessMemory/test3/test3.cpp
src/pal/tests/palsuite/file_io/CreateDirectoryA/test1/CreateDirectoryA.cpp
src/pal/tests/palsuite/file_io/CreateDirectoryW/test1/CreateDirectoryW.cpp
src/pal/tests/palsuite/file_io/CreateFileA/test1/CreateFileA.cpp
src/pal/tests/palsuite/file_io/CreateFileW/test1/CreateFileW.cpp
src/pal/tests/palsuite/file_io/GetTempFileNameA/test1/GetTempFileNameA.cpp
src/pal/tests/palsuite/file_io/MoveFileA/test1/MoveFileA.cpp
src/pal/tests/palsuite/file_io/MoveFileW/test1/MoveFileW.cpp
src/pal/tests/palsuite/file_io/RemoveDirectoryA/test1/RemoveDirectoryA.cpp
src/pal/tests/palsuite/file_io/RemoveDirectoryW/test1/RemoveDirectoryW.cpp
src/pal/tests/palsuite/file_io/SearchPathA/test1/SearchPathA.cpp
src/pal/tests/palsuite/file_io/SearchPathW/test1/SearchPathW.cpp
src/pal/tests/palsuite/file_io/SetCurrentDirectoryA/test1/SetCurrentDirectoryA.cpp
src/pal/tests/palsuite/file_io/SetCurrentDirectoryA/test2/setcurrentdirectorya.cpp
src/pal/tests/palsuite/file_io/SetCurrentDirectoryW/test2/setcurrentdirectoryw.cpp
src/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test2/CreateFileMappingW.cpp
src/pal/tests/palsuite/filemapping_memmgt/ReadProcessMemory/test2/test2.cpp
src/pal/tests/palsuite/loader/LoadLibraryA/test5/loadlibrarya.cpp
src/pal/tests/palsuite/loader/LoadLibraryW/test5/loadlibraryw.cpp
src/pal/tests/palsuite/pal_specific/PAL_RegisterLibraryW_UnregisterLibraryW/test1/PAL_RegisterLibraryW_UnregisterLibraryW.cpp
src/pal/tests/palsuite/pal_specific/PAL_RegisterLibraryW_UnregisterLibraryW/test2_neg/reg_unreg_libraryw_neg.cpp
src/pal/tests/palsuite/paltestlist.txt
src/pal/tests/palsuite/palverify.dat
src/tools/crossgen/crossgen.cpp
src/vm/CMakeLists.txt
src/vm/appdomain.cpp
src/vm/cgensys.h
src/vm/codeman.cpp
src/vm/comdelegate.cpp
src/vm/comdependenthandle.cpp
src/vm/comdependenthandle.h
src/vm/compile.cpp
src/vm/comsynchronizable.cpp
src/vm/dllimportcallback.cpp
src/vm/dllimportcallback.h
src/vm/ecalllist.h
src/vm/gcenv.ee.cpp
src/vm/gcenv.ee.h
src/vm/gcheaputilities.cpp
src/vm/gcheaputilities.h
src/vm/gdbjit.cpp
src/vm/i386/asmhelpers.S
src/vm/i386/cgenx86.cpp
src/vm/i386/umthunkstub.S [new file with mode: 0644]
src/vm/i386/unixstubs.cpp
src/vm/prestub.cpp
tests/src/Common/build_against_pkg_dependencies/project.json
tests/src/Common/netcoreapp/project.json
tests/src/Common/targeting_pack_ref/project.json
tests/src/Common/test_dependencies/project.json
tests/src/GC/API/GC/GetGenerationWR2.csproj
tests/src/JIT/Regression/JitBlue/GitHub_8599/GitHub_8599.cs [new file with mode: 0644]
tests/src/JIT/Regression/JitBlue/GitHub_8599/GitHub_8599.csproj [new file with mode: 0644]
tests/src/JIT/config/benchmark+roslyn/project.json
tests/src/JIT/config/benchmark+serialize/project.json
tests/src/JIT/config/benchmark/project.json
tests/src/JIT/config/extra/project.json
tests/src/JIT/config/minimal/project.json
tests/src/JIT/config/threading+thread/project.json
tests/src/JIT/config/threading/project.json
tests/src/performance/project.json

index 6b13ba8..670254d 100644 (file)
@@ -15,6 +15,7 @@ As much as possible, we should link to the most authoritative and recent source
 * JIT: [Just-in-Time](https://github.com/dotnet/coreclr/blob/master/Documentation/botr/ryujit-overview.md) compiler. RyuJIT is the code name for the next generation Just-in-Time(aka "JIT") for the .NET runtime.
 * LCG: Lightweight Code Generation. An early name for [dynamic methods](https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs).
 * NGen: Native Image Generator.
+* NYI: Not Yet Implemented
 * PAL: [Platform Adaptation Layer](http://archive.oreilly.com/pub/a/dotnet/2002/03/04/rotor.html). Provides an abstraction layer between the runtime and the operating system
 * PE: Portable Executable.
 * ProjectN: Codename for the first version of [.NET Native for UWP](https://msdn.microsoft.com/en-us/vstudio/dotnetnative.aspx).
@@ -22,6 +23,7 @@ As much as possible, we should link to the most authoritative and recent source
 * Redhawk: Codename for experimental minimal managed code runtime that evolved into [CoreRT](https://github.com/dotnet/corert/).
 * SOS: [Son of Strike](http://blogs.msdn.com/b/jasonz/archive/2003/10/21/53581.aspx). The debugging extension for DbgEng based debuggers. Uses the DAC as an abstraction layer for its operation.
 * SVR: The CLR used to be built as two variants, with one called "mscorsvr.dll", to mean the "server" version. In particular, it contained the server GC implementation, which was intended for multi-threaded apps capable of taking advantage of multiple processors. In the .NET Framework 2 release, the two variants were merged into "mscorwks.dll". The WKS version was the default, however the SVR version remained available.
+* TPA: Trusted Platform Assemblies used to be a special set of assemblies that comprised the platform assemblies, when it was originally designed. As of today, it is simply the set of assemblies known to constitute the application.
 * URT: Universal Runtime. Ancient name for what ended up being .NET, is used in the WinError facility name FACILITY_URT.
 * VSD: [Virtual Stub Dispatch](../botr/virtual-stub-dispatch.md). Technique of using stubs for virtual method invocations instead of the traditional virtual method table.
 * VM: Virtual machine.
index e6b496d..98dcb1a 100644 (file)
--- a/README.md
+++ b/README.md
@@ -33,8 +33,8 @@ related to .NET Core including:
 
 ## What Can you Make from this Repository?
 
-.NET Core relies heavily on the [Nuget](https://en.wikipedia.org/wiki/NuGet) package manager
-which is system to package, distribute and version software components.  See [https://www.nuget.org/](https://www.nuget.org/) 
+.NET Core relies heavily on the [Nuget](https://en.wikipedia.org/wiki/NuGet) package manager,
+which is system to package, distribute and version software components.  See [https://www.nuget.org/](https://www.nuget.org/) 
 for more information on Nuget.   For now it is enough to know Nuget is a system that
 bundles components into `*.nupkg` files (which are ZIP archives) and these packages can be 'published' 
 either through a local file system path or by a URL (e.g. https://www.nuget.org/).   There are then tools 
@@ -42,7 +42,7 @@ either through a local file system path or by a URL (e.g. https://www.nuget.org/
 how to search these publishing locations and pull down consistent set of packages for the 
 application.   
 
-In concrete terms, this repository is best thought of as the source code for the following Nuget package
+In concrete terms, this repository is best thought of as the source code for the following Nuget package
  
  * **Microsoft.NETCore.Runtime.CoreCLR** - Represents the object allocator, garbage collector (GC), class 
    loader, type system, interop and the most fundamental parts of the .NET class library (e.g. 
@@ -59,7 +59,7 @@ It also contains the source code for the following closely related support packa
  * **Microsoft.NETCore.TestHost** - This contains the corehost.exe program, which is a small wrapper 
    that uses the .NET Runtime to run IL DLLs passed to it on the command line.
  * **Microsoft.TargetingPack.Private.CoreCLR** - A set of assemblies that represent the compile time surface 
-   area of class library implemented by the runtime itself.
+   area of the class library implemented by the runtime itself.
 
 ## Relationship with the [CoreFX](https://github.com/dotnet/corefx) Repository 
 
@@ -79,19 +79,19 @@ belongs and use that package as its **public publishing** point.   That 'facade'
 to the (private) implementation in System.Private.CoreLib.dll defined here.
 For example the *System.Runtime* package defined in CoreFX declares the PUBLIC name for types like 
 System.Object and System.String.   Thus from an applications point of view these types live in System.Runtime.dll. 
-However System.Runtime.dll (defined in the CoreFX repo) forwards references ultimately to System.Private.CoreLib.dll 
+However, System.Runtime.dll (defined in the CoreFX repo) forwards references ultimately to System.Private.CoreLib.dll 
 which is defined here.
 
 Thus in order to run an application, you need BOTH the Microsoft.NETCore.Runtime.CoreCLR Nuget package 
-(defined in this repository) as well as  packages for whatever you actually references that were defined 
+(defined in this repository) as well as  packages for whatever you actually reference that were defined 
 in the CoreFX repository (which at a minimum includes the System.Runtime package).    You also need some 
 sort of 'host' executable that loads the CoreCLR package as well as the CoreFX packages and starts your code (typically 
 you use dotnet.exe for this).   
 
 These extra pieces are not defined here, however you don't need to build them in order to use the CoreCLR 
 Nuget package you create here.   There are already versions of the CoreFX packages published on 
-https://www.nuget.org/ so you  can just have your test application's project.json specify the CoreCLR you 
-built it will naturally pull anything else it needs from the official location https://www.nuget.org/ to 
+https://www.nuget.org/ so you can have your test application's project.json specify the CoreCLR you 
+built and it will naturally pull anything else it needs from the official location https://www.nuget.org/ to 
 make a complete application.  More on this in the [Using Your Build](Documentation/workflow/UsingYourBuild.md) page.
 
 --------------------------
@@ -128,8 +128,8 @@ The build has two main 'buildTypes'
    can be difficult to debug.   Passing 'release' to the build script select this.  
 
 In addition, by default the build will not only create the runtime executables, but it will also 
-build all the tests.   There are quit a few tests so this does take a significant amount of time
-that is not necessary if you are just want to experiment with changes.   You can submit the building
+build all the tests.   There are quite a few tests so this does take a significant amount of time
+that is not necessary if you want to experiment with changes.   You can submit the building
 of the tests with the 'skiptests' argument to the build script.
 
 Thus to get a build as quickly as possible type the following (using \ as the directory separator, use / on Unix machines)
@@ -156,7 +156,7 @@ that were built, which are placed in the directory
 
 * bin\Product\Windows_NT.x64.Release\.nuget\pkg
 
-directory.   These packages are the 'output' of your build.   
+These packages are the 'output' of your build.   
 
 There are two basic techniques for using your new runtime.
 
index 1017d5c..d42bf37 100755 (executable)
--- a/build.sh
+++ b/build.sh
@@ -56,19 +56,36 @@ usage()
     exit 1
 }
 
-initDistroRid()
+initHostDistroRid()
 {
-    if [ "$__BuildOS" == "Linux" ]; then
+    if [ "$__HostOS" == "Linux" ]; then
         if [ ! -e /etc/os-release ]; then
             echo "WARNING: Can not determine runtime id for current distro."
-            export __DistroRid=""
+            __HostDistroRid=""
         else
             source /etc/os-release
-            export __DistroRid="$ID.$VERSION_ID-$__HostArch"
+            __HostDistroRid="$ID.$VERSION_ID-$__HostArch"
         fi
     fi
 }
 
+initTargetDistroRid()
+{
+    if [ $__CrossBuild == 1 ]; then
+        if [ "$__BuildOS" == "Linux" ]; then
+            if [ ! -e $ROOTFS_DIR/etc/os-release ]; then
+                echo "WARNING: Can not determine runtime id for current distro."
+                export __DistroRid=""
+            else
+                source $ROOTFS_DIR/etc/os-release
+                export __DistroRid="$ID.$VERSION_ID-$__BuildArch"
+            fi
+        fi
+    else
+        export __DistroRid="$__HostDistroRid"
+    fi
+}
+
 setup_dirs()
 {
     echo Setting up directories for build
@@ -167,16 +184,22 @@ build_coreclr()
     if [ $__SkipConfigure == 0 ]; then
         # if msbuild is not supported, then set __SkipGenerateVersion to 1
         if [ $__isMSBuildOnNETCoreSupported == 0 ]; then __SkipGenerateVersion=1; fi
-        # Drop version.c file
+        # Drop version.cpp file
         __versionSourceFile=$__IntermediatesDir/version.cpp
         if [ $__SkipGenerateVersion == 0 ]; then
             "$__ProjectRoot/run.sh" build -Project=$__ProjectDir/build.proj -generateHeaderUnix -NativeVersionSourceFile=$__versionSourceFile $__RunArgs $__UnprocessedBuildArgs
         else
+            # Generate the dummy version.cpp, but only if it didn't exist to make sure we don't trigger unnecessary rebuild
             __versionSourceLine="static char sccsid[] __attribute__((used)) = \"@(#)No version information produced\";"
-            echo $__versionSourceLine > $__versionSourceFile
+            if [ -e $__versionSourceFile ]; then
+                read existingVersionSourceLine < $__versionSourceFile
+            fi
+            if [ "$__versionSourceLine" != "$existingVersionSourceLine" ]; then
+                echo $__versionSourceLine > $__versionSourceFile
+            fi
         fi
 
-               pushd "$__IntermediatesDir"
+        pushd "$__IntermediatesDir"
         # Regenerate the CMake solution
         __ExtraCmakeArgs="-DCLR_CMAKE_TARGET_OS=$__BuildOS -DCLR_CMAKE_PACKAGES_DIR=$__PackagesDir -DCLR_CMAKE_PGO_INSTRUMENT=$__PgoInstrument"
         echo "Invoking \"$__ProjectRoot/src/pal/tools/gen-buildsys-clang.sh\" \"$__ProjectRoot\" $__ClangMajorVersion $__ClangMinorVersion $__BuildArch $__BuildType $__CodeCoverage $__IncludeTests $generator $__ExtraCmakeArgs $__cmakeargs"
@@ -228,7 +251,7 @@ isMSBuildOnNETCoreSupported()
 
     if [ "$__HostArch" == "x64" ]; then
         if [ "$__HostOS" == "Linux" ]; then
-            case "$__DistroRid" in
+            case "$__HostDistroRid" in
                 "centos.7-x64")
                     __isMSBuildOnNETCoreSupported=1
                     ;;
@@ -476,6 +499,7 @@ __CrossBuild=0
 __ClangMajorVersion=0
 __ClangMinorVersion=0
 __NuGetPath="$__PackagesDir/NuGet.exe"
+__HostDistroRid=""
 __DistroRid=""
 __cmakeargs=""
 __SkipGenerateVersion=0
@@ -664,8 +688,8 @@ fi
 # Set dependent variables
 __LogsDir="$__RootBinDir/Logs"
 
-# init the distro name
-initDistroRid
+# init the host distro name
+initHostDistroRid
 
 # Set the remaining variables based upon the determined build configuration
 __BinDir="$__RootBinDir/Product/$__BuildOS.$__BuildArch.$__BuildType"
@@ -701,6 +725,9 @@ if [ $__CrossBuild == 1 ]; then
     fi
 fi
 
+# init the target distro name
+initTargetDistroRid
+
 # Make the directories necessary for build if they don't exist
 
 setup_dirs
index 08712d4..91346ec 100644 (file)
@@ -131,6 +131,9 @@ if(NOT CMAKE_SYSTEM_NAME STREQUAL NetBSD)
 endif(NOT CMAKE_SYSTEM_NAME STREQUAL NetBSD)
 add_definitions(-DFEATURE_HOST_ASSEMBLY_RESOLVER)
 add_definitions(-DFEATURE_ICASTABLE)
+if (WIN32 AND (CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_I386))
+add_definitions(-DFEATURE_INTEROP_DEBUGGING)
+endif (WIN32 AND (CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_I386))
 if (CLR_CMAKE_PLATFORM_UNIX OR CLR_CMAKE_TARGET_ARCH_ARM64)
   add_definitions(-DFEATURE_IMPLICIT_TLS)
   set(FEATURE_IMPLICIT_TLS 1)
index 4117691..4065a03 100644 (file)
@@ -1,18 +1,18 @@
 <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
   <!-- Source of truth for dependency tooling: the commit hash of the dotnet/versions master branch as of the last auto-upgrade. -->
   <PropertyGroup>
-    <CoreFxCurrentRef>e222c0b56c6f5b852d033473f6c2facf37219331</CoreFxCurrentRef>
-    <CoreClrCurrentRef>e222c0b56c6f5b852d033473f6c2facf37219331</CoreClrCurrentRef>
+    <CoreFxCurrentRef>789bedf73cf114afe26a354d6a8e642e9678de80</CoreFxCurrentRef>
+    <CoreClrCurrentRef>789bedf73cf114afe26a354d6a8e642e9678de80</CoreClrCurrentRef>
   </PropertyGroup>
 
   <!-- Auto-upgraded properties for each build info dependency. -->
   <PropertyGroup>
-    <CoreFxExpectedPrerelease>beta-24721-02</CoreFxExpectedPrerelease>
+    <CoreFxExpectedPrerelease>beta-24810-02</CoreFxExpectedPrerelease>
   </PropertyGroup>
 
   <!-- Full package version strings that are used in other parts of the build. -->
   <PropertyGroup>
-    <CoreClrPackageVersion>1.2.0-beta-24801-03</CoreClrPackageVersion>
+    <CoreClrPackageVersion>1.2.0-beta-24810-01</CoreClrPackageVersion>
     <XunitPackageVersion>2.2.0-beta2-build3300</XunitPackageVersion>
   </PropertyGroup>
 
index e33d950..d7eb783 100644 (file)
@@ -28,9 +28,6 @@ def static getOSGroup(def os) {
 [true, false].each { isPR ->
     ['Windows_NT'].each { os ->
                ['x64'].each { architecture ->
-                       def configuration = 'Release'
-                       def runType = isPR ? 'private' : 'rolling'
-                       def benchViewName = isPR ? 'coreclr private %ghprbPullTitle%' : 'coreclr rolling %GIT_BRANCH_WITHOUT_ORIGIN% %GIT_COMMIT%'
                        def newJob = job(Utilities.getFullJobName(project, "perf_perflab_${os}", isPR)) {
                                // Set the label.
                                label('windows_clr_perf')
@@ -40,6 +37,17 @@ def static getOSGroup(def os) {
                                        }
                                }
 
+                       if (isPR)
+                       {
+                               parameters
+                               {
+                                       stringParam('BenchviewCommitName', '%ghprbPullTitle%', 'The name that you will be used to build the full title of a run in Benchview.  The final name will be of the form <branch> private BenchviewCommitName')
+                               }
+                       }
+                       def configuration = 'Release'
+                       def runType = isPR ? 'private' : 'rolling'
+                       def benchViewName = isPR ? 'coreclr private %BenchviewCommitName%' : 'coreclr rolling %GIT_BRANCH_WITHOUT_ORIGIN% %GIT_COMMIT%'
+                               
                                steps {
                                        // Batch
 
@@ -86,11 +94,6 @@ def static getOSGroup(def os) {
 // Create the Linux/OSX/CentOS coreclr test leg for debug and release and each scenario
 [true, false].each { isPR ->
     ['Ubuntu14.04'].each { os ->
-        def osGroup = getOSGroup(os)
-        def architecture = 'x64'
-        def configuration = 'Release'
-               def runType = isPR ? 'private' : 'rolling'
-               def benchViewName = isPR ? 'coreclr private \$ghprbPullTitle' : 'coreclr rolling \$GIT_BRANCH_WITHOUT_ORIGIN \$GIT_COMMIT'
         def newJob = job(Utilities.getFullJobName(project, "perf_${os}", isPR)) {
                        
                        label('linux_clr_perf')
@@ -100,6 +103,19 @@ def static getOSGroup(def os) {
                                        }
                                }
                        
+                       if (isPR)
+                       {
+                               parameters
+                               {
+                                       stringParam('BenchviewCommitName', '\$ghprbPullTitle', 'The name that you will be used to build the full title of a run in Benchview.  The final name will be of the form <branch> private BenchviewCommitName')
+                               }
+                       }
+                       def osGroup = getOSGroup(os)
+                       def architecture = 'x64'
+                       def configuration = 'Release'
+                       def runType = isPR ? 'private' : 'rolling'
+                       def benchViewName = isPR ? 'coreclr private \$BenchviewCommitName' : 'coreclr rolling \$GIT_BRANCH_WITHOUT_ORIGIN \$GIT_COMMIT'
+                       
             steps {
                 shell("bash ./tests/scripts/perf-prep.sh")
                 shell("./init-tools.sh")
index 6f417e6..90a1786 100644 (file)
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.ILAsm.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.ILAsm.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.ILAsm.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.ILAsm.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
index a67cf4c..48c8db3 100644 (file)
     <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.ILAsm.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.ILAsm.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.ILAsm.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.ILAsm.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.ILAsm.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
@@ -57,4 +63,4 @@
     </ProjectReference>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index 0864a65..cacadc7 100644 (file)
@@ -4,8 +4,8 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)ilasm" />
@@ -26,4 +26,4 @@
     </File>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index b48290b..818495e 100644 (file)
@@ -4,8 +4,8 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)ilasm" />
@@ -26,4 +26,4 @@
     </File>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index 01cb6f6..db3bf8b 100644 (file)
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.ILDAsm.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.ILDAsm.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.ILDAsm.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.ILDAsm.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
index 1f2f397..8538749 100644 (file)
     <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.ILDAsm.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.ILDAsm.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.ILDAsm.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.ILDAsm.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.ILDAsm.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
@@ -57,4 +63,4 @@
     </ProjectReference>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index e5bdb51..e087645 100644 (file)
@@ -4,8 +4,8 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)ildasm" />
@@ -26,4 +26,4 @@
     </File>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index b20c9c9..776e59b 100644 (file)
@@ -4,8 +4,8 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)ildasm" />
@@ -26,4 +26,4 @@
     </File>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index d730126..6a95697 100644 (file)
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.Jit.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.Jit.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.Jit.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.Jit.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
index c2e5ee6..6775ccc 100644 (file)
     <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.Jit.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.Jit.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.Jit.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.Jit.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.Jit.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
@@ -56,4 +62,4 @@
     </ProjectReference>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index e6775da..50d343f 100644 (file)
@@ -4,8 +4,8 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)libclrjit.so" />
@@ -26,4 +26,4 @@
     </File>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index dc59c2a..e57b7c5 100644 (file)
@@ -4,8 +4,8 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)libclrjit.so" />
@@ -26,4 +26,4 @@
     </File>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index 284edcb..6124136 100644 (file)
@@ -6,7 +6,6 @@
     <!-- This property must be set to the same value as $(PackageOutputPath) for the nuspecs and nupkgs to be binplaced to the intended location. -->
     <OutputPath>$(PackageOutputPath)</OutputPath>
   </PropertyGroup>
-
   <!-- We always build the identity/redirection package. However, the platform specific runtime-*.nupkg is built based upon the target OS we are building the product for. -->
   <ItemGroup>
     <Project Include="Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
index aa01e62..f40ee4f 100644 (file)
     <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
@@ -62,4 +68,4 @@
     </ProjectReference>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index 4b1f151..86cb61a 100644 (file)
@@ -4,12 +4,12 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)libcoreclr.so" />
-    <NativeSplittableBinary Include="$(BinDir)libcoreclrtraceptprovider.so" />
+    <NativeSplittableBinary Condition="'$(PackagePlatform)' != 'arm'" Include="$(BinDir)libcoreclrtraceptprovider.so" />
     <NativeSplittableBinary Include="$(BinDir)libdbgshim.so" />
     <NativeSplittableBinary Include="$(BinDir)libmscordaccore.so" />
     <NativeSplittableBinary Include="$(BinDir)libmscordbi.so" />
@@ -17,8 +17,8 @@
     <NativeSplittableBinary Include="$(BinDir)libsosplugin.so" />
     <NativeSplittableBinary Include="$(BinDir)System.Globalization.Native.so" />
     <ArchitectureSpecificNativeFile Include="$(BinDir)sosdocsunix.txt" />
-    <ArchitectureSpecificNativeFile Include="$(BinDir)mscorlib.ni.dll" />
-    <ArchitectureSpecificNativeFile Include="$(BinDir)System.Private.CoreLib.ni.dll" />
+    <ArchitectureSpecificNativeFile Condition="'$(PackagePlatform)'!='arm'" Include="$(BinDir)mscorlib.ni.dll" />
+    <ArchitectureSpecificNativeFile Condition="'$(PackagePlatform)'!='arm'" Include="$(BinDir)System.Private.CoreLib.ni.dll" />
     <ArchitectureSpecificLibFile Include="$(BinDir)System.Private.CoreLib.dll" />
     <ArchitectureSpecificLibFile Include="$(BinDir)mscorlib.dll" />
     <ArchitectureSpecificLibFile Include="$(BinDir)SOS.NETCore.dll" />
index 7163623..72c48ee 100644 (file)
@@ -4,12 +4,12 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)libcoreclr.so" />
-    <NativeSplittableBinary Include="$(BinDir)libcoreclrtraceptprovider.so" />
+    <NativeSplittableBinary Condition="'$(PackagePlatform)' != 'arm'" Include="$(BinDir)libcoreclrtraceptprovider.so" />
     <NativeSplittableBinary Include="$(BinDir)libdbgshim.so" />
     <NativeSplittableBinary Include="$(BinDir)libmscordaccore.so" />
     <NativeSplittableBinary Include="$(BinDir)libmscordbi.so" />
@@ -17,8 +17,8 @@
     <NativeSplittableBinary Include="$(BinDir)libsosplugin.so" />
     <NativeSplittableBinary Include="$(BinDir)System.Globalization.Native.so" />
     <ArchitectureSpecificNativeFile Include="$(BinDir)sosdocsunix.txt" />
-    <ArchitectureSpecificNativeFile Include="$(BinDir)mscorlib.ni.dll" />
-    <ArchitectureSpecificNativeFile Include="$(BinDir)System.Private.CoreLib.ni.dll" />
+    <ArchitectureSpecificNativeFile Condition="'$(PackagePlatform)' != 'arm'" Include="$(BinDir)mscorlib.ni.dll" />
+    <ArchitectureSpecificNativeFile Condition="'$(PackagePlatform)' != 'arm'" Include="$(BinDir)System.Private.CoreLib.ni.dll" />
     <ArchitectureSpecificLibFile Include="$(BinDir)System.Private.CoreLib.dll" />
     <ArchitectureSpecificLibFile Include="$(BinDir)mscorlib.dll" />
     <ArchitectureSpecificLibFile Include="$(BinDir)SOS.NETCore.dll" />
index d8bcb3f..844fb0b 100644 (file)
     <CrossArchitectureSpecificNativeSymbol Condition="'$(HasCrossTargetComponents)' == 'true'" 
                                            Include="@(LongNameFiles -> '$(BinDir)$(CrossTargetComponentFolder)\%(FileName)$(CrossTargetLongNameSuffix)%(Extension)')" />
     <AdditionalLibPackageExcludes Condition="'$(HasCrossTargetComponents)' == 'true'" 
-                                  Include="@(LongNameFiles -> 'runtimes\$(PackageTargetRuntime)\native\%(FileName)$(CrossTargetLongNameSuffix)%(Extension)')" />
+                                  Include="@(LongNameFiles -> 'tools\$(CrossTargetComponentFolder)_$(PackagePlatform)\%(FileName)$(CrossTargetLongNameSuffix)%(Extension)')" />
     <File Include="@(ArchitectureSpecificNativeSymbol)">
       <TargetPath>runtimes\$(PackageTargetRuntime)\native</TargetPath> 
       <IsSymbolFile>true</IsSymbolFile>
     </File>
     <File Condition="'$(HasCrossTargetComponents)' == 'true'" Include="@(CrossArchitectureSpecificNativeSymbol)">
-      <TargetPath>tools/$(CrossTargetComponentFolder)_$(PackagePlatform)</TargetPath>
+      <TargetPath>tools\$(CrossTargetComponentFolder)_$(PackagePlatform)</TargetPath>
       <IsSymbolFile>true</IsSymbolFile>
     </File>
   </ItemGroup>
index 2053727..78681ef 100644 (file)
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.TestHost.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.TestHost.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
     </Project>
+    <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.TestHost.pkgproj">
+      <OSGroup>Linux</OSGroup>
+      <Platform>arm</Platform>
+    </Project>
     <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.TestHost.pkgproj">
       <OSGroup>Linux</OSGroup>
       <Platform>amd64</Platform>
index 928397e..c831f93 100644 (file)
     <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.TestHost.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.TestHost.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.TestHost.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
+    <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.TestHost.pkgproj">
+      <Platform>arm</Platform>
+    </ProjectReference>
     <ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.TestHost.pkgproj">
       <Platform>amd64</Platform>
     </ProjectReference>
@@ -56,4 +62,4 @@
     </ProjectReference>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index a73159a..8750e16 100644 (file)
@@ -4,8 +4,8 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)corerun" />
@@ -26,4 +26,4 @@
     </File>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index 0613194..3f1397f 100644 (file)
@@ -4,8 +4,8 @@
   <PropertyGroup>
     <SkipPackageFileCheck>true</SkipPackageFileCheck>
     <PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
-    <!-- only build for x64 -->
-    <PackagePlatforms>x64;</PackagePlatforms>
+    <!-- build for x64, arm -->
+    <PackagePlatforms>x64;arm;</PackagePlatforms>
   </PropertyGroup>
   <ItemGroup>
     <NativeSplittableBinary Include="$(BinDir)corerun" />
@@ -26,4 +26,4 @@
     </File>
   </ItemGroup>
   <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
index 7da55c9..492f7cb 100644 (file)
@@ -37,7 +37,7 @@ namespace SOS
         /// Read memory callback
         /// </summary>
         /// <returns>number of bytes read or 0 for error</returns>
-        internal unsafe delegate int ReadMemoryDelegate(IntPtr address, byte* buffer, int count);
+        internal unsafe delegate int ReadMemoryDelegate(ulong address, byte* buffer, int count);
 
         private sealed class OpenedReader : IDisposable
         {
@@ -61,7 +61,7 @@ namespace SOS
         /// </summary>
         private class TargetStream : Stream
         {
-            readonly IntPtr _address;
+            readonly ulong _address;
             readonly ReadMemoryDelegate _readMemory;
 
             public override long Position { get; set; }
@@ -70,7 +70,7 @@ namespace SOS
             public override bool CanRead { get { return true; } }
             public override bool CanWrite { get { return false; } }
 
-            public TargetStream(IntPtr address, int size, ReadMemoryDelegate readMemory)
+            public TargetStream(ulong address, int size, ReadMemoryDelegate readMemory)
                 : base()
             {
                 _address = address;
@@ -89,7 +89,7 @@ namespace SOS
                 {
                     fixed (byte* p = &buffer[offset])
                     {
-                        int read  = _readMemory(new IntPtr(_address.ToInt64() + Position), p, count);
+                        int read  = _readMemory(_address + (ulong)Position, p, count);
                         Position += read;
                         return read;
                     }
@@ -157,18 +157,18 @@ namespace SOS
         /// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
         /// <param name="inMemoryPdbSize">in memory PDB size</param>
         /// <returns>Symbol reader handle or zero if error</returns>
-        internal static IntPtr LoadSymbolsForModule(string assemblyPath, bool isFileLayout, IntPtr loadedPeAddress, int loadedPeSize, 
-            IntPtr inMemoryPdbAddress, int inMemoryPdbSize, ReadMemoryDelegate readMemory)
+        internal static IntPtr LoadSymbolsForModule(string assemblyPath, bool isFileLayout, ulong loadedPeAddress, int loadedPeSize, 
+            ulong inMemoryPdbAddress, int inMemoryPdbSize, ReadMemoryDelegate readMemory)
         {
             try
             {
                 TargetStream peStream = null;
-                if (assemblyPath == null && loadedPeAddress != IntPtr.Zero)
+                if (assemblyPath == null && loadedPeAddress != 0)
                 {
                     peStream = new TargetStream(loadedPeAddress, loadedPeSize, readMemory);
                 }
                 TargetStream pdbStream = null;
-                if (inMemoryPdbAddress != IntPtr.Zero)
+                if (inMemoryPdbAddress != 0)
                 {
                     pdbStream = new TargetStream(inMemoryPdbAddress, inMemoryPdbSize, readMemory);
                 }
index 4aba4ea..0af241c 100644 (file)
@@ -119,7 +119,7 @@ HRESULT CALLBACK _EFN_StackTrace(
 // cbString - number of characters available in the string buffer. 
 // 
 // The output will be truncated of cbString is not long enough for the full stack trace.
-HRESULT _EFN_GetManagedExcepStack(
+HRESULT CALLBACK _EFN_GetManagedExcepStack(
     PDEBUG_CLIENT client,
     ULONG64 StackObjAddr,
     __out_ecount(cbString) PSTR szStackString,
@@ -128,7 +128,7 @@ HRESULT _EFN_GetManagedExcepStack(
 
 // _EFN_GetManagedExcepStackW - same as _EFN_GetManagedExcepStack, but returns 
 //                              the stack as a wide string.
-HRESULT _EFN_GetManagedExcepStackW(
+HRESULT CALLBACK _EFN_GetManagedExcepStackW(
     PDEBUG_CLIENT client,
     ULONG64 StackObjAddr,
     __out_ecount(cchString) PWSTR wszStackString,
@@ -141,7 +141,7 @@ HRESULT _EFN_GetManagedExcepStackW(
 // szName - a buffer to be filled with the full type name
 // cbName - the number of characters available in the buffer
 //
-HRESULT _EFN_GetManagedObjectName(
+HRESULT CALLBACK _EFN_GetManagedObjectName(
     PDEBUG_CLIENT client,
     ULONG64 objAddr,
     __out_ecount(cbName) PSTR szName,
@@ -158,7 +158,7 @@ HRESULT _EFN_GetManagedObjectName(
 // pOffset - the offset from objAddr to the field. This parameter can be NULL.
 //
 // At least one of pValue and pOffset must be non-NULL.
-HRESULT _EFN_GetManagedObjectFieldInfo(
+HRESULT CALLBACK _EFN_GetManagedObjectFieldInfo(
     PDEBUG_CLIENT client,
     ULONG64 objAddr,
     __out_ecount (mdNameLen) PSTR szFieldName,
index b2c96fe..b6336fb 100644 (file)
@@ -6134,7 +6134,7 @@ HRESULT SymbolReader::LoadSymbolsForWindowsPDB(___in IMetaDataImport* pMD, ___in
 int ReadMemoryForSymbols(ULONG64 address, char *buffer, int cb)
 {
     ULONG read;
-    if (SafeReadMemory(address, (PVOID)buffer, cb, &read))
+    if (SafeReadMemory(TO_TADDR(address), (PVOID)buffer, cb, &read))
     {
         return read;
     }
index 1932e28..4612acc 100644 (file)
@@ -2355,11 +2355,11 @@ static const char *SymbolReaderDllName = "SOS.NETCore";
 static const char *SymbolReaderClassName = "SOS.SymbolReader";
 
 typedef  int (*ReadMemoryDelegate)(ULONG64, char *, int);
-typedef  ULONG64 (*LoadSymbolsForModuleDelegate)(const char*, BOOL, ULONG64, int, ULONG64, int, ReadMemoryDelegate);
-typedef  void (*DisposeDelegate)(ULONG64);
-typedef  BOOL (*ResolveSequencePointDelegate)(ULONG64, const char*, unsigned int, unsigned int*, unsigned int*);
-typedef  BOOL (*GetLocalVariableName)(ULONG64, int, int, BSTR*);
-typedef  BOOL (*GetLineByILOffsetDelegate)(ULONG64, mdMethodDef, ULONG64, ULONG *, BSTR*);
+typedef  PVOID (*LoadSymbolsForModuleDelegate)(const char*, BOOL, ULONG64, int, ULONG64, int, ReadMemoryDelegate);
+typedef  void (*DisposeDelegate)(PVOID);
+typedef  BOOL (*ResolveSequencePointDelegate)(PVOID, const char*, unsigned int, unsigned int*, unsigned int*);
+typedef  BOOL (*GetLocalVariableName)(PVOID, int, int, BSTR*);
+typedef  BOOL (*GetLineByILOffsetDelegate)(PVOID, mdMethodDef, ULONG64, ULONG *, BSTR*);
 
 class SymbolReader
 {
@@ -2367,7 +2367,7 @@ private:
 #ifndef FEATURE_PAL
     ISymUnmanagedReader* m_pSymReader;
 #endif
-    ULONG64 m_symbolReaderHandle;
+    PVOID m_symbolReaderHandle;
 
     static LoadSymbolsForModuleDelegate loadSymbolsForModuleDelegate;
     static DisposeDelegate disposeDelegate;
index 6a6f870..511893f 100644 (file)
@@ -237,7 +237,7 @@ void MCList::AddMethodToMCL(int methodIndex)
         DWORD charCount = 0;
         DWORD bytesWritten = 0;
 
-        charCount = sprintf(strMethodIndex, "%d\r\n", methodIndex);
+        charCount = sprintf_s(strMethodIndex, sizeof(strMethodIndex), "%d\r\n", methodIndex);
 
         if (!WriteFile(hMCLFile, strMethodIndex, charCount, &bytesWritten, nullptr) || bytesWritten != charCount)
         {
index 0a43f02..5cebc97 100644 (file)
@@ -50,11 +50,11 @@ void MethodStatsEmitter::Emit(int methodNumber, MethodContext *mc, ULONGLONG fir
             if (mc->dumpMethodMD5HashToBuffer(md5Hash, MD5_HASH_BUFFER_SIZE) != MD5_HASH_BUFFER_SIZE)
                 md5Hash[0] = 0;
 
-            charCount += sprintf(rowData + charCount, "%s,", md5Hash);
+            charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%s,", md5Hash);
         }
         if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'n') != NULL || strchr(statsTypes, 'N') != NULL)
         {
-            charCount += sprintf(rowData + charCount, "%d,", methodNumber);
+            charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%d,", methodNumber);
         }
         if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'i') != NULL || strchr(statsTypes, 'I') != NULL)
         {
@@ -63,7 +63,7 @@ void MethodStatsEmitter::Emit(int methodNumber, MethodContext *mc, ULONGLONG fir
             unsigned flags = 0;
             mc->repCompileMethod(&info, &flags);
 
-            charCount += sprintf(rowData + charCount, "%d,", info.ILCodeSize);
+            charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%d,", info.ILCodeSize);
         }
         if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'a') != NULL || strchr(statsTypes, 'A') != NULL)
         {
@@ -76,11 +76,11 @@ void MethodStatsEmitter::Emit(int methodNumber, MethodContext *mc, ULONGLONG fir
             else
                 codeSize = 0;//this is likely a thin mc
 
-            charCount += sprintf(rowData + charCount, "%d,", codeSize);
+            charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%d,", codeSize);
         }
         if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 't') != NULL || strchr(statsTypes, 'T') != NULL)
         {
-            charCount += sprintf(rowData + charCount, "%llu,%llu,", firstTime, secondTime);
+            charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%llu,%llu,", firstTime, secondTime);
         }
 
         //get rid of the final ',' and replace it with a '\n'
@@ -105,15 +105,15 @@ void MethodStatsEmitter::SetStatsTypes(char *types)
         DWORD bytesWritten = 0;
 
         if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'h') != NULL || strchr(statsTypes, 'H') != NULL)
-            charCount += sprintf(rowHeader + charCount, "HASH,");
+            charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "HASH,");
         if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'n') != NULL || strchr(statsTypes, 'N') != NULL)
-            charCount += sprintf(rowHeader + charCount, "METHOD_NUMBER,");
+            charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "METHOD_NUMBER,");
         if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'i') != NULL || strchr(statsTypes, 'I') != NULL)
-            charCount += sprintf(rowHeader + charCount, "IL_CODE_SIZE,");
+            charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "IL_CODE_SIZE,");
         if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'a') != NULL || strchr(statsTypes, 'A') != NULL)
-            charCount += sprintf(rowHeader + charCount, "ASM_CODE_SIZE,");
+            charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "ASM_CODE_SIZE,");
         if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 't') != NULL || strchr(statsTypes, 'T') != NULL)
-            charCount += sprintf(rowHeader + charCount, "Time1,Time2,");
+            charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "Time1,Time2,");
 
         //get rid of the final ',' and replace it with a '\n'
         rowHeader[charCount - 1] = '\n';
@@ -123,4 +123,4 @@ void MethodStatsEmitter::SetStatsTypes(char *types)
             LogError("Failed to write row header '%s'. GetLastError()=%u", rowHeader, GetLastError());
         }
     }
-}
\ No newline at end of file
+}
index 8c52323..301db3c 100644 (file)
@@ -138,7 +138,7 @@ bool WriteArrayToMCL(char *mclFilename, int *arr, int count)
         DWORD charCount = 0;
         DWORD bytesWritten = 0;
 
-        charCount = sprintf(strMethodIndex, "%d\r\n", arr[i]);
+        charCount = sprintf_s(strMethodIndex, sizeof(strMethodIndex), "%d\r\n", arr[i]);
 
         if (!WriteFile(hMCLFile, strMethodIndex, charCount, &bytesWritten, nullptr) || (bytesWritten != charCount))
         {
@@ -232,7 +232,7 @@ void ProcessChildStdOut(const CommandLine::Options& o, char *stdoutFilename, int
             if (o.applyDiff)
             {
                 int temp1 = 0, temp2 = 0, temp3 = 0, temp4 = 0;
-                int converted = sscanf(buff, g_AsmDiffsSummaryFormatString, &temp1, &temp2, &temp3, &temp4);
+                int converted = sscanf_s(buff, g_AsmDiffsSummaryFormatString, &temp1, &temp2, &temp3, &temp4);
                 if (converted != 4)
                 {
                     LogError("Couldn't parse status message: \"%s\"", buff);
@@ -248,7 +248,7 @@ void ProcessChildStdOut(const CommandLine::Options& o, char *stdoutFilename, int
             else
             {
                 int temp1 = 0, temp2 = 0, temp3 = 0;
-                int converted = sscanf(buff, g_SummaryFormatString, &temp1, &temp2, &temp3);
+                int converted = sscanf_s(buff, g_SummaryFormatString, &temp1, &temp2, &temp3);
                 if (converted != 3)
                 {
                     LogError("Couldn't parse status message: \"%s\"", buff);
index 43a2e56..2aed8bd 100644 (file)
@@ -597,8 +597,8 @@ void DoAssertOnType(DebuggerIPCEventType event, int count)
         if (g_iDbgRuntimeCounter[event & 0x00ff] == count)
         {
             char        tmpStr[256];
-            sprintf(tmpStr, "%s == %d, break now!",
-                     IPCENames::GetName(event), count);
+            _snprintf_s(tmpStr, _countof(tmpStr), _TRUNCATE, "%s == %d, break now!",
+                        IPCENames::GetName(event), count);
 
             // fire the assertion
             DbgAssertDialog(__FILE__, __LINE__, tmpStr);
@@ -611,8 +611,8 @@ void DoAssertOnType(DebuggerIPCEventType event, int count)
         if (g_iDbgDebuggerCounter[event & 0x00ff] == count)
         {
             char        tmpStr[256];
-            sprintf(tmpStr, "%s == %d, break now!",
-                     IPCENames::GetName(event), count);
+            _snprintf_s(tmpStr, _countof(tmpStr), _TRUNCATE, "%s == %d, break now!",
+                        IPCENames::GetName(event), count);
 
             // fire the assertion
             DbgAssertDialog(__FILE__, __LINE__, tmpStr);
index aa0b541..ffa5968 100644 (file)
@@ -57,6 +57,7 @@ _vsnwprintf_s
 _itow_s
 _i64tow_s
 memcpy_s
+sscanf_s
 
 CoCreateGuid
 CopyFileW
index 5588698..beb0c1a 100644 (file)
@@ -65,6 +65,7 @@ public:
     static void DiagWalkSurvivors(void* gcContext);
     static void DiagWalkLOHSurvivors(void* gcContext);
     static void DiagWalkBGCSurvivors(void* gcContext);
+    static void StompWriteBarrier(WriteBarrierParameters* args);
 };
 
 #endif // __GCENV_EE_H__
index 9d1736c..6187938 100644 (file)
@@ -333,8 +333,8 @@ void gc_heap::add_to_history_per_heap()
 #endif //BACKGROUND_GC
     current_hist->fgc_lowest = lowest_address;
     current_hist->fgc_highest = highest_address;
-    current_hist->g_lowest = g_lowest_address;
-    current_hist->g_highest = g_highest_address;
+    current_hist->g_lowest = g_gc_lowest_address;
+    current_hist->g_highest = g_gc_highest_address;
 
     gchist_index_per_heap++;
     if (gchist_index_per_heap == max_history_count)
@@ -1402,8 +1402,8 @@ int mark_time, plan_time, sweep_time, reloc_time, compact_time;
 
 #ifndef MULTIPLE_HEAPS
 
-#define ephemeral_low           g_ephemeral_low
-#define ephemeral_high          g_ephemeral_high
+#define ephemeral_low           g_gc_ephemeral_low
+#define ephemeral_high          g_gc_ephemeral_high
 
 #endif // MULTIPLE_HEAPS
 
@@ -2176,6 +2176,55 @@ int log2(unsigned int n)
     return pos;
 }
 
+#ifndef DACCESS_COMPILE
+
+void stomp_write_barrier_resize(bool is_runtime_suspended, bool requires_upper_bounds_check)
+{
+    WriteBarrierParameters args = {};
+    args.operation = WriteBarrierOp::StompResize;
+    args.is_runtime_suspended = is_runtime_suspended;
+    args.requires_upper_bounds_check = requires_upper_bounds_check;
+    args.card_table = g_gc_card_table;
+    args.lowest_address = g_gc_lowest_address;
+    args.highest_address = g_gc_highest_address;
+    GCToEEInterface::StompWriteBarrier(&args);
+}
+
+void stomp_write_barrier_ephemeral(bool is_runtime_suspended, uint8_t* ephemeral_lo, uint8_t* ephemeral_hi)
+{
+    WriteBarrierParameters args = {};
+    args.operation = WriteBarrierOp::StompEphemeral;
+    args.is_runtime_suspended = is_runtime_suspended;
+    args.ephemeral_lo = g_gc_ephemeral_low;
+    args.ephemeral_hi = g_gc_ephemeral_high;
+#ifdef MULTIPLE_HEAPS
+    // It is not correct to update the EE's g_ephemeral_low and g_ephemeral_high
+    // to anything other than their default values when using Server GC, since
+    // there is no single ephemeral generation across all of the heaps.
+    // Server GC write barriers do not reference these two globals, but ErectWriteBarrier does.
+    //
+    // When MULTIPLE_HEAPS is defined, g_gc_ephemeral_low and g_gc_ephemeral_high should
+    // always have their default values.
+    assert(args.ephemeral_lo == (uint8_t*)1);
+    assert(args.ephemeral_hi == (uint8_t*)~0);
+#endif // MULTIPLE_HEAPS
+    GCToEEInterface::StompWriteBarrier(&args);
+}
+
+void stomp_write_barrier_initialize()
+{
+    WriteBarrierParameters args = {};
+    args.operation = WriteBarrierOp::Initialize;
+    args.is_runtime_suspended = true;
+    args.requires_upper_bounds_check = false;
+    args.card_table = g_gc_card_table;
+    args.lowest_address = g_gc_lowest_address;
+    args.highest_address = g_gc_highest_address;
+    GCToEEInterface::StompWriteBarrier(&args);
+}
+
+#endif // DACCESS_COMPILE
+
 //extract the low bits [0,low[ of a uint32_t
 #define lowbits(wrd, bits) ((wrd) & ((1 << (bits))-1))
 //extract the high bits [high, 32] of a uint32_t
@@ -3406,7 +3455,7 @@ inline
 size_t ro_seg_begin_index (heap_segment* seg)
 {
     size_t begin_index = (size_t)seg / gc_heap::min_segment_size;
-    begin_index = max (begin_index, (size_t)g_lowest_address / gc_heap::min_segment_size);
+    begin_index = max (begin_index, (size_t)g_gc_lowest_address / gc_heap::min_segment_size);
     return begin_index;
 }
 
@@ -3414,14 +3463,14 @@ inline
 size_t ro_seg_end_index (heap_segment* seg)
 {
     size_t end_index = (size_t)(heap_segment_reserved (seg) - 1) / gc_heap::min_segment_size;
-    end_index = min (end_index, (size_t)g_highest_address / gc_heap::min_segment_size);
+    end_index = min (end_index, (size_t)g_gc_highest_address / gc_heap::min_segment_size);
     return end_index;
 }
 
 void seg_mapping_table_add_ro_segment (heap_segment* seg)
 {
 #ifdef GROWABLE_SEG_MAPPING_TABLE
-    if ((heap_segment_reserved (seg) <= g_lowest_address) || (heap_segment_mem (seg) >= g_highest_address))
+    if ((heap_segment_reserved (seg) <= g_gc_lowest_address) || (heap_segment_mem (seg) >= g_gc_highest_address))
         return;
 #endif //GROWABLE_SEG_MAPPING_TABLE
 
@@ -3605,7 +3654,7 @@ gc_heap* seg_mapping_table_heap_of_worker (uint8_t* o)
 gc_heap* seg_mapping_table_heap_of (uint8_t* o)
 {
 #ifdef GROWABLE_SEG_MAPPING_TABLE
-    if ((o < g_lowest_address) || (o >= g_highest_address))
+    if ((o < g_gc_lowest_address) || (o >= g_gc_highest_address))
         return 0;
 #endif //GROWABLE_SEG_MAPPING_TABLE
 
@@ -3615,7 +3664,7 @@ gc_heap* seg_mapping_table_heap_of (uint8_t* o)
 gc_heap* seg_mapping_table_heap_of_gc (uint8_t* o)
 {
 #if defined(FEATURE_BASICFREEZE) && defined(GROWABLE_SEG_MAPPING_TABLE)
-    if ((o < g_lowest_address) || (o >= g_highest_address))
+    if ((o < g_gc_lowest_address) || (o >= g_gc_highest_address))
         return 0;
 #endif //FEATURE_BASICFREEZE || GROWABLE_SEG_MAPPING_TABLE
 
@@ -3627,7 +3676,7 @@ gc_heap* seg_mapping_table_heap_of_gc (uint8_t* o)
 heap_segment* seg_mapping_table_segment_of (uint8_t* o)
 {
 #if defined(FEATURE_BASICFREEZE) && defined(GROWABLE_SEG_MAPPING_TABLE)
-    if ((o < g_lowest_address) || (o >= g_highest_address))
+    if ((o < g_gc_lowest_address) || (o >= g_gc_highest_address))
 #ifdef FEATURE_BASICFREEZE
         return ro_segment_lookup (o);
 #else
@@ -3670,7 +3719,7 @@ heap_segment* seg_mapping_table_segment_of (uint8_t* o)
 
 #ifdef FEATURE_BASICFREEZE
     // TODO: This was originally written assuming that the seg_mapping_table would always contain entries for ro 
-    // segments whenever the ro segment falls into the [g_lowest_address,g_highest_address) range.  I.e., it had an 
+    // segments whenever the ro segment falls into the [g_gc_lowest_address,g_gc_highest_address) range.  I.e., it had an 
     // extra "&& (size_t)(entry->seg1) & ro_in_entry" expression.  However, at the moment, grow_brick_card_table does 
     // not correctly go through the ro segments and add them back to the seg_mapping_table when the [lowest,highest) 
     // range changes.  We should probably go ahead and modify grow_brick_card_table and put back the 
@@ -4070,8 +4119,8 @@ BOOL reserve_initial_memory (size_t normal_size, size_t large_size, size_t num_h
     memory_details.current_block_normal = 0;
     memory_details.current_block_large = 0;
 
-    g_lowest_address = MAX_PTR;
-    g_highest_address = 0;
+    g_gc_lowest_address = MAX_PTR;
+    g_gc_highest_address = 0;
 
     if (((size_t)MAX_PTR - large_size) < normal_size)
     {
@@ -4091,8 +4140,8 @@ BOOL reserve_initial_memory (size_t normal_size, size_t large_size, size_t num_h
     uint8_t* allatonce_block = (uint8_t*)virtual_alloc (requestedMemory);
     if (allatonce_block)
     {
-        g_lowest_address =  allatonce_block;
-        g_highest_address = allatonce_block + (memory_details.block_count * (large_size + normal_size));
+        g_gc_lowest_address =  allatonce_block;
+        g_gc_highest_address = allatonce_block + (memory_details.block_count * (large_size + normal_size));
         memory_details.allocation_pattern = initial_memory_details::ALLATONCE;
 
         for(size_t i = 0; i < memory_details.block_count; i++)
@@ -4115,8 +4164,8 @@ BOOL reserve_initial_memory (size_t normal_size, size_t large_size, size_t num_h
             if (b2)
             {
                 memory_details.allocation_pattern = initial_memory_details::TWO_STAGE;
-                g_lowest_address = min(b1,b2);
-                g_highest_address = max(b1 + memory_details.block_count*normal_size,
+                g_gc_lowest_address = min(b1,b2);
+                g_gc_highest_address = max(b1 + memory_details.block_count*normal_size,
                                         b2 + memory_details.block_count*large_size);
                 for(size_t i = 0; i < memory_details.block_count; i++)
                 {
@@ -4162,10 +4211,10 @@ BOOL reserve_initial_memory (size_t normal_size, size_t large_size, size_t num_h
                 }
                 else
                 {
-                    if (current_block->memory_base < g_lowest_address)
-                        g_lowest_address =  current_block->memory_base;
-                    if (((uint8_t *) current_block->memory_base + block_size) > g_highest_address)
-                        g_highest_address = (current_block->memory_base + block_size);
+                    if (current_block->memory_base < g_gc_lowest_address)
+                        g_gc_lowest_address =  current_block->memory_base;
+                    if (((uint8_t *) current_block->memory_base + block_size) > g_gc_highest_address)
+                        g_gc_highest_address = (current_block->memory_base + block_size);
                 }
                 reserve_success = TRUE;
             }
@@ -4607,22 +4656,22 @@ gc_heap::get_segment (size_t size, BOOL loh_p)
         {
             uint8_t* start;
             uint8_t* end;
-            if (mem < g_lowest_address)
+            if (mem < g_gc_lowest_address)
             {
                 start =  (uint8_t*)mem;
             }
             else
             {
-                start = (uint8_t*)g_lowest_address;
+                start = (uint8_t*)g_gc_lowest_address;
             }
 
-            if (((uint8_t*)mem + size) > g_highest_address)
+            if (((uint8_t*)mem + size) > g_gc_highest_address)
             {
                 end = (uint8_t*)mem + size;
             }
             else
             {
-                end = (uint8_t*)g_highest_address;
+                end = (uint8_t*)g_gc_highest_address;
             }
 
             if (gc_heap::grow_brick_card_tables (start, end, size, result, __this, loh_p) != 0)
@@ -5321,7 +5370,7 @@ heap_segment* gc_heap::segment_of (uint8_t* add, ptrdiff_t& delta, BOOL verify_p
     uint8_t* sadd = add;
     heap_segment* hs = 0;
     heap_segment* hs1 = 0;
-    if (!((add >= g_lowest_address) && (add < g_highest_address)))
+    if (!((add >= g_gc_lowest_address) && (add < g_gc_highest_address)))
     {
         delta = 0;
         return 0;
@@ -6378,7 +6427,7 @@ void gc_heap::set_card (size_t card)
 inline
 void gset_card (size_t card)
 {
-    g_card_table [card_word (card)] |= (1 << card_bit (card));
+    g_gc_card_table [card_word (card)] |= (1 << card_bit (card));
 }
 
 inline
@@ -6489,7 +6538,7 @@ size_t size_card_bundle_of (uint8_t* from, uint8_t* end)
 
 uint32_t* translate_card_bundle_table (uint32_t* cb)
 {
-    return (uint32_t*)((uint8_t*)cb - ((((size_t)g_lowest_address) / (card_size*card_word_width*card_bundle_size*card_bundle_word_width)) * sizeof (uint32_t)));
+    return (uint32_t*)((uint8_t*)cb - ((((size_t)g_gc_lowest_address) / (card_size*card_word_width*card_bundle_size*card_bundle_word_width)) * sizeof (uint32_t)));
 }
 
 void gc_heap::enable_card_bundles ()
@@ -6701,7 +6750,7 @@ size_t size_mark_array_of (uint8_t* from, uint8_t* end)
 // according to the lowest_address.
 uint32_t* translate_mark_array (uint32_t* ma)
 {
-    return (uint32_t*)((uint8_t*)ma - size_mark_array_of (0, g_lowest_address));
+    return (uint32_t*)((uint8_t*)ma - size_mark_array_of (0, g_gc_lowest_address));
 }
 
 // from and end must be page aligned addresses. 
@@ -6829,16 +6878,16 @@ void release_card_table (uint32_t* c_table)
         {
             destroy_card_table (c_table);
             // sever the link from the parent
-            if (&g_card_table[card_word (gcard_of(g_lowest_address))] == c_table)
+            if (&g_gc_card_table[card_word (gcard_of(g_gc_lowest_address))] == c_table)
             {
-                g_card_table = 0;
+                g_gc_card_table = 0;
 #ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
                 SoftwareWriteWatch::StaticClose();
 #endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
             }
             else
             {
-                uint32_t* p_table = &g_card_table[card_word (gcard_of(g_lowest_address))];
+                uint32_t* p_table = &g_gc_card_table[card_word (gcard_of(g_gc_lowest_address))];
                 if (p_table)
                 {
                     while (p_table && (card_table_next (p_table) != c_table))
@@ -6860,8 +6909,8 @@ void destroy_card_table (uint32_t* c_table)
 
 uint32_t* gc_heap::make_card_table (uint8_t* start, uint8_t* end)
 {
-    assert (g_lowest_address == start);
-    assert (g_highest_address == end);
+    assert (g_gc_lowest_address == start);
+    assert (g_gc_highest_address == end);
 
     uint32_t virtual_reserve_flags = VirtualReserveFlags::None;
 
@@ -6881,7 +6930,7 @@ uint32_t* gc_heap::make_card_table (uint8_t* start, uint8_t* end)
     if (can_use_write_watch_for_card_table())
     {
         virtual_reserve_flags |= VirtualReserveFlags::WriteWatch;
-        cb = size_card_bundle_of (g_lowest_address, g_highest_address);
+        cb = size_card_bundle_of (g_gc_lowest_address, g_gc_highest_address);
     }
 #endif //CARD_BUNDLE
 
@@ -6897,7 +6946,7 @@ uint32_t* gc_heap::make_card_table (uint8_t* start, uint8_t* end)
 #endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
 
 #ifdef GROWABLE_SEG_MAPPING_TABLE
-    size_t st = size_seg_mapping_table_of (g_lowest_address, g_highest_address);
+    size_t st = size_seg_mapping_table_of (g_gc_lowest_address, g_gc_highest_address);
     size_t st_table_offset = sizeof(card_table_info) + cs + bs + cb + wws;
     size_t st_table_offset_aligned = align_for_seg_mapping_table (st_table_offset);
 
@@ -6952,7 +7001,7 @@ uint32_t* gc_heap::make_card_table (uint8_t* start, uint8_t* end)
 #ifdef GROWABLE_SEG_MAPPING_TABLE
     seg_mapping_table = (seg_mapping*)(mem + st_table_offset_aligned);
     seg_mapping_table = (seg_mapping*)((uint8_t*)seg_mapping_table - 
-                                        size_seg_mapping_table_of (0, (align_lower_segment (g_lowest_address))));
+                                        size_seg_mapping_table_of (0, (align_lower_segment (g_gc_lowest_address))));
 #endif //GROWABLE_SEG_MAPPING_TABLE
 
 #ifdef MARK_ARRAY
@@ -6991,10 +7040,10 @@ int gc_heap::grow_brick_card_tables (uint8_t* start,
                                      gc_heap* hp, 
                                      BOOL loh_p)
 {
-    uint8_t* la = g_lowest_address;
-    uint8_t* ha = g_highest_address;
-    uint8_t* saved_g_lowest_address = min (start, g_lowest_address);
-    uint8_t* saved_g_highest_address = max (end, g_highest_address);
+    uint8_t* la = g_gc_lowest_address;
+    uint8_t* ha = g_gc_highest_address;
+    uint8_t* saved_g_lowest_address = min (start, g_gc_lowest_address);
+    uint8_t* saved_g_highest_address = max (end, g_gc_highest_address);
 #ifdef BACKGROUND_GC
     // This value is only for logging purpose - it's not necessarily exactly what we 
     // would commit for mark array but close enough for diagnostics purpose.
@@ -7024,18 +7073,18 @@ int gc_heap::grow_brick_card_tables (uint8_t* start,
 #endif // BIT64
                 ps *= 2;
 
-            if (saved_g_lowest_address < g_lowest_address)
+            if (saved_g_lowest_address < g_gc_lowest_address)
             {
-                if (ps > (size_t)g_lowest_address)
+                if (ps > (size_t)g_gc_lowest_address)
                     saved_g_lowest_address = (uint8_t*)OS_PAGE_SIZE;
                 else
                 {
-                    assert (((size_t)g_lowest_address - ps) >= OS_PAGE_SIZE);
-                    saved_g_lowest_address = min (saved_g_lowest_address, (g_lowest_address - ps));
+                    assert (((size_t)g_gc_lowest_address - ps) >= OS_PAGE_SIZE);
+                    saved_g_lowest_address = min (saved_g_lowest_address, (g_gc_lowest_address - ps));
                 }
             }
 
-            if (saved_g_highest_address > g_highest_address)
+            if (saved_g_highest_address > g_gc_highest_address)
             {
                 saved_g_highest_address = max ((saved_g_lowest_address + ps), saved_g_highest_address);
                 if (saved_g_highest_address > top)
@@ -7048,7 +7097,7 @@ int gc_heap::grow_brick_card_tables (uint8_t* start,
 
         bool write_barrier_updated = false;
         uint32_t virtual_reserve_flags = VirtualReserveFlags::None;
-        uint32_t* saved_g_card_table = g_card_table;
+        uint32_t* saved_g_card_table = g_gc_card_table;
         uint32_t* ct = 0;
         uint32_t* translated_ct = 0;
         short* bt = 0;
@@ -7131,7 +7180,7 @@ int gc_heap::grow_brick_card_tables (uint8_t* start,
         card_table_refcount (ct) = 0;
         card_table_lowest_address (ct) = saved_g_lowest_address;
         card_table_highest_address (ct) = saved_g_highest_address;
-        card_table_next (ct) = &g_card_table[card_word (gcard_of (la))];
+        card_table_next (ct) = &g_gc_card_table[card_word (gcard_of (la))];
 
         //clear the card table
 /*
@@ -7158,9 +7207,9 @@ int gc_heap::grow_brick_card_tables (uint8_t* start,
             seg_mapping* new_seg_mapping_table = (seg_mapping*)(mem + st_table_offset_aligned);
             new_seg_mapping_table = (seg_mapping*)((uint8_t*)new_seg_mapping_table -
                                               size_seg_mapping_table_of (0, (align_lower_segment (saved_g_lowest_address))));
-            memcpy(&new_seg_mapping_table[seg_mapping_word_of(g_lowest_address)],
-                &seg_mapping_table[seg_mapping_word_of(g_lowest_address)],
-                size_seg_mapping_table_of(g_lowest_address, g_highest_address));
+            memcpy(&new_seg_mapping_table[seg_mapping_word_of(g_gc_lowest_address)],
+                &seg_mapping_table[seg_mapping_word_of(g_gc_lowest_address)],
+                size_seg_mapping_table_of(g_gc_lowest_address, g_gc_highest_address));
 
             seg_mapping_table = new_seg_mapping_table;
         }
@@ -7222,12 +7271,14 @@ int gc_heap::grow_brick_card_tables (uint8_t* start,
                 // Note on points where the runtime is suspended anywhere in this function. Upon an attempt to suspend the
                 // runtime, a different thread may suspend first, causing this thread to block at the point of the suspend call.
                 // So, at any suspend point, externally visible state needs to be consistent, as code that depends on that state
-                // may run while this thread is blocked. This includes updates to g_card_table, g_lowest_address, and
-                // g_highest_address.
+                // may run while this thread is blocked. This includes updates to g_gc_card_table, g_gc_lowest_address, and
+                // g_gc_highest_address.
                 suspend_EE();
             }
 
-            g_card_table = translated_ct;
+            g_gc_card_table = translated_ct;
+            g_gc_lowest_address = saved_g_lowest_address;
+            g_gc_highest_address = saved_g_highest_address;
 
             SoftwareWriteWatch::SetResizedUntranslatedTable(
                 mem + sw_ww_table_offset,
@@ -7239,7 +7290,7 @@ int gc_heap::grow_brick_card_tables (uint8_t* start,
             // grow version of the write barrier.  This test tells us if the new
             // segment was allocated at a lower address than the old, requiring
             // that we start doing an upper bounds check in the write barrier.
-            StompWriteBarrierResize(true, la != saved_g_lowest_address);
+            stomp_write_barrier_resize(true, la != saved_g_lowest_address);
             write_barrier_updated = true;
 
             if (!is_runtime_suspended)
@@ -7250,9 +7301,12 @@ int gc_heap::grow_brick_card_tables (uint8_t* start,
         else
 #endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
         {
-            g_card_table = translated_ct;
+            g_gc_card_table = translated_ct;
         }
 
+        g_gc_lowest_address = saved_g_lowest_address;
+        g_gc_highest_address = saved_g_highest_address;
+
         if (!write_barrier_updated)
         {
             // This passes a bool telling whether we need to switch to the post
@@ -7263,19 +7317,9 @@ int gc_heap::grow_brick_card_tables (uint8_t* start,
             // to be changed, so we are doing this after all global state has
             // been updated. See the comment above suspend_EE() above for more
             // info.
-            StompWriteBarrierResize(!!IsGCThread(), la != saved_g_lowest_address);
+            stomp_write_barrier_resize(!!IsGCThread(), la != saved_g_lowest_address);
         }
 
-        // We need to make sure that other threads executing checked write barriers
-        // will see the g_card_table update before g_lowest/highest_address updates.
-        // Otherwise, the checked write barrier may AV accessing the old card table
-        // with address that it does not cover. Write barriers access card table 
-        // without memory barriers for performance reasons, so we need to flush 
-        // the store buffers here.
-        GCToOSInterface::FlushProcessWriteBuffers();
-
-        g_lowest_address = saved_g_lowest_address;
-        VolatileStore(&g_highest_address, saved_g_highest_address);
 
         return 0;
         
@@ -7284,7 +7328,7 @@ fail:
 
         if (mem)
         {
-            assert(g_card_table == saved_g_card_table);
+            assert(g_gc_card_table == saved_g_card_table);
 
             //delete (uint32_t*)((uint8_t*)ct - sizeof(card_table_info));
             if (!GCToOSInterface::VirtualRelease (mem, alloc_size_aligned))
@@ -7442,7 +7486,7 @@ void gc_heap::copy_brick_card_table()
     assert (ha == card_table_highest_address (&old_card_table[card_word (card_of (la))]));
 
     /* todo: Need a global lock for this */
-    uint32_t* ct = &g_card_table[card_word (gcard_of (g_lowest_address))];
+    uint32_t* ct = &g_gc_card_table[card_word (gcard_of (g_gc_lowest_address))];
     own_card_table (ct);
     card_table = translate_card_table (ct);
     /* End of global lock */
@@ -7455,8 +7499,8 @@ void gc_heap::copy_brick_card_table()
     if (gc_can_use_concurrent)
     {
         mark_array = translate_mark_array (card_table_mark_array (ct));
-        assert (mark_word_of (g_highest_address) ==
-            mark_word_of (align_on_mark_word (g_highest_address)));
+        assert (mark_word_of (g_gc_highest_address) ==
+            mark_word_of (align_on_mark_word (g_gc_highest_address)));
     }
     else
         mark_array = NULL;
@@ -7465,13 +7509,13 @@ void gc_heap::copy_brick_card_table()
 #ifdef CARD_BUNDLE
 #if defined(MARK_ARRAY) && defined(_DEBUG)
 #ifdef GROWABLE_SEG_MAPPING_TABLE
-    size_t st = size_seg_mapping_table_of (g_lowest_address, g_highest_address);
+    size_t st = size_seg_mapping_table_of (g_gc_lowest_address, g_gc_highest_address);
 #else  //GROWABLE_SEG_MAPPING_TABLE
     size_t st = 0;
 #endif //GROWABLE_SEG_MAPPING_TABLE
 #endif //MARK_ARRAY && _DEBUG
     card_bundle_table = translate_card_bundle_table (card_table_card_bundle_table (ct));
-    assert (&card_bundle_table [card_bundle_word (cardw_card_bundle (card_word (card_of (g_lowest_address))))] ==
+    assert (&card_bundle_table [card_bundle_word (cardw_card_bundle (card_word (card_of (g_gc_lowest_address))))] ==
             card_table_card_bundle_table (ct));
 
     //set the card table if we are in a heap growth scenario
@@ -9315,7 +9359,7 @@ void gc_heap::update_card_table_bundle()
             {
                 size_t bcardw = (uint32_t*)(max(g_addresses[i],base_address)) - &card_table[0];
                 size_t ecardw = (uint32_t*)(min(g_addresses[i]+OS_PAGE_SIZE, high_address)) - &card_table[0];
-                assert (bcardw >= card_word (card_of (g_lowest_address)));
+                assert (bcardw >= card_word (card_of (g_gc_lowest_address)));
 
                 card_bundles_set (cardw_card_bundle (bcardw),
                                   cardw_card_bundle (align_cardw_on_bundle (ecardw)));
@@ -9627,7 +9671,7 @@ void gc_heap::adjust_ephemeral_limits (bool is_runtime_suspended)
                  (size_t)ephemeral_low, (size_t)ephemeral_high))
 
     // This updates the write barrier helpers with the new info.
-    StompWriteBarrierEphemeral(is_runtime_suspended);
+    stomp_write_barrier_ephemeral(is_runtime_suspended, ephemeral_low, ephemeral_high);
 }
 
 #if defined(TRACE_GC) || defined(GC_CONFIG_DRIVEN)
@@ -9800,9 +9844,9 @@ HRESULT gc_heap::initialize_gc (size_t segment_size,
 
     settings.first_init();
 
-    g_card_table = make_card_table (g_lowest_address, g_highest_address);
+    g_gc_card_table = make_card_table (g_gc_lowest_address, g_gc_highest_address);
 
-    if (!g_card_table)
+    if (!g_gc_card_table)
         return E_OUTOFMEMORY;
 
     gc_started = FALSE;
@@ -10285,7 +10329,7 @@ gc_heap::init_gc_heap (int  h_number)
 #endif //MULTIPLE_HEAPS
 
     /* todo: Need a global lock for this */
-    uint32_t* ct = &g_card_table [card_word (card_of (g_lowest_address))];
+    uint32_t* ct = &g_gc_card_table [card_word (card_of (g_gc_lowest_address))];
     own_card_table (ct);
     card_table = translate_card_table (ct);
     /* End of global lock */
@@ -10296,13 +10340,13 @@ gc_heap::init_gc_heap (int  h_number)
 
 #ifdef CARD_BUNDLE
     card_bundle_table = translate_card_bundle_table (card_table_card_bundle_table (ct));
-    assert (&card_bundle_table [card_bundle_word (cardw_card_bundle (card_word (card_of (g_lowest_address))))] ==
+    assert (&card_bundle_table [card_bundle_word (cardw_card_bundle (card_word (card_of (g_gc_lowest_address))))] ==
             card_table_card_bundle_table (ct));
 #endif //CARD_BUNDLE
 
 #ifdef MARK_ARRAY
     if (gc_can_use_concurrent)
-        mark_array = translate_mark_array (card_table_mark_array (&g_card_table[card_word (card_of (g_lowest_address))]));
+        mark_array = translate_mark_array (card_table_mark_array (&g_gc_card_table[card_word (card_of (g_gc_lowest_address))]));
     else
         mark_array = NULL;
 #endif //MARK_ARRAY
@@ -15166,7 +15210,7 @@ void gc_heap::gc1()
 
     vm_heap->GcCondemnedGeneration = settings.condemned_generation;
 
-    assert (g_card_table == card_table);
+    assert (g_gc_card_table == card_table);
 
     {
         if (n == max_generation)
@@ -16373,7 +16417,7 @@ int gc_heap::garbage_collect (int n)
         for (int i = 0; i < n_heaps; i++)
         {
             //copy the card and brick tables
-            if (g_card_table != g_heaps[i]->card_table)
+            if (g_gc_card_table != g_heaps[i]->card_table)
             {
                 g_heaps[i]->copy_brick_card_table();
             }
@@ -16397,7 +16441,7 @@ int gc_heap::garbage_collect (int n)
             }
 #endif //BACKGROUND_GC
         // check for card table growth
-        if (g_card_table != card_table)
+        if (g_gc_card_table != card_table)
             copy_brick_card_table();
 
 #endif //MULTIPLE_HEAPS
@@ -22373,7 +22417,7 @@ void gc_heap::plan_phase (int condemned_gen_number)
         for (i = 0; i < n_heaps; i++)
         {
             //copy the card and brick tables
-            if (g_card_table!= g_heaps[i]->card_table)
+            if (g_gc_card_table!= g_heaps[i]->card_table)
             {
                 g_heaps[i]->copy_brick_card_table();
             }
@@ -25079,14 +25123,14 @@ BOOL gc_heap::commit_mark_array_new_seg (gc_heap* hp,
 
         if (new_card_table == 0)
         {
-            new_card_table = g_card_table;
+            new_card_table = g_gc_card_table;
         }
 
         if (hp->card_table != new_card_table)
         {
             if (new_lowest_address == 0)
             {
-                new_lowest_address = g_lowest_address;
+                new_lowest_address = g_gc_lowest_address;
             }
 
             uint32_t* ct = &new_card_table[card_word (gcard_of (new_lowest_address))];
@@ -29076,7 +29120,7 @@ generation* gc_heap::expand_heap (int condemned_generation,
         return consing_gen;
 
     //copy the card and brick tables
-    if (g_card_table!= card_table)
+    if (g_gc_card_table!= card_table)
         copy_brick_card_table();
 
     BOOL new_segment_p = (heap_segment_next (new_seg) == 0);
@@ -32386,7 +32430,7 @@ void gc_heap::clear_all_mark_array()
 void gc_heap::verify_mark_array_cleared (heap_segment* seg)
 {
 #if defined (VERIFY_HEAP) && defined (MARK_ARRAY)
-    assert (card_table == g_card_table);
+    assert (card_table == g_gc_card_table);
     size_t  markw = mark_word_of (heap_segment_mem (seg));
     size_t  markw_end = mark_word_of (heap_segment_reserved (seg));
 
@@ -32734,8 +32778,8 @@ gc_heap::verify_heap (BOOL begin_gc_p)
 #endif //BACKGROUND_GC 
 
 #ifndef MULTIPLE_HEAPS
-    if ((g_ephemeral_low != generation_allocation_start (generation_of (max_generation - 1))) ||
-        (g_ephemeral_high != heap_segment_reserved (ephemeral_heap_segment)))
+    if ((g_gc_ephemeral_low != generation_allocation_start (generation_of (max_generation - 1))) ||
+        (g_gc_ephemeral_high != heap_segment_reserved (ephemeral_heap_segment)))
     {
         FATAL_GC_ERROR();
     }
@@ -32794,7 +32838,7 @@ gc_heap::verify_heap (BOOL begin_gc_p)
         for (int i = 0; i < n_heaps; i++)
         {
             //copy the card and brick tables
-            if (g_card_table != g_heaps[i]->card_table)
+            if (g_gc_card_table != g_heaps[i]->card_table)
             {
                 g_heaps[i]->copy_brick_card_table();
             }
@@ -32803,7 +32847,7 @@ gc_heap::verify_heap (BOOL begin_gc_p)
         current_join->restart();
     }
 #else
-        if (g_card_table != card_table)
+        if (g_gc_card_table != card_table)
             copy_brick_card_table();
 #endif //MULTIPLE_HEAPS
 
@@ -33228,11 +33272,11 @@ HRESULT GCHeap::Shutdown ()
     //CloseHandle (WaitForGCEvent);
 
     //find out if the global card table hasn't been used yet
-    uint32_t* ct = &g_card_table[card_word (gcard_of (g_lowest_address))];
+    uint32_t* ct = &g_gc_card_table[card_word (gcard_of (g_gc_lowest_address))];
     if (card_table_refcount (ct) == 0)
     {
         destroy_card_table (ct);
-        g_card_table = 0;
+        g_gc_card_table = 0;
 #ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
         SoftwareWriteWatch::StaticClose();
 #endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
@@ -33392,7 +33436,7 @@ HRESULT GCHeap::Initialize ()
         return E_FAIL;
     }
 
-    StompWriteBarrierResize(true, false);
+    stomp_write_barrier_initialize();
 
 #ifndef FEATURE_REDHAWK // Redhawk forces relocation a different way
 #if defined (STRESS_HEAP) && !defined (MULTIPLE_HEAPS)
@@ -33513,7 +33557,7 @@ Object * GCHeap::NextObj (Object * object)
     uint8_t* o = (uint8_t*)object;
 
 #ifndef FEATURE_BASICFREEZE
-    if (!((o < g_highest_address) && (o >= g_lowest_address)))
+    if (!((o < g_gc_highest_address) && (o >= g_gc_lowest_address)))
     {
         return NULL;
     }
@@ -33584,7 +33628,7 @@ BOOL GCHeap::IsHeapPointer (void* vpObject, BOOL small_heap_only)
 
     uint8_t* object = (uint8_t*) vpObject;
 #ifndef FEATURE_BASICFREEZE
-    if (!((object < g_highest_address) && (object >= g_lowest_address)))
+    if (!((object < g_gc_highest_address) && (object >= g_gc_lowest_address)))
         return FALSE;
 #endif //!FEATURE_BASICFREEZE
 
@@ -35695,12 +35739,12 @@ GCHeap::SetCardsAfterBulkCopy( Object **StartPoint, size_t len )
     end = StartPoint + (len/sizeof(Object*));
     while (rover < end)
     {
-        if ( (((uint8_t*)*rover) >= g_ephemeral_low) && (((uint8_t*)*rover) < g_ephemeral_high) )
+        if ( (((uint8_t*)*rover) >= g_gc_ephemeral_low) && (((uint8_t*)*rover) < g_gc_ephemeral_high) )
         {
             // Set Bit For Card and advance to next card
             size_t card = gcard_of ((uint8_t*)rover);
 
-            Interlocked::Or (&g_card_table[card/card_word_width], (1U << (card % card_word_width)));
+            Interlocked::Or (&g_gc_card_table[card/card_word_width], (1U << (card % card_word_width)));
             // Skip to next card for the object
             rover = (Object**)align_on_card ((uint8_t*)(rover+1));
         }
@@ -36568,7 +36612,7 @@ void initGCShadow()
     if (!(g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_BARRIERCHECK))
         return;
 
-    size_t len = g_highest_address - g_lowest_address;
+    size_t len = g_gc_highest_address - g_gc_lowest_address;
     if (len > (size_t)(g_GCShadowEnd - g_GCShadow)) 
     {
         deleteGCShadow();
@@ -36587,10 +36631,10 @@ void initGCShadow()
         g_GCShadowEnd += len;
     }
 
-    // save the value of g_lowest_address at this time.  If this value changes before
+    // save the value of g_gc_lowest_address at this time.  If this value changes before
     // the next call to checkGCWriteBarrier() it means we extended the heap (with a
     // large object segment most probably), and the whole shadow segment is inconsistent.
-    g_shadow_lowest_address = g_lowest_address;
+    g_shadow_lowest_address = g_gc_lowest_address;
 
         //****** Copy the whole GC heap ******
     //
@@ -36600,7 +36644,7 @@ void initGCShadow()
     generation* gen = gc_heap::generation_of (max_generation);
     heap_segment* seg = heap_segment_rw (generation_start_segment (gen));
 
-    ptrdiff_t delta = g_GCShadow - g_lowest_address;
+    ptrdiff_t delta = g_GCShadow - g_gc_lowest_address;
     BOOL small_object_segments = TRUE;
     while(1)
     {
@@ -36628,7 +36672,7 @@ void initGCShadow()
     // test to see if 'ptr' was only updated via the write barrier.
 inline void testGCShadow(Object** ptr)
 {
-    Object** shadow = (Object**) &g_GCShadow[((uint8_t*) ptr - g_lowest_address)];
+    Object** shadow = (Object**) &g_GCShadow[((uint8_t*) ptr - g_gc_lowest_address)];
     if (*ptr != 0 && (uint8_t*) shadow < g_GCShadowEnd && *ptr != *shadow)
     {
 
@@ -36687,9 +36731,9 @@ void testGCShadowHelper (uint8_t* x)
     // Walk the whole heap, looking for pointers that were not updated with the write barrier.
 void checkGCWriteBarrier()
 {
-    // g_shadow_lowest_address != g_lowest_address means the GC heap was extended by a segment
+    // g_shadow_lowest_address != g_gc_lowest_address means the GC heap was extended by a segment
     // and the GC shadow segment did not track that change!
-    if (g_GCShadowEnd <= g_GCShadow || g_shadow_lowest_address != g_lowest_address)
+    if (g_GCShadowEnd <= g_GCShadow || g_shadow_lowest_address != g_gc_lowest_address)
     {
         // No shadow stack, nothing to check.
         return;
index da047ad..b7f1e95 100644 (file)
@@ -137,6 +137,12 @@ class DacHeapWalker;
 
 #define MP_LOCKS
 
+extern "C" uint32_t* g_gc_card_table;
+extern "C" uint8_t* g_gc_lowest_address;
+extern "C" uint8_t* g_gc_highest_address;
+extern "C" uint8_t* g_gc_ephemeral_low;
+extern "C" uint8_t* g_gc_ephemeral_high;
+
 namespace WKS {
     ::IGCHeapInternal* CreateGCHeap();
     class GCHeap;
index 2e6bfce..d1ccddd 100644 (file)
@@ -26,28 +26,24 @@ IGCHeapInternal* g_theGCHeap;
 IGCToCLR* g_theGCToCLR;
 #endif // FEATURE_STANDALONE_GC
 
-/* global versions of the card table and brick table */ 
-GPTR_IMPL(uint32_t,g_card_table);
-
-/* absolute bounds of the GC memory */
-GPTR_IMPL_INIT(uint8_t,g_lowest_address,0);
-GPTR_IMPL_INIT(uint8_t,g_highest_address,0);
-
 #ifdef GC_CONFIG_DRIVEN
 GARY_IMPL(size_t, gc_global_mechanisms, MAX_GLOBAL_GC_MECHANISMS_COUNT);
 #endif //GC_CONFIG_DRIVEN
 
 #ifndef DACCESS_COMPILE
 
-uint8_t* g_ephemeral_low = (uint8_t*)1;
-uint8_t* g_ephemeral_high = (uint8_t*)~0;
-
 #ifdef WRITE_BARRIER_CHECK
 uint8_t* g_GCShadow;
 uint8_t* g_GCShadowEnd;
 uint8_t* g_shadow_lowest_address = NULL;
 #endif
 
+uint32_t* g_gc_card_table;
+uint8_t* g_gc_lowest_address  = 0;
+uint8_t* g_gc_highest_address = 0;
+uint8_t* g_gc_ephemeral_low   = (uint8_t*)1;
+uint8_t* g_gc_ephemeral_high  = (uint8_t*)~0;
+
 VOLATILE(int32_t) m_GCLock = -1;
 
 #ifdef GC_CONFIG_DRIVEN
index a4f86e1..3b64586 100644 (file)
@@ -166,4 +166,11 @@ inline void GCToEEInterface::DiagWalkBGCSurvivors(void* gcContext)
     assert(g_theGCToCLR != nullptr);
     return g_theGCToCLR->DiagWalkBGCSurvivors(gcContext);
 }
+
+inline void GCToEEInterface::StompWriteBarrier(WriteBarrierParameters* args)
+{
+    assert(g_theGCToCLR != nullptr);
+    g_theGCToCLR->StompWriteBarrier(args);
+}
+
 #endif // __GCTOENV_EE_STANDALONE_INL__
index 3e6631b..c5f87ef 100644 (file)
@@ -123,6 +123,11 @@ public:
     // At the end of a background GC, gives the diagnostics code a chance to run.
     virtual
     void DiagWalkBGCSurvivors(void* gcContext) = 0;
+
+    // Informs the EE of changes to the location of the card table, potentially updating the write
+    // barrier if it needs to be updated.
+    virtual
+    void StompWriteBarrier(WriteBarrierParameters* args) = 0;
 };
 
 #endif // _GCINTERFACE_EE_H_
index 1f66809..1457848 100644 (file)
@@ -41,6 +41,57 @@ typedef enum
     walk_for_loh = 3
 } walk_surv_type;
 
+// Different operations that can be done by GCToEEInterface::StompWriteBarrier
+enum class WriteBarrierOp
+{
+    StompResize,
+    StompEphemeral,
+    Initialize
+};
+
+// Arguments to GCToEEInterface::StompWriteBarrier
+struct WriteBarrierParameters
+{
+    // The operation that StompWriteBarrier will perform.
+    WriteBarrierOp operation;
+
+    // Whether or not the runtime is currently suspended. If it is not,
+    // the EE will need to suspend it before bashing the write barrier.
+    // Used for all operations.
+    bool is_runtime_suspended;
+
+    // Whether or not the GC has moved the ephemeral generation to no longer
+    // be at the top of the heap. When the ephemeral generation is at the top
+    // of the heap, and the write barrier observes that a pointer is greater than
+    // g_ephemeral_low, it does not need to check that the pointer is less than
+    // g_ephemeral_high because there is nothing in the GC heap above the ephemeral
+    // generation. When this is not the case, however, the GC must inform the EE
+    // so that the EE can switch to a write barrier that checks that a pointer
+    // is both greater than g_ephemeral_low and less than g_ephemeral_high.
+    // Used for WriteBarrierOp::StompResize.
+    bool requires_upper_bounds_check;
+
+    // The new card table location. May or may not be the same as the previous
+    // card table. Used for WriteBarrierOp::Initialize and WriteBarrierOp::StompResize.
+    uint32_t* card_table;
+
+    // The heap's new low boundary. May or may not be the same as the previous
+    // value. Used for WriteBarrierOp::Initialize and WriteBarrierOp::StompResize.
+    uint8_t* lowest_address;
+
+    // The heap's new high boundary. May or may not be the same as the previous
+    // value. Used for WriteBarrierOp::Initialize and WriteBarrierOp::StompResize.
+    uint8_t* highest_address;
+
+    // The new start of the ephemeral generation. 
+    // Used for WriteBarrierOp::StompEphemeral.
+    uint8_t* ephemeral_lo;
+
+    // The new end of the ephemeral generation.
+    // Used for WriteBarrierOp::StompEphemeral.
+    uint8_t* ephemeral_hi;
+};
+
 #include "gcinterface.ee.h"
 
 // The allocation context must be known to the VM for use in the allocation
@@ -110,19 +161,6 @@ IGCHeap* InitializeGarbageCollector(IGCToCLR* clrToGC);
 // and the heap is actually recated.
 void InitializeHeapType(bool bServerHeap);
 
-#ifndef DACCESS_COMPILE
-extern "C" {
-#endif // !DACCESS_COMPILE
-GPTR_DECL(uint8_t,g_lowest_address);
-GPTR_DECL(uint8_t,g_highest_address);
-GPTR_DECL(uint32_t,g_card_table);
-#ifndef DACCESS_COMPILE
-} 
-#endif // !DACCESS_COMPILE
-
-extern "C" uint8_t* g_ephemeral_low;
-extern "C" uint8_t* g_ephemeral_high;
-
 #ifdef WRITE_BARRIER_CHECK
 //always defined, but should be 0 in Server GC
 extern uint8_t* g_GCShadow;
index c088c34..3bed8c2 100644 (file)
@@ -4319,9 +4319,6 @@ dynamic_data* gc_heap::dynamic_data_of (int gen_number)
     return &dynamic_data_table [ gen_number ];
 }
 
-extern "C" uint8_t* g_ephemeral_low;
-extern "C" uint8_t* g_ephemeral_high;
-
 #define card_word_width ((size_t)32)
 
 //
index 7f0dd8c..664dc38 100644 (file)
@@ -91,14 +91,14 @@ inline void ErectWriteBarrier(Object ** dst, Object * ref)
 {
     // if the dst is outside of the heap (unboxed value classes) then we
     //      simply exit
-    if (((uint8_t*)dst < g_lowest_address) || ((uint8_t*)dst >= g_highest_address))
+    if (((uint8_t*)dst < g_gc_lowest_address) || ((uint8_t*)dst >= g_gc_highest_address))
         return;
         
-    if((uint8_t*)ref >= g_ephemeral_low && (uint8_t*)ref < g_ephemeral_high)
+    if((uint8_t*)ref >= g_gc_ephemeral_low && (uint8_t*)ref < g_gc_ephemeral_high)
     {
         // volatile is used here to prevent fetch of g_card_table from being reordered 
         // with g_lowest/highest_address check above. See comment in code:gc_heap::grow_brick_card_tables.
-        uint8_t* pCardByte = (uint8_t *)*(volatile uint8_t **)(&g_card_table) + card_byte((uint8_t *)dst);
+        uint8_t* pCardByte = (uint8_t *)*(volatile uint8_t **)(&g_gc_card_table) + card_byte((uint8_t *)dst);
         if(*pCardByte != 0xFF)
             *pCardByte = 0xFF;
     }
index 779d034..51a735c 100644 (file)
@@ -249,6 +249,10 @@ void GCToEEInterface::DiagWalkBGCSurvivors(void* gcContext)
 {
 }
 
+void GCToEEInterface::StompWriteBarrier(WriteBarrierParameters* args)
+{
+}
+
 void FinalizerThread::EnableFinalization()
 {
     // Signal to finalizer thread that there are objects to finalize
@@ -266,14 +270,6 @@ bool IsGCSpecialThread()
     return false;
 }
 
-void StompWriteBarrierEphemeral(bool /* isRuntimeSuspended */)
-{
-}
-
-void StompWriteBarrierResize(bool /* isRuntimeSuspended */, bool /*bReqUpperBoundsCheck*/)
-{
-}
-
 bool IsGCThread()
 {
     return false;
index 1c512c8..c89dd6c 100644 (file)
@@ -11,7 +11,9 @@
  * to the standard code-manager spec.
  */
 
+#ifndef FEATURE_PAL
 #include "utilcode.h"           // For _ASSERTE()
+#endif //!FEATURE_PAL
 #include "gcdump.h"
 
 /*****************************************************************************/
index 0c90397..23e6c68 100644 (file)
@@ -9,7 +9,9 @@
 #ifdef _TARGET_X86_
 /*****************************************************************************/
 
+#ifndef FEATURE_PAL
 #include "utilcode.h"           // For _ASSERTE()
+#endif //!FEATURE_PAL
 #include "gcdump.h"
 
 
index 71b31a5..50c6203 100644 (file)
@@ -1744,7 +1744,7 @@ YYSTATIC YYCONST short yyrecover[] = {
 #define        YYAPI_TOKENTYPE         int
 #define        YYAPI_TOKENEME(t)       (t)
 #define        YYAPI_TOKENNONE         -1
-#define        YYAPI_TOKENSTR(t)       (sprintf(yytokbuf, "%d", t), yytokbuf)
+#define        YYAPI_TOKENSTR(t)       (sprintf_s(yytokbuf, _countof(yytokbuf), "%d", t), yytokbuf)
 #define        YYAPI_VALUENAME         yylval
 #define        YYAPI_VALUETYPE         YYSTYPE
 #define        YYAPI_VALUEOF(v)        (v)
index ad5e5a7..371466f 100644 (file)
@@ -475,7 +475,7 @@ void dumpOneEHInfo(DasmExceptionInfoClause* ehInfo, IMDInternalImport *pImport,
     /*
     if(ehInfo->GetFlags() & ERR_OUT_OF_CODE)
     {
-        sprintf(szString,"%s// WARNING: Boundary outside the method code",g_szAsmCodeIndent);
+        _snprintf_s(szString, _countof(szString), _TRUNCATE, "%s// WARNING: Boundary outside the method code",g_szAsmCodeIndent);
         printLine(GUICookie,szString);
     }
     */
@@ -863,8 +863,8 @@ BOOL SourceLinesHelper(void *GUICookie, LineCodeDescr* pLCD, __out_ecount(nSize)
             /*
             BOOL fHasEmbeddedSource=FALSE;
             ((ISymUnmanagedDocument*)(pParam->pLCD->FileToken))->HasEmbeddedSource(&fHasEmbeddedSource);
-            sprintf(szString,"%s// PDB has %sembedded source",g_szAsmCodeIndent,
-                fHasEmbeddedSource ? "" : "no ");
+            _snprintf_s(szString, _countof(szString), _TRUNCATE, "%s// PDB has %sembedded source",g_szAsmCodeIndent,
+                        fHasEmbeddedSource ? "" : "no ");
             printLine(pParam->GUICookie,szString);
             */
         }
index 0f23fcc..53e1925 100644 (file)
@@ -281,11 +281,11 @@ DWORD   DumpResourceToFile(__in __nullterminated WCHAR*   wzFileName)
                 void* GUICookie = (void*)wzFileName;
                 BYTE* pbData;
                 printLine(GUICookie,"");
-                sprintf(szString,"// ========== Win32 Resource Entries (%d) ========",ulNumResNodes);
+                sprintf_s(szString, _countof(szString), "// ========== Win32 Resource Entries (%d) ========",ulNumResNodes);
                 for(i=0; i < ulNumResNodes; i++)
                 {
                     printLine(GUICookie,"");
-                    sprintf(szString,"// Res.# %d Type=0x%X Name=0x%X Lang=0x%X DataOffset=0x%X DataLength=%d",
+                    sprintf_s(szString, _countof(szString), "// Res.# %d Type=0x%X Name=0x%X Lang=0x%X DataOffset=0x%X DataLength=%d",
                         i+1,
                         g_prResNodePtr[i]->ResHdr.dwTypeID,
                         g_prResNodePtr[i]->ResHdr.dwNameID,
index f5f141d..83501e6 100644 (file)
@@ -2256,7 +2256,7 @@ void FindTextInListbox(HWND hwnd, FINDREPLACEW* lpfr)
         if(pos >= 0)
         {
             //char sz[32];
-            //sprintf(sz,"%d:%d",strFind.chrg.cpMin,strFind.chrg.cpMax);
+            //sprintf_s(sz, _countof(sz), "%d:%d",strFind.chrg.cpMin,strFind.chrg.cpMax);
             //MessageBox(hwnd,sz,"Find",MB_OK);
             SendMessage(hwndLB,EM_SETSEL,(WPARAM)pos,(LPARAM)(pos+wcslen(lpfr->lpstrFindWhat)));
         }
index 057521f..076fb0f 100644 (file)
@@ -737,7 +737,8 @@ void CodeGen::genCodeForTreeNode(GenTreePtr treeNode)
         {
 #ifdef DEBUG
             char message[256];
-            sprintf(message, "NYI: Unimplemented node type %s\n", GenTree::NodeName(treeNode->OperGet()));
+            _snprintf_s(message, _countof(message), _TRUNCATE, "NYI: Unimplemented node type %s\n",
+                        GenTree::NodeName(treeNode->OperGet()));
             notYetImplemented(message, __FILE__, __LINE__);
 #else
             NYI("unimplemented node");
index 5220ebc..65477fa 100644 (file)
@@ -2896,7 +2896,8 @@ void CodeGen::genCodeForTreeNode(GenTreePtr treeNode)
         {
 #ifdef DEBUG
             char message[256];
-            sprintf(message, "Unimplemented node type %s\n", GenTree::NodeName(treeNode->OperGet()));
+            _snprintf_s(message, _countof(message), _TRUNCATE, "Unimplemented node type %s\n",
+                        GenTree::NodeName(treeNode->OperGet()));
 #endif
             assert(!"Unknown node in codegen");
         }
index ab0bc3a..1adefc1 100644 (file)
@@ -2193,7 +2193,8 @@ void CodeGen::genCodeForTreeNode(GenTreePtr treeNode)
         {
 #ifdef DEBUG
             char message[256];
-            sprintf(message, "Unimplemented node type %s\n", GenTree::NodeName(treeNode->OperGet()));
+            _snprintf_s(message, _countof(message), _TRUNCATE, "Unimplemented node type %s\n",
+                        GenTree::NodeName(treeNode->OperGet()));
 #endif
             assert(!"Unknown node in codegen");
         }
index 0b991bd..a4b7375 100644 (file)
@@ -18562,20 +18562,20 @@ static escapeMapping_t s_EscapeMapping[] =
     {'"', "&quot;"},
     {0, nullptr}
 };
-// clang-formt on
+// clang-format on
 
-const char*   Compiler::fgProcessEscapes(const char* nameIn, escapeMapping_t* map)
+const char* Compiler::fgProcessEscapes(const char* nameIn, escapeMapping_t* map)
 {
-    const char*  nameOut = nameIn;
-    unsigned     lengthOut;
-    unsigned     index;
-    bool         match;
-    bool         subsitutionRequired;
-    const char*  pChar;
-
-    lengthOut = 1;
+    const char* nameOut = nameIn;
+    unsigned    lengthOut;
+    unsigned    index;
+    bool        match;
+    bool        subsitutionRequired;
+    const char* pChar;
+
+    lengthOut           = 1;
     subsitutionRequired = false;
-    pChar = nameIn;
+    pChar               = nameIn;
     while (*pChar != '\0')
     {
         match = false;
@@ -18603,8 +18603,8 @@ const char*   Compiler::fgProcessEscapes(const char* nameIn, escapeMapping_t* ma
 
     if (subsitutionRequired)
     {
-        char*   newName = (char*) compGetMemA(lengthOut, CMK_DebugOnly);
-        char*   pDest;
+        char* newName = (char*)compGetMemA(lengthOut, CMK_DebugOnly);
+        char* pDest;
         pDest = newName;
         pChar = nameIn;
         while (*pChar != '\0')
@@ -18632,7 +18632,7 @@ const char*   Compiler::fgProcessEscapes(const char* nameIn, escapeMapping_t* ma
             pChar++;
         }
         *pDest++ = '\0';
-        nameOut = (const char*) newName;
+        nameOut  = (const char*)newName;
     }
 
     return nameOut;
@@ -18668,44 +18668,47 @@ static void fprintfDouble(FILE* fgxFile, double value)
 //    Opens a file to which a flowgraph can be dumped, whose name is based on the current
 //    config vales.
 
-FILE*              Compiler::fgOpenFlowGraphFile(bool*  wbDontClose, Phases phase, LPCWSTR type)
+FILE* Compiler::fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type)
 {
-    FILE*          fgxFile;
-    LPCWSTR        pattern  = nullptr;
-    LPCWSTR        filename = nullptr;
-    LPCWSTR        pathname = nullptr;
-    const char*    escapedString;
-    bool           createDuplicateFgxFiles = true;
+    FILE*       fgxFile;
+    LPCWSTR     pattern  = nullptr;
+    LPCWSTR     filename = nullptr;
+    LPCWSTR     pathname = nullptr;
+    const char* escapedString;
+    bool        createDuplicateFgxFiles = true;
 
 #ifdef DEBUG
     if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PREJIT))
     {
-        pattern = JitConfig.NgenDumpFg();
+        pattern  = JitConfig.NgenDumpFg();
         filename = JitConfig.NgenDumpFgFile();
         pathname = JitConfig.NgenDumpFgDir();
     }
     else
     {
-        pattern = JitConfig.JitDumpFg();
+        pattern  = JitConfig.JitDumpFg();
         filename = JitConfig.JitDumpFgFile();
         pathname = JitConfig.JitDumpFgDir();
     }
 #endif // DEBUG
 
-    if (fgBBcount <= 1) {
+    if (fgBBcount <= 1)
+    {
         return nullptr;
-}
+    }
 
-    if (pattern == nullptr) {
+    if (pattern == nullptr)
+    {
         return nullptr;
-}
+    }
 
-    if (wcslen(pattern) == 0) {
+    if (wcslen(pattern) == 0)
+    {
         return nullptr;
-}
+    }
 
     LPCWSTR phasePattern = JitConfig.JitDumpFgPhase();
-    LPCWSTR phaseName = PhaseShortNames[phase];
+    LPCWSTR phaseName    = PhaseShortNames[phase];
     if (phasePattern == nullptr)
     {
         if (phase != PHASE_DETERMINE_FIRST_COLD_BLOCK)
@@ -18736,9 +18739,10 @@ FILE*              Compiler::fgOpenFlowGraphFile(bool*  wbDontClose, Phases phas
             {
                 while ((*pattern != W(':')) && (*pattern != W('*')))
                 {
-                    if (*pattern != *className) {
+                    if (*pattern != *className)
+                    {
                         return nullptr;
-}
+                    }
 
                     pattern++;
                     className++;
@@ -18749,12 +18753,14 @@ FILE*              Compiler::fgOpenFlowGraphFile(bool*  wbDontClose, Phases phas
                 }
                 else
                 {
-                    if (*className != 0) {
+                    if (*className != 0)
+                    {
                         return nullptr;
-}
-                }
+                    }
                 }
-            if (*pattern != W(':')) {
+            }
+            if (*pattern != W(':'))
+            {
                 return nullptr;
             }
 
@@ -18770,9 +18776,10 @@ FILE*              Compiler::fgOpenFlowGraphFile(bool*  wbDontClose, Phases phas
         {
             while ((*pattern != 0) && (*pattern != W('*')))
             {
-                if (*pattern != *methodName) {
+                if (*pattern != *methodName)
+                {
                     return nullptr;
-}
+                }
 
                 pattern++;
                 methodName++;
@@ -18783,12 +18790,14 @@ FILE*              Compiler::fgOpenFlowGraphFile(bool*  wbDontClose, Phases phas
             }
             else
             {
-                if (*methodName != 0) {
+                if (*methodName != 0)
+                {
                     return nullptr;
-}
-            }
+                }
             }
-        if (*pattern != 0) {
+        }
+        if (*pattern != 0)
+        {
             return nullptr;
         }
     }
@@ -18851,15 +18860,15 @@ FILE*              Compiler::fgOpenFlowGraphFile(bool*  wbDontClose, Phases phas
     {
         createDuplicateFgxFiles = true;
 
-ONE_FILE_PER_METHOD:;
+    ONE_FILE_PER_METHOD:;
 
-        escapedString = fgProcessEscapes(info.compFullName, s_EscapeFileMapping);
+        escapedString     = fgProcessEscapes(info.compFullName, s_EscapeFileMapping);
         size_t wCharCount = strlen(escapedString) + wcslen(phaseName) + 1 + strlen("~999") + wcslen(type) + 1;
         if (pathname != nullptr)
         {
             wCharCount += wcslen(pathname) + 1;
         }
-        filename = (LPCWSTR) alloca(wCharCount * sizeof(WCHAR));
+        filename = (LPCWSTR)alloca(wCharCount * sizeof(WCHAR));
         if (pathname != nullptr)
         {
             swprintf_s((LPWSTR)filename, wCharCount, W("%s\\%S-%s.%s"), pathname, escapedString, phaseName, type);
@@ -18868,7 +18877,7 @@ ONE_FILE_PER_METHOD:;
         {
             swprintf_s((LPWSTR)filename, wCharCount, W("%S.%s"), escapedString, type);
         }
-        fgxFile = _wfopen(filename, W("r"));   // Check if this file already exists
+        fgxFile = _wfopen(filename, W("r")); // Check if this file already exists
         if (fgxFile != nullptr)
         {
             // For Generic methods we will have both hot and cold versions
@@ -18889,10 +18898,11 @@ ONE_FILE_PER_METHOD:;
                 {
                     swprintf_s((LPWSTR)filename, wCharCount, W("%S~%d.%s"), escapedString, i, type);
                 }
-                fgxFile = _wfopen(filename, W("r"));   // Check if this file exists
-                if (fgxFile == nullptr) {
+                fgxFile = _wfopen(filename, W("r")); // Check if this file exists
+                if (fgxFile == nullptr)
+                {
                     break;
-            }
+                }
             }
             // If we have already created 1000 files with this name then just fail
             if (fgxFile != nullptr)
@@ -18901,28 +18911,28 @@ ONE_FILE_PER_METHOD:;
                 return nullptr;
             }
         }
-        fgxFile = _wfopen(filename, W("a+"));
+        fgxFile      = _wfopen(filename, W("a+"));
         *wbDontClose = false;
     }
     else if (wcscmp(filename, W("stdout")) == 0)
     {
-        fgxFile = jitstdout;
+        fgxFile      = jitstdout;
         *wbDontClose = true;
     }
     else if (wcscmp(filename, W("stderr")) == 0)
     {
-        fgxFile = stderr;
+        fgxFile      = stderr;
         *wbDontClose = true;
     }
     else
     {
         LPCWSTR origFilename = filename;
-        size_t wCharCount = wcslen(origFilename) + wcslen(type) + 2;
+        size_t  wCharCount   = wcslen(origFilename) + wcslen(type) + 2;
         if (pathname != nullptr)
         {
             wCharCount += wcslen(pathname) + 1;
         }
-        filename = (LPCWSTR) alloca(wCharCount * sizeof(WCHAR));
+        filename = (LPCWSTR)alloca(wCharCount * sizeof(WCHAR));
         if (pathname != nullptr)
         {
             swprintf_s((LPWSTR)filename, wCharCount, W("%s\\%s.%s"), pathname, origFilename, type);
@@ -18931,7 +18941,7 @@ ONE_FILE_PER_METHOD:;
         {
             swprintf_s((LPWSTR)filename, wCharCount, W("%s.%s"), origFilename, type);
         }
-        fgxFile = _wfopen(filename, W("a+"));
+        fgxFile      = _wfopen(filename, W("a+"));
         *wbDontClose = false;
     }
 
@@ -18972,39 +18982,39 @@ ONE_FILE_PER_METHOD:;
 //                              phases.
 //      COMPlus_JitDumpFgDot    Set to non-zero to emit Dot instead of Xml Flowgraph dump. (Default is xml format.)
 
-bool               Compiler::fgDumpFlowGraph(Phases phase)
+bool Compiler::fgDumpFlowGraph(Phases phase)
 {
-    bool    result    = false;
-    bool    dontClose = false;
-    bool    createDotFile = false;
+    bool result        = false;
+    bool dontClose     = false;
+    bool createDotFile = false;
     if (JitConfig.JitDumpFgDot())
     {
         createDotFile = true;
     }
 
-    FILE*   fgxFile   = fgOpenFlowGraphFile(&dontClose, phase, createDotFile ? W("dot") : W("fgx"));
+    FILE* fgxFile = fgOpenFlowGraphFile(&dontClose, phase, createDotFile ? W("dot") : W("fgx"));
 
     if (fgxFile == nullptr)
     {
         return false;
     }
-    bool           validWeights  = fgHaveValidEdgeWeights;
-    unsigned       calledCount   = max(fgCalledWeight, BB_UNITY_WEIGHT) / BB_UNITY_WEIGHT;
-    double         weightDivisor = (double) (calledCount * BB_UNITY_WEIGHT);
-    const char*    escapedString;
-    const char*    regionString  = "NONE";
+    bool        validWeights  = fgHaveValidEdgeWeights;
+    unsigned    calledCount   = max(fgCalledWeight, BB_UNITY_WEIGHT) / BB_UNITY_WEIGHT;
+    double      weightDivisor = (double)(calledCount * BB_UNITY_WEIGHT);
+    const char* escapedString;
+    const char* regionString = "NONE";
 
-    if      (info.compMethodInfo->regionKind == CORINFO_REGION_HOT)
+    if (info.compMethodInfo->regionKind == CORINFO_REGION_HOT)
     {
-        regionString="HOT";
+        regionString = "HOT";
     }
     else if (info.compMethodInfo->regionKind == CORINFO_REGION_COLD)
     {
-        regionString="COLD";
+        regionString = "COLD";
     }
     else if (info.compMethodInfo->regionKind == CORINFO_REGION_JIT)
     {
-        regionString="JIT";
+        regionString = "JIT";
     }
 
     if (createDotFile)
@@ -19014,7 +19024,7 @@ bool               Compiler::fgDumpFlowGraph(Phases phase)
     }
     else
     {
-        fprintf(fgxFile,   "<method");
+        fprintf(fgxFile, "<method");
 
         escapedString = fgProcessEscapes(info.compFullName, s_EscapeMapping);
         fprintf(fgxFile, "\n    name=\"%s\"", escapedString);
@@ -19055,77 +19065,74 @@ bool               Compiler::fgDumpFlowGraph(Phases phase)
             fprintf(fgxFile, "\n    firstColdBlock=\"%d\"", fgFirstColdBlock->bbNum);
         }
 
-        fprintf(fgxFile,        ">");
+        fprintf(fgxFile, ">");
 
         fprintf(fgxFile, "\n    <blocks");
         fprintf(fgxFile, "\n        blockCount=\"%d\"", fgBBcount);
-        fprintf(fgxFile,            ">");
+        fprintf(fgxFile, ">");
     }
 
-    static const char* kindImage[] = { "EHFINALLYRET", "EHFILTERRET", "EHCATCHRET",
-                                       "THROW", "RETURN", "NONE", "ALWAYS", "LEAVE",
-                                       "CALLFINALLY", "COND", "SWITCH" };
+    static const char* kindImage[] = {"EHFINALLYRET", "EHFILTERRET", "EHCATCHRET",  "THROW", "RETURN", "NONE",
+                                      "ALWAYS",       "LEAVE",       "CALLFINALLY", "COND",  "SWITCH"};
 
     BasicBlock* block;
     unsigned    blockOrdinal;
-    for (block = fgFirstBB    , blockOrdinal = 1;
-         block != nullptr;
-         block = block->bbNext, blockOrdinal++)
+    for (block = fgFirstBB, blockOrdinal = 1; block != nullptr; block = block->bbNext, blockOrdinal++)
     {
         if (createDotFile)
         {
             // Add constraint edges to try to keep nodes ordered.
             // It seems to work best if these edges are all created first.
-            switch(block->bbJumpKind)
+            switch (block->bbJumpKind)
             {
-            case BBJ_COND:
-            case BBJ_NONE:
-                assert(block->bbNext != nullptr);
-                fprintf(fgxFile, "    BB%02u -> BB%02u\n", block->bbNum, block->bbNext->bbNum);
-                break;
-            default:
-                // These may or may not have an edge to the next block.
-                // Add a transparent edge to keep nodes ordered.
-                if (block->bbNext != nullptr)
-                {
-                    fprintf(fgxFile, "    BB%02u -> BB%02u [arrowtail=none,color=transparent]\n", block->bbNum, block->bbNext->bbNum);
-                }
+                case BBJ_COND:
+                case BBJ_NONE:
+                    assert(block->bbNext != nullptr);
+                    fprintf(fgxFile, "    BB%02u -> BB%02u\n", block->bbNum, block->bbNext->bbNum);
+                    break;
+                default:
+                    // These may or may not have an edge to the next block.
+                    // Add a transparent edge to keep nodes ordered.
+                    if (block->bbNext != nullptr)
+                    {
+                        fprintf(fgxFile, "    BB%02u -> BB%02u [arrowtail=none,color=transparent]\n", block->bbNum,
+                                block->bbNext->bbNum);
+                    }
             }
         }
         else
         {
-            fprintf(fgxFile,"\n        <block");
-            fprintf(fgxFile,"\n            id=\"%d\"", block->bbNum);
-            fprintf(fgxFile,"\n            ordinal=\"%d\"", blockOrdinal);
-            fprintf(fgxFile,"\n            jumpKind=\"%s\"", kindImage[block->bbJumpKind]);
+            fprintf(fgxFile, "\n        <block");
+            fprintf(fgxFile, "\n            id=\"%d\"", block->bbNum);
+            fprintf(fgxFile, "\n            ordinal=\"%d\"", blockOrdinal);
+            fprintf(fgxFile, "\n            jumpKind=\"%s\"", kindImage[block->bbJumpKind]);
             if (block->hasTryIndex())
             {
-                fprintf(fgxFile,"\n            inTry=\"%s\"", "true");
+                fprintf(fgxFile, "\n            inTry=\"%s\"", "true");
             }
             if (block->hasHndIndex())
             {
-                fprintf(fgxFile,"\n            inHandler=\"%s\"", "true");
+                fprintf(fgxFile, "\n            inHandler=\"%s\"", "true");
             }
-            if (((fgFirstBB->bbFlags & BBF_PROF_WEIGHT) != 0) &&
-                ((block->bbFlags     & BBF_COLD)        == 0)    )
+            if (((fgFirstBB->bbFlags & BBF_PROF_WEIGHT) != 0) && ((block->bbFlags & BBF_COLD) == 0))
             {
-                fprintf(fgxFile,"\n            hot=\"true\"");
+                fprintf(fgxFile, "\n            hot=\"true\"");
             }
             if (block->bbFlags & (BBF_HAS_NEWOBJ | BBF_HAS_NEWARRAY))
             {
-                fprintf(fgxFile,"\n            callsNew=\"true\"");
+                fprintf(fgxFile, "\n            callsNew=\"true\"");
             }
             if (block->bbFlags & BBF_LOOP_HEAD)
             {
-                fprintf(fgxFile,"\n            loopHead=\"true\"");
+                fprintf(fgxFile, "\n            loopHead=\"true\"");
             }
-            fprintf(fgxFile,"\n            weight=");
-            fprintfDouble(fgxFile, ((double) block->bbWeight) / weightDivisor);
-            fprintf(fgxFile,"\n            codeEstimate=\"%d\"", fgGetCodeEstimate(block));
-            fprintf(fgxFile,"\n            startOffset=\"%d\"", block->bbCodeOffs);
-            fprintf(fgxFile,"\n            endOffset=\"%d\"", block->bbCodeOffsEnd);
-            fprintf(fgxFile,               ">");
-            fprintf(fgxFile,"\n        </block>");
+            fprintf(fgxFile, "\n            weight=");
+            fprintfDouble(fgxFile, ((double)block->bbWeight) / weightDivisor);
+            fprintf(fgxFile, "\n            codeEstimate=\"%d\"", fgGetCodeEstimate(block));
+            fprintf(fgxFile, "\n            startOffset=\"%d\"", block->bbCodeOffs);
+            fprintf(fgxFile, "\n            endOffset=\"%d\"", block->bbCodeOffsEnd);
+            fprintf(fgxFile, ">");
+            fprintf(fgxFile, "\n        </block>");
         }
     }
 
@@ -19135,10 +19142,10 @@ bool               Compiler::fgDumpFlowGraph(Phases phase)
 
         fprintf(fgxFile, "\n    <edges");
         fprintf(fgxFile, "\n        edgeCount=\"%d\"", fgEdgeCount);
-        fprintf(fgxFile,            ">");
+        fprintf(fgxFile, ">");
     }
 
-    unsigned edgeNum = 1;
+    unsigned    edgeNum = 1;
     BasicBlock* bTarget;
     for (bTarget = fgFirstBB; bTarget != nullptr; bTarget = bTarget->bbNext)
     {
@@ -19149,21 +19156,21 @@ bool               Compiler::fgDumpFlowGraph(Phases phase)
         }
         else
         {
-            targetWeightDivisor = (double) bTarget->bbWeight;
+            targetWeightDivisor = (double)bTarget->bbWeight;
         }
 
         flowList* edge;
         for (edge = bTarget->bbPreds; edge != nullptr; edge = edge->flNext, edgeNum++)
         {
-            BasicBlock*  bSource = edge->flBlock;
-            double       sourceWeightDivisor;
+            BasicBlock* bSource = edge->flBlock;
+            double      sourceWeightDivisor;
             if (bSource->bbWeight == BB_ZERO_WEIGHT)
             {
                 sourceWeightDivisor = 1.0;
             }
             else
             {
-                sourceWeightDivisor = (double) bSource->bbWeight;
+                sourceWeightDivisor = (double)bSource->bbWeight;
             }
             if (createDotFile)
             {
@@ -19185,54 +19192,54 @@ bool               Compiler::fgDumpFlowGraph(Phases phase)
             }
             else
             {
-                fprintf(fgxFile,"\n        <edge");
-                fprintf(fgxFile,"\n            id=\"%d\"", edgeNum);
-                fprintf(fgxFile,"\n            source=\"%d\"", bSource->bbNum);
-                fprintf(fgxFile,"\n            target=\"%d\"", bTarget->bbNum);
+                fprintf(fgxFile, "\n        <edge");
+                fprintf(fgxFile, "\n            id=\"%d\"", edgeNum);
+                fprintf(fgxFile, "\n            source=\"%d\"", bSource->bbNum);
+                fprintf(fgxFile, "\n            target=\"%d\"", bTarget->bbNum);
                 if (bSource->bbJumpKind == BBJ_SWITCH)
                 {
                     if (edge->flDupCount >= 2)
                     {
-                        fprintf(fgxFile,"\n            switchCases=\"%d\"", edge->flDupCount);
+                        fprintf(fgxFile, "\n            switchCases=\"%d\"", edge->flDupCount);
                     }
                     if (bSource->bbJumpSwt->getDefault() == bTarget)
                     {
-                        fprintf(fgxFile,"\n            switchDefault=\"true\"");
+                        fprintf(fgxFile, "\n            switchDefault=\"true\"");
                     }
                 }
                 if (validWeights)
                 {
                     unsigned edgeWeight = (edge->flEdgeWeightMin + edge->flEdgeWeightMax) / 2;
-                    fprintf(fgxFile,"\n            weight=");
-                    fprintfDouble(fgxFile, ((double) edgeWeight) / weightDivisor);
+                    fprintf(fgxFile, "\n            weight=");
+                    fprintfDouble(fgxFile, ((double)edgeWeight) / weightDivisor);
 
                     if (edge->flEdgeWeightMin != edge->flEdgeWeightMax)
                     {
-                        fprintf(fgxFile,"\n            minWeight=");
-                        fprintfDouble(fgxFile, ((double) edge->flEdgeWeightMin) / weightDivisor);
-                        fprintf(fgxFile,"\n            maxWeight=");
-                        fprintfDouble(fgxFile, ((double) edge->flEdgeWeightMax) / weightDivisor);
+                        fprintf(fgxFile, "\n            minWeight=");
+                        fprintfDouble(fgxFile, ((double)edge->flEdgeWeightMin) / weightDivisor);
+                        fprintf(fgxFile, "\n            maxWeight=");
+                        fprintfDouble(fgxFile, ((double)edge->flEdgeWeightMax) / weightDivisor);
                     }
 
                     if (edgeWeight > 0)
                     {
                         if (edgeWeight < bSource->bbWeight)
                         {
-                            fprintf(fgxFile,"\n            out=");
-                            fprintfDouble(fgxFile, ((double) edgeWeight) / sourceWeightDivisor );
+                            fprintf(fgxFile, "\n            out=");
+                            fprintfDouble(fgxFile, ((double)edgeWeight) / sourceWeightDivisor);
                         }
                         if (edgeWeight < bTarget->bbWeight)
                         {
-                            fprintf(fgxFile,"\n            in=");
-                            fprintfDouble(fgxFile, ((double) edgeWeight) / targetWeightDivisor);
+                            fprintf(fgxFile, "\n            in=");
+                            fprintfDouble(fgxFile, ((double)edgeWeight) / targetWeightDivisor);
                         }
                     }
                 }
             }
             if (!createDotFile)
             {
-                fprintf(fgxFile,               ">");
-                fprintf(fgxFile,"\n        </edge>");
+                fprintf(fgxFile, ">");
+                fprintf(fgxFile, "\n        </edge>");
             }
         }
     }
@@ -19264,7 +19271,7 @@ bool               Compiler::fgDumpFlowGraph(Phases phase)
 /*****************************************************************************/
 #ifdef DEBUG
 
-void                Compiler::fgDispReach()
+void Compiler::fgDispReach()
 {
     printf("------------------------------------------------\n");
     printf("BBnum  Reachable by \n");
@@ -19282,7 +19289,7 @@ void                Compiler::fgDispReach()
     }
 }
 
-void                Compiler::fgDispDoms()
+void Compiler::fgDispDoms()
 {
     // Don't bother printing this when we have a large number of BasicBlocks in the method
     if (fgBBcount > 256)
@@ -19309,23 +19316,18 @@ void                Compiler::fgDispDoms()
 
 /*****************************************************************************/
 
-void                Compiler::fgTableDispBasicBlock(BasicBlock* block,
-                                                    int ibcColWidth /* = 0 */)
+void Compiler::fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth /* = 0 */)
 {
-    unsigned        flags = block->bbFlags;
+    unsigned flags = block->bbFlags;
 
-    unsigned bbNumMax = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax;
-    int maxBlockNumWidth = CountDigits(bbNumMax);
-    maxBlockNumWidth = max(maxBlockNumWidth, 2);
-    int blockNumWidth = CountDigits(block->bbNum);
-    blockNumWidth = max(blockNumWidth, 2);
-    int blockNumPadding = maxBlockNumWidth - blockNumWidth;
+    unsigned bbNumMax         = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax;
+    int      maxBlockNumWidth = CountDigits(bbNumMax);
+    maxBlockNumWidth          = max(maxBlockNumWidth, 2);
+    int blockNumWidth         = CountDigits(block->bbNum);
+    blockNumWidth             = max(blockNumWidth, 2);
+    int blockNumPadding       = maxBlockNumWidth - blockNumWidth;
 
-    printf("BB%02u%*s [%08p] %2u",
-           block->bbNum,
-           blockNumPadding, "",
-           dspPtr(block),
-           block->bbRefs);
+    printf("BB%02u%*s [%08p] %2u", block->bbNum, blockNumPadding, "", dspPtr(block), block->bbRefs);
 
     //
     // Display EH 'try' region index
@@ -19419,86 +19421,89 @@ void                Compiler::fgTableDispBasicBlock(BasicBlock* block,
     // Display block branch target
     //
 
-    if  (flags & BBF_REMOVED)
+    if (flags & BBF_REMOVED)
     {
-        printf(  "[removed]       ");
+        printf("[removed]       ");
     }
     else
     {
         switch (block->bbJumpKind)
         {
-        case BBJ_COND:
-            printf("-> BB%02u%*s ( cond )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
-            break;
+            case BBJ_COND:
+                printf("-> BB%02u%*s ( cond )", block->bbJumpDest->bbNum,
+                       maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+                break;
 
-        case BBJ_CALLFINALLY:
-            printf("-> BB%02u%*s (callf )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
-            break;
+            case BBJ_CALLFINALLY:
+                printf("-> BB%02u%*s (callf )", block->bbJumpDest->bbNum,
+                       maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+                break;
 
-        case BBJ_ALWAYS:
-            if (flags & BBF_KEEP_BBJ_ALWAYS)
-            {
-                printf("-> BB%02u%*s (ALWAYS)", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
-            }
-            else
-            {
-                printf("-> BB%02u%*s (always)", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
-            }
-            break;
+            case BBJ_ALWAYS:
+                if (flags & BBF_KEEP_BBJ_ALWAYS)
+                {
+                    printf("-> BB%02u%*s (ALWAYS)", block->bbJumpDest->bbNum,
+                           maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+                }
+                else
+                {
+                    printf("-> BB%02u%*s (always)", block->bbJumpDest->bbNum,
+                           maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+                }
+                break;
 
-        case BBJ_LEAVE:
-            printf("-> BB%02u%*s (leave )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
-            break;
+            case BBJ_LEAVE:
+                printf("-> BB%02u%*s (leave )", block->bbJumpDest->bbNum,
+                       maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+                break;
 
-        case BBJ_EHFINALLYRET:
-            printf(  "%*s        (finret)", maxBlockNumWidth - 2, "");
-            break;
+            case BBJ_EHFINALLYRET:
+                printf("%*s        (finret)", maxBlockNumWidth - 2, "");
+                break;
 
-        case BBJ_EHFILTERRET:
-            printf(  "%*s        (fltret)", maxBlockNumWidth - 2, "");
-            break;
+            case BBJ_EHFILTERRET:
+                printf("%*s        (fltret)", maxBlockNumWidth - 2, "");
+                break;
 
-        case BBJ_EHCATCHRET:
-            printf("-> BB%02u%*s ( cret )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
-            break;
+            case BBJ_EHCATCHRET:
+                printf("-> BB%02u%*s ( cret )", block->bbJumpDest->bbNum,
+                       maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+                break;
 
-        case BBJ_THROW:
-            printf(  "%*s        (throw )", maxBlockNumWidth - 2, "");
-            break;
+            case BBJ_THROW:
+                printf("%*s        (throw )", maxBlockNumWidth - 2, "");
+                break;
 
-        case BBJ_RETURN:
-            printf(  "%*s        (return)", maxBlockNumWidth - 2, "");
-            break;
+            case BBJ_RETURN:
+                printf("%*s        (return)", maxBlockNumWidth - 2, "");
+                break;
 
-        default:
-            printf(  "%*s                ", maxBlockNumWidth - 2, "");
-            break;
+            default:
+                printf("%*s                ", maxBlockNumWidth - 2, "");
+                break;
 
-        case BBJ_SWITCH:
-            printf("->");
-
-            unsigned        jumpCnt;
-                            jumpCnt = block->bbJumpSwt->bbsCount;
-            BasicBlock**    jumpTab;
-                            jumpTab = block->bbJumpSwt->bbsDstTab;
-            int             switchWidth;
-                            switchWidth = 0;
-            do
-            {
-                printf("%cBB%02u",
-                       (jumpTab == block->bbJumpSwt->bbsDstTab) ? ' ' : ',',
-                       (*jumpTab)->bbNum);
-                switchWidth += 1 /* space/comma */ + 2 /* BB */ + max(CountDigits((*jumpTab)->bbNum), 2);
-            }
-            while (++jumpTab, --jumpCnt);
+            case BBJ_SWITCH:
+                printf("->");
 
-            if (switchWidth < 7)
-            {
-                printf("%*s", 8 - switchWidth, "");
-            }
+                unsigned jumpCnt;
+                jumpCnt = block->bbJumpSwt->bbsCount;
+                BasicBlock** jumpTab;
+                jumpTab = block->bbJumpSwt->bbsDstTab;
+                int switchWidth;
+                switchWidth = 0;
+                do
+                {
+                    printf("%cBB%02u", (jumpTab == block->bbJumpSwt->bbsDstTab) ? ' ' : ',', (*jumpTab)->bbNum);
+                    switchWidth += 1 /* space/comma */ + 2 /* BB */ + max(CountDigits((*jumpTab)->bbNum), 2);
+                } while (++jumpTab, --jumpCnt);
 
-            printf(" (switch)");
-            break;
+                if (switchWidth < 7)
+                {
+                    printf("%*s", 8 - switchWidth, "");
+                }
+
+                printf(" (switch)");
+                break;
         }
     }
 
@@ -19539,12 +19544,28 @@ void                Compiler::fgTableDispBasicBlock(BasicBlock* block,
 
     switch (block->bbCatchTyp)
     {
-    case BBCT_NONE:            break;
-    case BBCT_FAULT:           printf("fault ");   cnt += 6; break;
-    case BBCT_FINALLY:         printf("finally "); cnt += 8; break;
-    case BBCT_FILTER:          printf("filter ");  cnt += 7; break;
-    case BBCT_FILTER_HANDLER:  printf("filtHnd "); cnt += 8; break;
-    default:                   printf("catch ");   cnt += 6; break;
+        case BBCT_NONE:
+            break;
+        case BBCT_FAULT:
+            printf("fault ");
+            cnt += 6;
+            break;
+        case BBCT_FINALLY:
+            printf("finally ");
+            cnt += 8;
+            break;
+        case BBCT_FILTER:
+            printf("filter ");
+            cnt += 7;
+            break;
+        case BBCT_FILTER_HANDLER:
+            printf("filtHnd ");
+            cnt += 8;
+            break;
+        default:
+            printf("catch ");
+            cnt += 6;
+            break;
     }
 
     if (block->bbCatchTyp != BBCT_NONE)
@@ -19561,9 +19582,7 @@ void                Compiler::fgTableDispBasicBlock(BasicBlock* block,
         EHblkDsc* HBtab;
         EHblkDsc* HBtabEnd;
 
-        for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount;
-             HBtab < HBtabEnd;
-             HBtab++)
+        for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++)
         {
             if (HBtab->ebdTryBeg == block)
             {
@@ -19577,9 +19596,7 @@ void                Compiler::fgTableDispBasicBlock(BasicBlock* block,
     EHblkDsc* HBtab;
     EHblkDsc* HBtabEnd;
 
-    for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount;
-         HBtab < HBtabEnd;
-         HBtab++)
+    for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++)
     {
         if (HBtab->ebdTryLast == block)
         {
@@ -19620,9 +19637,7 @@ void                Compiler::fgTableDispBasicBlock(BasicBlock* block,
     Dump blocks from firstBlock to lastBlock.
 */
 
-void                Compiler::fgDispBasicBlocks(BasicBlock*  firstBlock,
-                                                BasicBlock*  lastBlock,
-                                                bool         dumpTrees)
+void Compiler::fgDispBasicBlocks(BasicBlock* firstBlock, BasicBlock* lastBlock, bool dumpTrees)
 {
     BasicBlock* block;
 
@@ -19640,24 +19655,27 @@ void                Compiler::fgDispBasicBlocks(BasicBlock*  firstBlock,
         if (block->bbFlags & BBF_PROF_WEIGHT)
         {
             int thisIbcWidth = CountDigits(block->bbWeight);
-            ibcColWidth = max(ibcColWidth, thisIbcWidth);
+            ibcColWidth      = max(ibcColWidth, thisIbcWidth);
         }
 
-        if (block == lastBlock) {
+        if (block == lastBlock)
+        {
             break;
-    }
+        }
     }
     if (ibcColWidth > 0)
     {
         ibcColWidth = max(ibcColWidth, 3) + 1; // + 1 for the leading space
     }
 
-    unsigned bbNumMax = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax;
-    int maxBlockNumWidth = CountDigits(bbNumMax);
-    maxBlockNumWidth = max(maxBlockNumWidth, 2);
+    unsigned bbNumMax         = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax;
+    int      maxBlockNumWidth = CountDigits(bbNumMax);
+    maxBlockNumWidth          = max(maxBlockNumWidth, 2);
 
     padWidth += maxBlockNumWidth - 2; // Account for functions with a large number of blocks.
 
+    // clang-format off
+
     printf("\n");
     printf("------%*s------------------------------------%*s-----------------------%*s----------------------------------------\n",
         padWidth, "------------",
@@ -19678,9 +19696,9 @@ void                Compiler::fgDispBasicBlocks(BasicBlock*  firstBlock,
         ibcColWidth, "------------",
         maxBlockNumWidth, "----");
 
-    for (block = firstBlock;
-         block;
-         block = block->bbNext)
+    // clang-format on
+
+    for (block = firstBlock; block; block = block->bbNext)
     {
         // First, do some checking on the bbPrev links
         if (block->bbPrev)
@@ -19697,33 +19715,31 @@ void                Compiler::fgDispBasicBlocks(BasicBlock*  firstBlock,
 
         if (block == fgFirstColdBlock)
         {
-            printf("~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n",
-                padWidth, "~~~~~~~~~~~~",
-                ibcColWidth, "~~~~~~~~~~~~",
-                maxBlockNumWidth, "~~~~");
+            printf("~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~"
+                   "~~~~~~~~~~~~~~~\n",
+                   padWidth, "~~~~~~~~~~~~", ibcColWidth, "~~~~~~~~~~~~", maxBlockNumWidth, "~~~~");
         }
 
 #if FEATURE_EH_FUNCLETS
         if (block == fgFirstFuncletBB)
         {
-            printf("++++++%*s++++++++++++++++++++++++++++++++++++%*s+++++++++++++++++++++++%*s++++++++++++++++++++++++++++++++++++++++ funclets follow\n",
-                padWidth, "++++++++++++",
-                ibcColWidth, "++++++++++++",
-                maxBlockNumWidth, "++++");
+            printf("++++++%*s++++++++++++++++++++++++++++++++++++%*s+++++++++++++++++++++++%*s+++++++++++++++++++++++++"
+                   "+++++++++++++++ funclets follow\n",
+                   padWidth, "++++++++++++", ibcColWidth, "++++++++++++", maxBlockNumWidth, "++++");
         }
 #endif // FEATURE_EH_FUNCLETS
 
         fgTableDispBasicBlock(block, ibcColWidth);
 
-        if (block == lastBlock) {
+        if (block == lastBlock)
+        {
             break;
-    }
+        }
     }
 
-    printf("------%*s------------------------------------%*s-----------------------%*s----------------------------------------\n",
-        padWidth, "------------",
-        ibcColWidth, "------------",
-        maxBlockNumWidth, "----");
+    printf("------%*s------------------------------------%*s-----------------------%*s---------------------------------"
+           "-------\n",
+           padWidth, "------------", ibcColWidth, "------------", maxBlockNumWidth, "----");
 
     if (dumpTrees)
     {
@@ -19733,7 +19749,7 @@ void                Compiler::fgDispBasicBlocks(BasicBlock*  firstBlock,
 
 /*****************************************************************************/
 
-void                Compiler::fgDispBasicBlocks(bool dumpTrees)
+void Compiler::fgDispBasicBlocks(bool dumpTrees)
 {
     fgDispBasicBlocks(fgFirstBB, nullptr, dumpTrees);
 }
@@ -19741,9 +19757,9 @@ void                Compiler::fgDispBasicBlocks(bool dumpTrees)
 /*****************************************************************************/
 //  Increment the stmtNum and dump the tree using gtDispTree
 //
-void                Compiler::fgDumpStmtTree(GenTreePtr stmt, unsigned blkNum)
+void Compiler::fgDumpStmtTree(GenTreePtr stmt, unsigned blkNum)
 {
-    compCurStmtNum++;  // Increment the current stmtNum
+    compCurStmtNum++; // Increment the current stmtNum
 
     printf("\n***** BB%02u, stmt %d\n", blkNum, compCurStmtNum);
 
@@ -19763,7 +19779,7 @@ void                Compiler::fgDumpStmtTree(GenTreePtr stmt, unsigned blkNum)
 // Arguments:
 //    block - The block to dump.
 //
-void                Compiler::fgDumpBlock(BasicBlock* block)
+void Compiler::fgDumpBlock(BasicBlock* block)
 {
     printf("\n------------ ");
     block->dspBlockHeader(this);
@@ -19775,7 +19791,7 @@ void                Compiler::fgDumpBlock(BasicBlock* block)
             fgDumpStmtTree(stmt, block->bbNum);
             if (stmt == block->bbTreeList)
             {
-                block->bbStmtNum = compCurStmtNum;  // Set the block->bbStmtNum
+                block->bbStmtNum = compCurStmtNum; // Set the block->bbStmtNum
             }
         }
     }
@@ -19788,10 +19804,9 @@ void                Compiler::fgDumpBlock(BasicBlock* block)
 /*****************************************************************************/
 //  Walk the BasicBlock list calling fgDumpTree once per Stmt
 //
-void                Compiler::fgDumpTrees(BasicBlock*  firstBlock,
-                                          BasicBlock*  lastBlock)
+void Compiler::fgDumpTrees(BasicBlock* firstBlock, BasicBlock* lastBlock)
 {
-    compCurStmtNum = 0;  // Reset the current stmtNum
+    compCurStmtNum = 0; // Reset the current stmtNum
 
     /* Walk the basic blocks */
 
@@ -19802,26 +19817,28 @@ void                Compiler::fgDumpTrees(BasicBlock*  firstBlock,
     {
         fgDumpBlock(block);
 
-        if (block == lastBlock) {
+        if (block == lastBlock)
+        {
             break;
+        }
     }
-    }
-    printf("\n-------------------------------------------------------------------------------------------------------------------\n");
+    printf("\n---------------------------------------------------------------------------------------------------------"
+           "----------\n");
 }
 
-
 /*****************************************************************************
  * Try to create as many candidates for GTF_MUL_64RSLT as possible.
  * We convert 'intOp1*intOp2' into 'int(long(nop(intOp1))*long(intOp2))'.
  */
 
 /* static */
-Compiler::fgWalkResult      Compiler::fgStress64RsltMulCB(GenTreePtr* pTree, fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgStress64RsltMulCB(GenTreePtr* pTree, fgWalkData* data)
 {
-    GenTreePtr tree = *pTree;
+    GenTreePtr tree  = *pTree;
     Compiler*  pComp = data->compiler;
 
-    if (tree->gtOper != GT_MUL || tree->gtType != TYP_INT || (tree->gtOverflow())) {
+    if (tree->gtOper != GT_MUL || tree->gtType != TYP_INT || (tree->gtOverflow()))
+    {
         return WALK_CONTINUE;
     }
 
@@ -19838,8 +19855,8 @@ Compiler::fgWalkResult      Compiler::fgStress64RsltMulCB(GenTreePtr* pTree, fgW
     tree->gtOp.gtOp1 = pComp->gtNewOperNode(GT_NOP, TYP_LONG, tree->gtOp.gtOp1);
     tree->gtOp.gtOp1 = pComp->gtNewCastNode(TYP_LONG, tree->gtOp.gtOp1, TYP_LONG);
     tree->gtOp.gtOp2 = pComp->gtNewCastNode(TYP_LONG, tree->gtOp.gtOp2, TYP_LONG);
-    tree->gtType = TYP_LONG;
-    *pTree = pComp->gtNewCastNode(TYP_INT, tree, TYP_INT);
+    tree->gtType     = TYP_LONG;
+    *pTree           = pComp->gtNewCastNode(TYP_INT, tree, TYP_INT);
 
 #ifdef DEBUG
     if (pComp->verbose)
@@ -19852,16 +19869,16 @@ Compiler::fgWalkResult      Compiler::fgStress64RsltMulCB(GenTreePtr* pTree, fgW
     return WALK_SKIP_SUBTREES;
 }
 
-void                Compiler::fgStress64RsltMul()
+void Compiler::fgStress64RsltMul()
 {
-    if (!compStressCompile(STRESS_64RSLT_MUL, 20)) {
+    if (!compStressCompile(STRESS_64RSLT_MUL, 20))
+    {
         return;
     }
 
     fgWalkAllTreesPre(fgStress64RsltMulCB, (void*)this);
 }
 
-
 // This variable is used to generate "traversal labels": one-time constants with which
 // we label basic blocks that are members of the basic block list, in order to have a
 // fast, high-probability test for membership in that list.  Type is "volatile" because
@@ -19877,8 +19894,7 @@ static volatile int bbTraverseLabel = 1;
  *
  *****************************************************************************/
 
-void                Compiler::fgDebugCheckBBlist(bool checkBBNum  /* = false */,
-                                                 bool checkBBRefs /* = true  */)
+void Compiler::fgDebugCheckBBlist(bool checkBBNum /* = false */, bool checkBBRefs /* = true  */)
 {
 #ifdef DEBUG
     if (verbose)
@@ -19905,7 +19921,7 @@ void                Compiler::fgDebugCheckBBlist(bool checkBBNum  /* = false */,
     unsigned    blockRefs;
 
 #if FEATURE_EH_FUNCLETS
-    bool            reachedFirstFunclet = false;
+    bool reachedFirstFunclet = false;
     if (fgFuncletsCreated)
     {
         //
@@ -19928,15 +19944,13 @@ void                Compiler::fgDebugCheckBBlist(bool checkBBNum  /* = false */,
         block->bbTraversalStamp = curTraversalStamp;
     }
 
-    for (prevBlock = nullptr, block = fgFirstBB;
-                              block;
-         prevBlock = block,   block = block->bbNext)
+    for (prevBlock = nullptr, block = fgFirstBB; block; prevBlock = block, block = block->bbNext)
     {
         blockRefs = 0;
 
         /* First basic block has countOfInEdges() >= 1 */
 
-        if  (block == fgFirstBB)
+        if (block == fgFirstBB)
         {
             noway_assert(block->countOfInEdges() >= 1);
             blockRefs = 1;
@@ -19960,17 +19974,14 @@ void                Compiler::fgDebugCheckBBlist(bool checkBBNum  /* = false */,
         {
 #ifndef LEGACY_BACKEND
             noway_assert(block->lastNode()->gtNext == nullptr &&
-                         (block->lastNode()->gtOper == GT_SWITCH ||
-                          block->lastNode()->gtOper == GT_SWITCH_TABLE));
-#else // LEGACY_BACKEND
-            noway_assert(block->lastStmt()->gtNext == NULL &&
-                         block->lastStmt()->gtStmtExpr->gtOper == GT_SWITCH);
+                         (block->lastNode()->gtOper == GT_SWITCH || block->lastNode()->gtOper == GT_SWITCH_TABLE));
+#else  // LEGACY_BACKEND
+            noway_assert(block->lastStmt()->gtNext == NULL && block->lastStmt()->gtStmtExpr->gtOper == GT_SWITCH);
 #endif // LEGACY_BACKEND
         }
-        else if (!(   block->bbJumpKind == BBJ_ALWAYS
-                   || block->bbJumpKind == BBJ_RETURN))
+        else if (!(block->bbJumpKind == BBJ_ALWAYS || block->bbJumpKind == BBJ_RETURN))
         {
-            //this block cannot have a poll
+            // this block cannot have a poll
             noway_assert(!(block->bbFlags & BBF_NEEDS_GCPOLL));
         }
 
@@ -20011,7 +20022,8 @@ void                Compiler::fgDebugCheckBBlist(bool checkBBNum  /* = false */,
 #endif // FEATURE_EH_FUNCLETS
 
         // Don't check cheap preds.
-        for (pred = (fgCheapPredsValid ? nullptr : block->bbPreds); pred != nullptr; blockRefs += pred->flDupCount, pred = pred->flNext)
+        for (pred = (fgCheapPredsValid ? nullptr : block->bbPreds); pred != nullptr;
+             blockRefs += pred->flDupCount, pred = pred->flNext)
         {
             assert(fgComputePredsDone); // If this isn't set, why do we have a preds list?
 
@@ -20024,95 +20036,101 @@ void                Compiler::fgDebugCheckBBlist(bool checkBBNum  /* = false */,
             if (ehTryDsc != nullptr)
             {
                 // You can jump to the start of a try
-                if (ehTryDsc->ebdTryBeg == block) {
+                if (ehTryDsc->ebdTryBeg == block)
+                {
                     goto CHECK_HND;
-}
+                }
 
                 // You can jump within the same try region
-                if (bbInTryRegions(block->getTryIndex(), blockPred)) {
+                if (bbInTryRegions(block->getTryIndex(), blockPred))
+                {
                     goto CHECK_HND;
-}
+                }
 
                 // The catch block can jump back into the middle of the try
-                if (bbInCatchHandlerRegions(block, blockPred)) {
+                if (bbInCatchHandlerRegions(block, blockPred))
+                {
                     goto CHECK_HND;
-}
+                }
 
                 // The end of a finally region is a BBJ_EHFINALLYRET block (during importing, BBJ_LEAVE) which
                 // is marked as "returning" to the BBJ_ALWAYS block following the BBJ_CALLFINALLY
                 // block that does a local call to the finally. This BBJ_ALWAYS is within
                 // the try region protected by the finally (for x86, ARM), but that's ok.
-                if (prevBlock->bbJumpKind == BBJ_CALLFINALLY &&
-                        block->bbJumpKind == BBJ_ALWAYS &&
-                    blockPred->bbJumpKind == BBJ_EHFINALLYRET) {
+                if (prevBlock->bbJumpKind == BBJ_CALLFINALLY && block->bbJumpKind == BBJ_ALWAYS &&
+                    blockPred->bbJumpKind == BBJ_EHFINALLYRET)
+                {
                     goto CHECK_HND;
-}
+                }
 
-                printf("Jump into the middle of try region: BB%02u branches to BB%02u\n", blockPred->bbNum, block->bbNum);
+                printf("Jump into the middle of try region: BB%02u branches to BB%02u\n", blockPred->bbNum,
+                       block->bbNum);
                 noway_assert(!"Jump into middle of try region");
             }
 
-CHECK_HND:;
+        CHECK_HND:;
 
             EHblkDsc* ehHndDsc = ehGetBlockHndDsc(block);
             if (ehHndDsc != nullptr)
             {
                 // You can do a BBJ_EHFINALLYRET or BBJ_EHFILTERRET into a handler region
-                if (   (blockPred->bbJumpKind == BBJ_EHFINALLYRET)
-                    || (blockPred->bbJumpKind == BBJ_EHFILTERRET)) {
+                if ((blockPred->bbJumpKind == BBJ_EHFINALLYRET) || (blockPred->bbJumpKind == BBJ_EHFILTERRET))
+                {
                     goto CHECK_JUMP;
-}
+                }
 
                 // Our try block can call our finally block
-                if ((block->bbCatchTyp == BBCT_FINALLY) &&
-                    (blockPred->bbJumpKind == BBJ_CALLFINALLY) &&
+                if ((block->bbCatchTyp == BBCT_FINALLY) && (blockPred->bbJumpKind == BBJ_CALLFINALLY) &&
                     ehCallFinallyInCorrectRegion(blockPred, block->getHndIndex()))
                 {
                     goto CHECK_JUMP;
                 }
 
                 // You can jump within the same handler region
-                if (bbInHandlerRegions(block->getHndIndex(), blockPred)) {
+                if (bbInHandlerRegions(block->getHndIndex(), blockPred))
+                {
                     goto CHECK_JUMP;
-}
+                }
 
                 // A filter can jump to the start of the filter handler
-                if (ehHndDsc->HasFilter()) {
+                if (ehHndDsc->HasFilter())
+                {
                     goto CHECK_JUMP;
-}
+                }
 
-                printf("Jump into the middle of handler region: BB%02u branches to BB%02u\n", blockPred->bbNum, block->bbNum);
+                printf("Jump into the middle of handler region: BB%02u branches to BB%02u\n", blockPred->bbNum,
+                       block->bbNum);
                 noway_assert(!"Jump into the middle of handler region");
             }
 
-CHECK_JUMP:;
+        CHECK_JUMP:;
 
             switch (blockPred->bbJumpKind)
             {
-            case BBJ_COND:
-                noway_assert(blockPred->bbNext == block || blockPred->bbJumpDest == block);
-                break;
+                case BBJ_COND:
+                    noway_assert(blockPred->bbNext == block || blockPred->bbJumpDest == block);
+                    break;
 
-            case BBJ_NONE:
-                noway_assert(blockPred->bbNext == block);
-                break;
+                case BBJ_NONE:
+                    noway_assert(blockPred->bbNext == block);
+                    break;
 
-            case BBJ_CALLFINALLY:
-            case BBJ_ALWAYS:
-            case BBJ_EHCATCHRET:
-            case BBJ_EHFILTERRET:
-                noway_assert(blockPred->bbJumpDest == block);
-                break;
+                case BBJ_CALLFINALLY:
+                case BBJ_ALWAYS:
+                case BBJ_EHCATCHRET:
+                case BBJ_EHFILTERRET:
+                    noway_assert(blockPred->bbJumpDest == block);
+                    break;
 
-            case BBJ_EHFINALLYRET:
+                case BBJ_EHFINALLYRET:
                 {
                     // If the current block is a successor to a BBJ_EHFINALLYRET (return from finally),
                     // then the lexically previous block should be a call to the same finally.
                     // Verify all of that.
 
-                    unsigned hndIndex = blockPred->getHndIndex();
-                    EHblkDsc* ehDsc = ehGetDsc(hndIndex);
-                    BasicBlock* finBeg = ehDsc->ebdHndBeg;
+                    unsigned    hndIndex = blockPred->getHndIndex();
+                    EHblkDsc*   ehDsc    = ehGetDsc(hndIndex);
+                    BasicBlock* finBeg   = ehDsc->ebdHndBeg;
 
                     // Because there is no bbPrev, we have to search for the lexically previous
                     // block.  We can shorten the search by only looking in places where it is legal
@@ -20124,13 +20142,15 @@ CHECK_JUMP:;
 
                     for (BasicBlock* bcall = begBlk; bcall != endBlk; bcall = bcall->bbNext)
                     {
-                        if  (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) {
+                        if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg)
+                        {
                             continue;
-}
+                        }
 
-                        if  (block == bcall->bbNext) {
+                        if (block == bcall->bbNext)
+                        {
                             goto PRED_OK;
-                    }
+                        }
                     }
 
 #if FEATURE_EH_FUNCLETS
@@ -20144,19 +20164,22 @@ CHECK_JUMP:;
 
                         for (BasicBlock* bcall = fgFirstFuncletBB; bcall; bcall = bcall->bbNext)
                         {
-                            if  (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) {
+                            if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg)
+                            {
                                 continue;
-}
+                            }
 
-                            if  (block != bcall->bbNext) {
+                            if (block != bcall->bbNext)
+                            {
                                 continue;
-}
+                            }
 
-                            if (ehCallFinallyInCorrectRegion(bcall, hndIndex)) {
+                            if (ehCallFinallyInCorrectRegion(bcall, hndIndex))
+                            {
                                 goto PRED_OK;
+                            }
                         }
                     }
-                    }
 
 #endif // FEATURE_EH_FUNCLETS
 
@@ -20164,34 +20187,34 @@ CHECK_JUMP:;
                 }
                 break;
 
-            case BBJ_THROW:
-            case BBJ_RETURN:
-                noway_assert(!"THROW and RETURN block cannot be in the predecessor list!");
-                break;
+                case BBJ_THROW:
+                case BBJ_RETURN:
+                    noway_assert(!"THROW and RETURN block cannot be in the predecessor list!");
+                    break;
 
-            case BBJ_SWITCH:
-                unsigned        jumpCnt; jumpCnt = blockPred->bbJumpSwt->bbsCount;
-                BasicBlock**    jumpTab; jumpTab = blockPred->bbJumpSwt->bbsDstTab;
+                case BBJ_SWITCH:
+                    unsigned jumpCnt;
+                    jumpCnt = blockPred->bbJumpSwt->bbsCount;
+                    BasicBlock** jumpTab;
+                    jumpTab = blockPred->bbJumpSwt->bbsDstTab;
 
-                do
-                {
-                    if  (block == *jumpTab)
+                    do
                     {
-                        goto PRED_OK;
-                    }
-                }
-                while (++jumpTab, --jumpCnt);
+                        if (block == *jumpTab)
+                        {
+                            goto PRED_OK;
+                        }
+                    } while (++jumpTab, --jumpCnt);
 
-                noway_assert(!"SWITCH in the predecessor list with no jump label to BLOCK!");
-                break;
+                    noway_assert(!"SWITCH in the predecessor list with no jump label to BLOCK!");
+                    break;
 
-            default:
-                noway_assert(!"Unexpected bbJumpKind");
-                break;
+                default:
+                    noway_assert(!"Unexpected bbJumpKind");
+                    break;
             }
 
-PRED_OK:;
-
+        PRED_OK:;
         }
 
         /* Check the bbRefs */
@@ -20230,7 +20253,7 @@ PRED_OK:;
     copiedForGenericsCtxt = ((info.compMethodInfo->options & CORINFO_GENERICS_CTXT_FROM_THIS) != 0);
 #else  // JIT32_GCENCODER
     copiedForGenericsCtxt = FALSE;
-#endif  // JIT32_GCENCODER
+#endif // JIT32_GCENCODER
 
     // This if only in support of the noway_asserts it contains.
     if (info.compIsStatic)
@@ -20243,16 +20266,18 @@ PRED_OK:;
         // For instance method:
         assert(info.compThisArg != BAD_VAR_NUM);
         bool compThisArgAddrExposedOK = !lvaTable[info.compThisArg].lvAddrExposed;
+
 #ifndef JIT32_GCENCODER
         compThisArgAddrExposedOK = compThisArgAddrExposedOK || copiedForGenericsCtxt;
-#endif  // !JIT32_GCENCODER
-        noway_assert(compThisArgAddrExposedOK &&                  //     should never expose the address of arg 0 or
-                     !lvaTable[info.compThisArg].lvArgWrite &&    //     write to arg 0.
-                     (                                                  //   In addition,
-                        lvaArg0Var == info.compThisArg ||               //     lvArg0Var should remain 0 if arg0 is not written to or address-exposed.
-                        lvaArg0Var != info.compThisArg &&
-                        (lvaTable[lvaArg0Var].lvAddrExposed || lvaTable[lvaArg0Var].lvArgWrite || copiedForGenericsCtxt)
-                     ));
+#endif // !JIT32_GCENCODER
+
+        // Should never expose the address of arg 0 or write to arg 0.
+        // In addition, lvArg0Var should remain 0 if arg0 is not
+        // written to or address-exposed.
+        noway_assert(compThisArgAddrExposedOK && !lvaTable[info.compThisArg].lvArgWrite &&
+                     (lvaArg0Var == info.compThisArg ||
+                      lvaArg0Var != info.compThisArg && (lvaTable[lvaArg0Var].lvAddrExposed ||
+                                                         lvaTable[lvaArg0Var].lvArgWrite || copiedForGenericsCtxt)));
     }
 }
 
@@ -20262,40 +20287,40 @@ PRED_OK:;
  *
  ****************************************************************************/
 
-void                Compiler::fgDebugCheckFlags(GenTreePtr tree)
+void Compiler::fgDebugCheckFlags(GenTreePtr tree)
 {
     noway_assert(tree->gtOper != GT_STMT);
 
-    genTreeOps      oper        = tree->OperGet();
-    unsigned        kind        = tree->OperKind();
-    unsigned        treeFlags   = tree->gtFlags & GTF_ALL_EFFECT;
-    unsigned        chkFlags    = 0;
+    genTreeOps oper      = tree->OperGet();
+    unsigned   kind      = tree->OperKind();
+    unsigned   treeFlags = tree->gtFlags & GTF_ALL_EFFECT;
+    unsigned   chkFlags  = 0;
 
     /* Is this a leaf node? */
 
-    if  (kind & GTK_LEAF)
+    if (kind & GTK_LEAF)
     {
         switch (oper)
         {
-        case GT_CLS_VAR:
-            chkFlags |= GTF_GLOB_REF;
-            break;
+            case GT_CLS_VAR:
+                chkFlags |= GTF_GLOB_REF;
+                break;
 
-        case GT_CATCH_ARG:
-            chkFlags |= GTF_ORDER_SIDEEFF;
-            break;
+            case GT_CATCH_ARG:
+                chkFlags |= GTF_ORDER_SIDEEFF;
+                break;
 
-        default:
-            break;
+            default:
+                break;
         }
     }
 
     /* Is it a 'simple' unary/binary operator? */
 
-    else if  (kind & GTK_SMPOP)
+    else if (kind & GTK_SMPOP)
     {
-        GenTreePtr      op1 = tree->gtOp.gtOp1;
-        GenTreePtr      op2 = tree->gtGetOp2();
+        GenTreePtr op1 = tree->gtOp.gtOp1;
+        GenTreePtr op2 = tree->gtGetOp2();
 
         // During GS work, we make shadow copies for params.
         // In gsParamsToShadows(), we create a shadow var of TYP_INT for every small type param.
@@ -20305,62 +20330,67 @@ void                Compiler::fgDebugCheckFlags(GenTreePtr tree)
         // TYP_INT up to the GT_ASG tree is only correct if we don't need to propagate the TYP_INT back up.
         // The following checks will ensure this.
 
-        // Is the left child of "tree" a GT_ASG?,
+        // Is the left child of "tree" a GT_ASG?
+        //
+        // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine.
+        // (or) If GT_ASG is the left child of a GT_COMMA, the type of the GT_COMMA node will
+        // be determined by its right child. So we don't need to propagate TYP_INT up either. We are fine.
         if (op1 && op1->gtOper == GT_ASG)
         {
-            assert(tree->gtType == TYP_VOID ||  // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine.
-                   tree->gtOper == GT_COMMA);   // (or) If GT_ASG is the left child of a GT_COMMA, the type of the GT_COMMA node will
-        }                                       // be determined by its right child. So we don't need to propagate TYP_INT up either. We are fine.
+            assert(tree->gtType == TYP_VOID || tree->gtOper == GT_COMMA);
+        }
 
-        // Is the right child of "tree" a GT_ASG?,
+        // Is the right child of "tree" a GT_ASG?
+        //
+        // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine.
         if (op2 && op2->gtOper == GT_ASG)
         {
-            assert(tree->gtType == TYP_VOID);   // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine.
+            assert(tree->gtType == TYP_VOID);
         }
 
         switch (oper)
         {
-        case GT_QMARK:
-            if (op1->OperIsCompare())
-            {
-                noway_assert(op1->gtFlags & GTF_DONT_CSE);
-            }
-            else
-            {
-                noway_assert( (op1->gtOper == GT_CNS_INT) &&
-                              ((op1->gtIntCon.gtIconVal == 0) || (op1->gtIntCon.gtIconVal == 1)) );
-            }
-            break;
-
-        case GT_LIST:
-        case GT_FIELD_LIST:
-            if ((op2 != nullptr) && op2->OperIsAnyList())
-            {
-                ArrayStack<GenTree *> stack(this);
-                while ((tree->gtGetOp2() != nullptr) && tree->gtGetOp2()->OperIsAnyList())
+            case GT_QMARK:
+                if (op1->OperIsCompare())
                 {
-                    stack.Push(tree);
-                    tree = tree->gtGetOp2();
+                    noway_assert(op1->gtFlags & GTF_DONT_CSE);
                 }
-
-                fgDebugCheckFlags(tree);
-
-                while (stack.Height() > 0)
+                else
                 {
-                    tree = stack.Pop();
-                    assert((tree->gtFlags & GTF_REVERSE_OPS) == 0);
-                    fgDebugCheckFlags(tree->gtOp.gtOp1);
-                    chkFlags |= (tree->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT);
-                    chkFlags |= (tree->gtGetOp2()->gtFlags & GTF_ALL_EFFECT);
-                    fgDebugCheckFlagsHelper(tree, (tree->gtFlags & GTF_ALL_EFFECT), chkFlags);
+                    noway_assert((op1->gtOper == GT_CNS_INT) &&
+                                 ((op1->gtIntCon.gtIconVal == 0) || (op1->gtIntCon.gtIconVal == 1)));
                 }
+                break;
 
-                return;
-            }
-            break;
+            case GT_LIST:
+            case GT_FIELD_LIST:
+                if ((op2 != nullptr) && op2->OperIsAnyList())
+                {
+                    ArrayStack<GenTree*> stack(this);
+                    while ((tree->gtGetOp2() != nullptr) && tree->gtGetOp2()->OperIsAnyList())
+                    {
+                        stack.Push(tree);
+                        tree = tree->gtGetOp2();
+                    }
 
-        default:
-            break;
+                    fgDebugCheckFlags(tree);
+
+                    while (stack.Height() > 0)
+                    {
+                        tree = stack.Pop();
+                        assert((tree->gtFlags & GTF_REVERSE_OPS) == 0);
+                        fgDebugCheckFlags(tree->gtOp.gtOp1);
+                        chkFlags |= (tree->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT);
+                        chkFlags |= (tree->gtGetOp2()->gtFlags & GTF_ALL_EFFECT);
+                        fgDebugCheckFlagsHelper(tree, (tree->gtFlags & GTF_ALL_EFFECT), chkFlags);
+                    }
+
+                    return;
+                }
+                break;
+
+            default:
+                break;
         }
 
         /* Recursively check the subtrees */
@@ -20376,11 +20406,11 @@ void                Compiler::fgDebugCheckFlags(GenTreePtr tree)
 
         if (op1)
         {
-            chkFlags   |= (op1->gtFlags & GTF_ALL_EFFECT);
+            chkFlags |= (op1->gtFlags & GTF_ALL_EFFECT);
         }
         if (op2)
         {
-            chkFlags   |= (op2->gtFlags & GTF_ALL_EFFECT);
+            chkFlags |= (op2->gtFlags & GTF_ALL_EFFECT);
         }
 
         // We reuse the value of GTF_REVERSE_OPS for a GT_IND-specific flag,
@@ -20396,7 +20426,7 @@ void                Compiler::fgDebugCheckFlags(GenTreePtr tree)
                was set and thus GTF_ASG cannot be considered here. */
 
             /* For a GT_ASG(GT_IND(x), y) we are interested in the side effects of x */
-            GenTreePtr  op1p;
+            GenTreePtr op1p;
             if ((kind & GTK_ASGOP) && (op1->gtOper == GT_IND))
             {
                 op1p = op1->gtOp.gtOp1;
@@ -20420,20 +20450,18 @@ void                Compiler::fgDebugCheckFlags(GenTreePtr tree)
 
         if (kind & GTK_ASGOP)
         {
-            chkFlags        |= GTF_ASG;
+            chkFlags |= GTF_ASG;
         }
 
         /* Note that it is OK for treeFlags not to have a GTF_EXCEPT,
            AssertionProp's non-Null may have cleared it */
         if (tree->OperMayThrow())
         {
-            chkFlags        |= (treeFlags & GTF_EXCEPT);
+            chkFlags |= (treeFlags & GTF_EXCEPT);
         }
 
-        if (oper == GT_ADDR &&
-            (op1->OperIsLocal() ||
-             op1->gtOper == GT_CLS_VAR ||
-             (op1->gtOper == GT_IND && op1->gtOp.gtOp1->gtOper == GT_CLS_VAR_ADDR)))
+        if (oper == GT_ADDR && (op1->OperIsLocal() || op1->gtOper == GT_CLS_VAR ||
+                                (op1->gtOper == GT_IND && op1->gtOp.gtOp1->gtOper == GT_CLS_VAR_ADDR)))
         {
             /* &aliasedVar doesn't need GTF_GLOB_REF, though alisasedVar does.
                Similarly for clsVar */
@@ -20445,128 +20473,127 @@ void                Compiler::fgDebugCheckFlags(GenTreePtr tree)
 
     else
     {
-        switch  (tree->OperGet())
+        switch (tree->OperGet())
         {
-        case GT_CALL:
+            case GT_CALL:
 
-            GenTreePtr      args;
-            GenTreePtr      argx;
-            GenTreeCall*    call;
+                GenTreePtr   args;
+                GenTreePtr   argx;
+                GenTreeCall* call;
 
-            call = tree->AsCall();
+                call = tree->AsCall();
 
-            chkFlags |= GTF_CALL;
+                chkFlags |= GTF_CALL;
 
-            if ((treeFlags & GTF_EXCEPT) && !(chkFlags & GTF_EXCEPT))
-            {
-                switch (eeGetHelperNum(tree->gtCall.gtCallMethHnd))
+                if ((treeFlags & GTF_EXCEPT) && !(chkFlags & GTF_EXCEPT))
                 {
-                    // Is this a helper call that can throw an exception ?
-                case CORINFO_HELP_LDIV:
-                case CORINFO_HELP_LMOD:
-                case CORINFO_HELP_METHOD_ACCESS_CHECK:
-                case CORINFO_HELP_FIELD_ACCESS_CHECK:
-                case CORINFO_HELP_CLASS_ACCESS_CHECK:
-                case CORINFO_HELP_DELEGATE_SECURITY_CHECK:
-                    chkFlags |= GTF_EXCEPT;
-                    break;
-                default:
-                    break;
+                    switch (eeGetHelperNum(tree->gtCall.gtCallMethHnd))
+                    {
+                        // Is this a helper call that can throw an exception ?
+                        case CORINFO_HELP_LDIV:
+                        case CORINFO_HELP_LMOD:
+                        case CORINFO_HELP_METHOD_ACCESS_CHECK:
+                        case CORINFO_HELP_FIELD_ACCESS_CHECK:
+                        case CORINFO_HELP_CLASS_ACCESS_CHECK:
+                        case CORINFO_HELP_DELEGATE_SECURITY_CHECK:
+                            chkFlags |= GTF_EXCEPT;
+                            break;
+                        default:
+                            break;
+                    }
                 }
-            }
 
-            if (call->gtCallObjp)
-            {
-                fgDebugCheckFlags(call->gtCallObjp);
-                chkFlags |= (call->gtCallObjp->gtFlags & GTF_SIDE_EFFECT);
-
-                if (call->gtCallObjp->gtFlags & GTF_ASG)
+                if (call->gtCallObjp)
                 {
-                    treeFlags |= GTF_ASG;
+                    fgDebugCheckFlags(call->gtCallObjp);
+                    chkFlags |= (call->gtCallObjp->gtFlags & GTF_SIDE_EFFECT);
+
+                    if (call->gtCallObjp->gtFlags & GTF_ASG)
+                    {
+                        treeFlags |= GTF_ASG;
+                    }
                 }
-            }
 
-            for (args = call->gtCallArgs; args; args = args->gtOp.gtOp2)
-            {
-                argx = args->gtOp.gtOp1;
-                fgDebugCheckFlags(argx);
+                for (args = call->gtCallArgs; args; args = args->gtOp.gtOp2)
+                {
+                    argx = args->gtOp.gtOp1;
+                    fgDebugCheckFlags(argx);
 
-                chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT);
+                    chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT);
 
-                if (argx->gtFlags & GTF_ASG)
-                {
-                    treeFlags |= GTF_ASG;
+                    if (argx->gtFlags & GTF_ASG)
+                    {
+                        treeFlags |= GTF_ASG;
+                    }
                 }
-            }
 
-            for (args = call->gtCallLateArgs; args; args = args->gtOp.gtOp2)
-            {
-                argx = args->gtOp.gtOp1;
-                fgDebugCheckFlags(argx);
+                for (args = call->gtCallLateArgs; args; args = args->gtOp.gtOp2)
+                {
+                    argx = args->gtOp.gtOp1;
+                    fgDebugCheckFlags(argx);
 
-                chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT);
+                    chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT);
 
-                if (argx->gtFlags & GTF_ASG)
-                {
-                    treeFlags |= GTF_ASG;
+                    if (argx->gtFlags & GTF_ASG)
+                    {
+                        treeFlags |= GTF_ASG;
+                    }
                 }
-            }
-
-            if ((call->gtCallType == CT_INDIRECT) && (call->gtCallCookie != nullptr))
-            {
-                fgDebugCheckFlags(call->gtCallCookie);
-                chkFlags |= (call->gtCallCookie->gtFlags & GTF_SIDE_EFFECT);
-            }
 
-            if (call->gtCallType == CT_INDIRECT)
-            {
-                fgDebugCheckFlags(call->gtCallAddr);
-                chkFlags |= (call->gtCallAddr->gtFlags & GTF_SIDE_EFFECT);
-            }
+                if ((call->gtCallType == CT_INDIRECT) && (call->gtCallCookie != nullptr))
+                {
+                    fgDebugCheckFlags(call->gtCallCookie);
+                    chkFlags |= (call->gtCallCookie->gtFlags & GTF_SIDE_EFFECT);
+                }
 
-            if (call->IsUnmanaged() &&
-                (call->gtCallMoreFlags & GTF_CALL_M_UNMGD_THISCALL))
-            {
-                if (call->gtCallArgs->gtOp.gtOp1->OperGet() == GT_NOP)
+                if (call->gtCallType == CT_INDIRECT)
                 {
-                    noway_assert(call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL ||
-                                 call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF);
+                    fgDebugCheckFlags(call->gtCallAddr);
+                    chkFlags |= (call->gtCallAddr->gtFlags & GTF_SIDE_EFFECT);
                 }
-                else
+
+                if (call->IsUnmanaged() && (call->gtCallMoreFlags & GTF_CALL_M_UNMGD_THISCALL))
                 {
-                    noway_assert(call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL ||
-                                 call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF);
+                    if (call->gtCallArgs->gtOp.gtOp1->OperGet() == GT_NOP)
+                    {
+                        noway_assert(call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL ||
+                                     call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF);
+                    }
+                    else
+                    {
+                        noway_assert(call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL ||
+                                     call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF);
+                    }
                 }
-            }
-            break;
+                break;
 
-        case GT_ARR_ELEM:
+            case GT_ARR_ELEM:
 
-            GenTreePtr      arrObj;
-            unsigned        dim;
+                GenTreePtr arrObj;
+                unsigned   dim;
 
-            arrObj = tree->gtArrElem.gtArrObj;
-            fgDebugCheckFlags(arrObj);
-            chkFlags   |= (arrObj->gtFlags & GTF_ALL_EFFECT);
+                arrObj = tree->gtArrElem.gtArrObj;
+                fgDebugCheckFlags(arrObj);
+                chkFlags |= (arrObj->gtFlags & GTF_ALL_EFFECT);
 
-            for (dim = 0; dim < tree->gtArrElem.gtArrRank; dim++)
-            {
-                fgDebugCheckFlags(tree->gtArrElem.gtArrInds[dim]);
-                chkFlags |= tree->gtArrElem.gtArrInds[dim]->gtFlags & GTF_ALL_EFFECT;
-            }
-            break;
+                for (dim = 0; dim < tree->gtArrElem.gtArrRank; dim++)
+                {
+                    fgDebugCheckFlags(tree->gtArrElem.gtArrInds[dim]);
+                    chkFlags |= tree->gtArrElem.gtArrInds[dim]->gtFlags & GTF_ALL_EFFECT;
+                }
+                break;
 
-        case GT_ARR_OFFSET:
-            fgDebugCheckFlags(tree->gtArrOffs.gtOffset);
-            chkFlags   |= (tree->gtArrOffs.gtOffset->gtFlags & GTF_ALL_EFFECT);
-            fgDebugCheckFlags(tree->gtArrOffs.gtIndex);
-            chkFlags   |= (tree->gtArrOffs.gtIndex->gtFlags & GTF_ALL_EFFECT);
-            fgDebugCheckFlags(tree->gtArrOffs.gtArrObj);
-            chkFlags   |= (tree->gtArrOffs.gtArrObj->gtFlags & GTF_ALL_EFFECT);
-            break;
+            case GT_ARR_OFFSET:
+                fgDebugCheckFlags(tree->gtArrOffs.gtOffset);
+                chkFlags |= (tree->gtArrOffs.gtOffset->gtFlags & GTF_ALL_EFFECT);
+                fgDebugCheckFlags(tree->gtArrOffs.gtIndex);
+                chkFlags |= (tree->gtArrOffs.gtIndex->gtFlags & GTF_ALL_EFFECT);
+                fgDebugCheckFlags(tree->gtArrOffs.gtArrObj);
+                chkFlags |= (tree->gtArrOffs.gtArrObj->gtFlags & GTF_ALL_EFFECT);
+                break;
 
-        default:
-            break;
+            default:
+                break;
         }
     }
 
@@ -20585,7 +20612,7 @@ void                Compiler::fgDebugCheckFlags(GenTreePtr tree)
 // Note:
 //    Checking that all bits that are set in treeFlags are also set in chkFlags is currently disabled.
 
-void  Compiler::fgDebugCheckFlagsHelper(GenTreePtr tree, unsigned treeFlags, unsigned chkFlags)
+void Compiler::fgDebugCheckFlagsHelper(GenTreePtr tree, unsigned treeFlags, unsigned chkFlags)
 {
     if (chkFlags & ~treeFlags)
     {
@@ -20631,7 +20658,7 @@ void  Compiler::fgDebugCheckFlagsHelper(GenTreePtr tree, unsigned treeFlags, uns
             gtDispTree(tree);
     }
 #endif // 0
-}
+    }
 }
 
 // DEBUG routine to check correctness of the internal gtNext, gtPrev threading of a statement.
@@ -20653,14 +20680,13 @@ void Compiler::fgDebugCheckNodeLinks(BasicBlock* block, GenTree* node)
     noway_assert(stmt->gtStmtList);
 
     // The first node's gtPrev must be nullptr (the gtPrev list is not circular).
-    // The last node's gtNext must be nullptr (the gtNext list is not circular). This is tested if the loop below terminates.
+    // The last node's gtNext must be nullptr (the gtNext list is not circular). This is tested if the loop below
+    // terminates.
     assert(stmt->gtStmtList->gtPrev == nullptr);
 
-    for (GenTreePtr tree = stmt->gtStmtList;
-         tree != nullptr;
-         tree = tree->gtNext)
+    for (GenTreePtr tree = stmt->gtStmtList; tree != nullptr; tree = tree->gtNext)
     {
-        if  (tree->gtPrev)
+        if (tree->gtPrev)
         {
             noway_assert(tree->gtPrev->gtNext == tree);
         }
@@ -20669,7 +20695,7 @@ void Compiler::fgDebugCheckNodeLinks(BasicBlock* block, GenTree* node)
             noway_assert(tree == stmt->gtStmtList);
         }
 
-        if  (tree->gtNext)
+        if (tree->gtNext)
         {
             noway_assert(tree->gtNext->gtPrev == tree);
         }
@@ -20705,40 +20731,40 @@ void Compiler::fgDebugCheckNodeLinks(BasicBlock* block, GenTree* node)
         {
             switch (tree->gtOper)
             {
-            case GT_QMARK:
-                expectedPrevTree = tree->gtOp.gtOp2->AsColon()->ThenNode(); // "then" operand of the GT_COLON (generated second).
-                break;
+                case GT_QMARK:
+                    expectedPrevTree =
+                        tree->gtOp.gtOp2->AsColon()->ThenNode(); // "then" operand of the GT_COLON (generated second).
+                    break;
 
-            case GT_COLON:
-                expectedPrevTree = tree->AsColon()->ElseNode(); // "else" branch result (generated first).
-                break;
+                case GT_COLON:
+                    expectedPrevTree = tree->AsColon()->ElseNode(); // "else" branch result (generated first).
+                    break;
 
-            default:
-                if (tree->gtOp.gtOp2)
-                {
-                    if (tree->gtFlags & GTF_REVERSE_OPS)
+                default:
+                    if (tree->gtOp.gtOp2)
                     {
-                        expectedPrevTree = tree->gtOp.gtOp1;
+                        if (tree->gtFlags & GTF_REVERSE_OPS)
+                        {
+                            expectedPrevTree = tree->gtOp.gtOp1;
+                        }
+                        else
+                        {
+                            expectedPrevTree = tree->gtOp.gtOp2;
+                        }
                     }
                     else
                     {
-                        expectedPrevTree = tree->gtOp.gtOp2;
+                        expectedPrevTree = tree->gtOp.gtOp1;
                     }
-                }
-                else
-                {
-                    expectedPrevTree = tree->gtOp.gtOp1;
-                }
-                break;
+                    break;
             }
         }
 
-        noway_assert(expectedPrevTree == nullptr ||                // No expectations about the prev node
-                     tree->gtPrev == expectedPrevTree);         // The "normal" case
+        noway_assert(expectedPrevTree == nullptr ||     // No expectations about the prev node
+                     tree->gtPrev == expectedPrevTree); // The "normal" case
     }
 }
 
-
 /*****************************************************************************
  *
  * A DEBUG routine to check the correctness of the links between GT_STMT nodes
@@ -20746,15 +20772,14 @@ void Compiler::fgDebugCheckNodeLinks(BasicBlock* block, GenTree* node)
  *
  ****************************************************************************/
 
-void                Compiler::fgDebugCheckLinks(bool morphTrees)
+void Compiler::fgDebugCheckLinks(bool morphTrees)
 {
     // This used to be only on for stress, and there was a comment stating that
     // it was "quite an expensive operation" but I did not find that to be true.
     // Set DO_SANITY_DEBUG_CHECKS to false to revert to that behavior.
     const bool DO_SANITY_DEBUG_CHECKS = true;
 
-    if (!DO_SANITY_DEBUG_CHECKS &&
-        !compStressCompile(STRESS_CHK_FLOW_UPDATE, 30))
+    if (!DO_SANITY_DEBUG_CHECKS && !compStressCompile(STRESS_CHK_FLOW_UPDATE, 30))
     {
         return;
     }
@@ -20764,7 +20789,7 @@ void                Compiler::fgDebugCheckLinks(bool morphTrees)
     /* For each basic block check the bbTreeList links */
     for (BasicBlock* block = fgFirstBB; block; block = block->bbNext)
     {
-PROCESS_BLOCK_AGAIN:;
+    PROCESS_BLOCK_AGAIN:;
         if (block->IsLIR())
         {
             LIR::AsRange(block).CheckLIR(this);
@@ -20774,11 +20799,12 @@ PROCESS_BLOCK_AGAIN:;
             for (GenTreeStmt* stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt)
             {
                 /* Verify that bbTreeList is threaded correctly */
-                /* Note that for the GT_STMT list, the gtPrev list is circular. The gtNext list is not: gtNext of the last GT_STMT in a block is nullptr. */
+                /* Note that for the GT_STMT list, the gtPrev list is circular. The gtNext list is not: gtNext of the
+                 * last GT_STMT in a block is nullptr. */
 
                 noway_assert(stmt->gtPrev);
 
-                if  (stmt == block->bbTreeList)
+                if (stmt == block->bbTreeList)
                 {
                     noway_assert(stmt->gtPrev->gtNext == nullptr);
                 }
@@ -20787,7 +20813,7 @@ PROCESS_BLOCK_AGAIN:;
                     noway_assert(stmt->gtPrev->gtNext == stmt);
                 }
 
-                if  (stmt->gtNext)
+                if (stmt->gtNext)
                 {
                     noway_assert(stmt->gtNext->gtPrev == stmt);
                 }
@@ -20866,9 +20892,9 @@ void Compiler::fgDebugCheckBlockLinks()
                 // Create a set with all the successors. Don't use BlockSet, so we don't need to worry
                 // about the BlockSet epoch.
                 BitVecTraits bitVecTraits(fgBBNumMax + 1, this);
-                BitVec BITVEC_INIT_NOCOPY(succBlocks, BitVecOps::MakeEmpty(&bitVecTraits));
+                BitVec       BITVEC_INIT_NOCOPY(succBlocks, BitVecOps::MakeEmpty(&bitVecTraits));
                 BasicBlock** jumpTable = block->bbJumpSwt->bbsDstTab;
-                unsigned jumpCount = block->bbJumpSwt->bbsCount;
+                unsigned     jumpCount = block->bbJumpSwt->bbsCount;
                 for (unsigned i = 0; i < jumpCount; i++)
                 {
                     BitVecOps::AddElemD(&bitVecTraits, succBlocks, jumpTable[i]->bbNum);
@@ -20906,7 +20932,7 @@ void Compiler::fgDebugCheckBlockLinks()
 //    Likewise the depth limit is a policy consideration, and serves mostly
 //    as a safeguard to prevent runaway inlining of small methods.
 
-unsigned     Compiler::fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo)
+unsigned Compiler::fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo)
 {
     BYTE*          candidateCode = inlineInfo->inlineCandidateInfo->methInfo.ILCode;
     InlineContext* inlineContext = inlineInfo->iciStmt->gtInlineContext;
@@ -20944,17 +20970,18 @@ unsigned     Compiler::fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo)
  *  Inlining phase
  */
 
-
-void                Compiler::fgInline()
+void Compiler::fgInline()
 {
-    if (!opts.OptEnabled(CLFLG_INLINING)) {
+    if (!opts.OptEnabled(CLFLG_INLINING))
+    {
         return;
-}
+    }
 
 #ifdef DEBUG
-    if  (verbose) {
+    if (verbose)
+    {
         printf("*************** In fgInline()\n");
-}
+    }
 #endif // DEBUG
 
     BasicBlock* block = fgFirstBB;
@@ -20965,9 +20992,7 @@ void                Compiler::fgInline()
 
     for (; block != nullptr; block = block->bbNext)
     {
-        for (GenTreeStmt* stmt = block->firstStmt();
-             stmt;
-             stmt = stmt->gtNextStmt)
+        for (GenTreeStmt* stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt)
         {
             stmt->gtInlineContext = rootContext;
         }
@@ -20985,9 +21010,7 @@ void                Compiler::fgInline()
         GenTreeStmt* stmt;
         GenTreePtr   expr;
 
-        for (stmt = block->firstStmt();
-             stmt != nullptr;
-             stmt = stmt->gtNextStmt)
+        for (stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt)
         {
             expr = stmt->gtStmtExpr;
 
@@ -21016,14 +21039,11 @@ void                Compiler::fgInline()
             }
 
             // See if we need to replace the return value place holder.
-            fgWalkTreePre(&stmt->gtStmtExpr,
-                          fgUpdateInlineReturnExpressionPlaceHolder,
-                          (void *) this);
+            fgWalkTreePre(&stmt->gtStmtExpr, fgUpdateInlineReturnExpressionPlaceHolder, (void*)this);
 
             // See if stmt is of the form GT_COMMA(call, nop)
             // If yes, we can get rid of GT_COMMA.
-            if (expr->OperGet() == GT_COMMA &&
-                expr->gtOp.gtOp1->OperGet() == GT_CALL &&
+            if (expr->OperGet() == GT_COMMA && expr->gtOp.gtOp1->OperGet() == GT_CALL &&
                 expr->gtOp.gtOp2->OperGet() == GT_NOP)
             {
                 stmt->gtStmtExpr = expr->gtOp.gtOp1;
@@ -21045,9 +21065,7 @@ void                Compiler::fgInline()
     {
         GenTreeStmt* stmt;
 
-        for (stmt = block->firstStmt();
-             stmt;
-             stmt = stmt->gtNextStmt)
+        for (stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt)
         {
             // Call Compiler::fgDebugCheckInlineCandidates on each node
             fgWalkTreePre(&stmt->gtStmtExpr, fgDebugCheckInlineCandidates);
@@ -21059,17 +21077,17 @@ void                Compiler::fgInline()
 
     fgVerifyHandlerTab();
 
-    if  (verbose)
+    if (verbose)
     {
         printf("*************** After fgInline()\n");
         fgDispBasicBlocks(true);
         fgDispHandlerTab();
     }
 
-    if  (verbose || fgPrintInlinedMethods)
+    if (verbose || fgPrintInlinedMethods)
     {
-       printf("**************** Inline Tree\n");
-       m_inlineStrategy->Dump();
+        printf("**************** Inline Tree\n");
+        m_inlineStrategy->Dump();
     }
 
 #endif // DEBUG
@@ -21091,14 +21109,13 @@ void                Compiler::fgInline()
 // Note:
 //    Invokes fgNoteNonInlineCandidate on the nodes it finds.
 
-Compiler::fgWalkResult      Compiler::fgFindNonInlineCandidate(GenTreePtr* pTree,
-                                                               fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgFindNonInlineCandidate(GenTreePtr* pTree, fgWalkData* data)
 {
     GenTreePtr tree = *pTree;
     if (tree->gtOper == GT_CALL)
     {
         Compiler*    compiler = data->compiler;
-        GenTreeStmt* stmt     = (GenTreeStmt*) data->pCallbackData;
+        GenTreeStmt* stmt     = (GenTreeStmt*)data->pCallbackData;
         GenTreeCall* call     = tree->AsCall();
 
         compiler->fgNoteNonInlineCandidate(stmt, call);
@@ -21118,10 +21135,9 @@ Compiler::fgWalkResult      Compiler::fgFindNonInlineCandidate(GenTreePtr* pTree
 //    Used in debug only to try and place descriptions of inline failures
 //    into the proper context in the inline tree.
 
-void Compiler::fgNoteNonInlineCandidate(GenTreeStmt* stmt,
-                                        GenTreeCall* call)
+void Compiler::fgNoteNonInlineCandidate(GenTreeStmt* stmt, GenTreeCall* call)
 {
-    InlineResult inlineResult(this, call, nullptr, "fgNotInlineCandidate");
+    InlineResult      inlineResult(this, call, nullptr, "fgNotInlineCandidate");
     InlineObservation currentObservation = InlineObservation::CALLSITE_NOT_CANDIDATE;
 
     // Try and recover the reason left behind when the jit decided
@@ -21172,12 +21188,8 @@ void Compiler::fgNoteNonInlineCandidate(GenTreeStmt* stmt,
  */
 GenTreePtr Compiler::fgGetStructAsStructPtr(GenTreePtr tree)
 {
-    noway_assert((tree->gtOper == GT_LCL_VAR) ||
-                 (tree->gtOper == GT_FIELD)   ||
-                 (tree->gtOper == GT_IND)     ||
-                 (tree->gtOper == GT_BLK)     ||
-                 (tree->gtOper == GT_OBJ)     ||
-                 tree->OperIsSIMD()           ||
+    noway_assert((tree->gtOper == GT_LCL_VAR) || (tree->gtOper == GT_FIELD) || (tree->gtOper == GT_IND) ||
+                 (tree->gtOper == GT_BLK) || (tree->gtOper == GT_OBJ) || tree->OperIsSIMD() ||
                  // tree->gtOper == GT_CALL     || cannot get address of call.
                  // tree->gtOper == GT_MKREFANY || inlining should've been aborted due to mkrefany opcode.
                  // tree->gtOper == GT_RET_EXPR || cannot happen after fgUpdateInlineReturnExpressionPlaceHolder
@@ -21185,18 +21197,18 @@ GenTreePtr Compiler::fgGetStructAsStructPtr(GenTreePtr tree)
 
     switch (tree->OperGet())
     {
-    case GT_BLK:
-    case GT_OBJ:
-    case GT_IND:
-        return tree->gtOp.gtOp1;
+        case GT_BLK:
+        case GT_OBJ:
+        case GT_IND:
+            return tree->gtOp.gtOp1;
 
-    case GT_COMMA:
-        tree->gtOp.gtOp2 = fgGetStructAsStructPtr(tree->gtOp.gtOp2);
-        tree->gtType = TYP_BYREF;
-        return tree;
+        case GT_COMMA:
+            tree->gtOp.gtOp2 = fgGetStructAsStructPtr(tree->gtOp.gtOp2);
+            tree->gtType     = TYP_BYREF;
+            return tree;
 
-    default:
-        return gtNewOperNode(GT_ADDR, TYP_BYREF, tree);
+        default:
+            return gtNewOperNode(GT_ADDR, TYP_BYREF, tree);
     }
 }
 
@@ -21221,12 +21233,12 @@ GenTreePtr Compiler::fgAssignStructInlineeToVar(GenTreePtr child, CORINFO_CLASS_
     // we have a ", , , call()" -- this is very defensive as we may never get
     // an inlinee that is made of commas. If the inlinee is not a call, then
     // we use a copy block to do the assignment.
-    GenTreePtr src = child;
+    GenTreePtr src       = child;
     GenTreePtr lastComma = nullptr;
     while (src->gtOper == GT_COMMA)
     {
         lastComma = src;
-        src = src->gtOp.gtOp2;
+        src       = src->gtOp.gtOp2;
     }
 
     GenTreePtr newInlinee = nullptr;
@@ -21246,16 +21258,16 @@ GenTreePtr Compiler::fgAssignStructInlineeToVar(GenTreePtr child, CORINFO_CLASS_
         if (child->gtOper == GT_COMMA)
         {
             lastComma->gtOp.gtOp2 = newInlinee;
-            newInlinee = child;
+            newInlinee            = child;
         }
     }
     else
     {
         // Inlinee is not a call, so just create a copy block to the tmp.
-        src = child;
+        src                = child;
         GenTreePtr dstAddr = fgGetStructAsStructPtr(dst);
         GenTreePtr srcAddr = fgGetStructAsStructPtr(src);
-        newInlinee = gtNewCpObjNode(dstAddr, srcAddr, retClsHnd, false);
+        newInlinee         = gtNewCpObjNode(dstAddr, srcAddr, retClsHnd, false);
     }
 
     GenTreePtr production = gtNewLclvNode(tmpNum, structType);
@@ -21288,9 +21300,10 @@ void Compiler::fgAttachStructInlineeToAsg(GenTreePtr tree, GenTreePtr child, COR
     }
 
     GenTreePtr dstAddr = fgGetStructAsStructPtr(tree->gtOp.gtOp1);
-    GenTreePtr srcAddr = fgGetStructAsStructPtr((child->gtOper == GT_CALL)
-                            ? fgAssignStructInlineeToVar(child, retClsHnd) // Assign to a variable if it is a call.
-                            : child);                                   // Just get the address, if not a call.
+    GenTreePtr srcAddr = fgGetStructAsStructPtr(
+        (child->gtOper == GT_CALL)
+            ? fgAssignStructInlineeToVar(child, retClsHnd) // Assign to a variable if it is a call.
+            : child);                                      // Just get the address, if not a call.
 
     tree->CopyFrom(gtNewCpObjNode(dstAddr, srcAddr, retClsHnd, false), this);
 }
@@ -21302,11 +21315,10 @@ void Compiler::fgAttachStructInlineeToAsg(GenTreePtr tree, GenTreePtr child, COR
  */
 
 /* static */
-Compiler::fgWalkResult      Compiler::fgUpdateInlineReturnExpressionPlaceHolder(GenTreePtr* pTree,
-                                                                                fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgUpdateInlineReturnExpressionPlaceHolder(GenTreePtr* pTree, fgWalkData* data)
 {
-    GenTreePtr tree = *pTree;
-    Compiler*  comp = data->compiler;
+    GenTreePtr           tree      = *pTree;
+    Compiler*            comp      = data->compiler;
     CORINFO_CLASS_HANDLE retClsHnd = NO_CLASS_HANDLE;
 
     if (tree->gtOper == GT_RET_EXPR)
@@ -21347,8 +21359,7 @@ Compiler::fgWalkResult      Compiler::fgUpdateInlineReturnExpressionPlaceHolder(
                 printf("\n");
             }
 #endif // DEBUG
-        }
-        while (tree->gtOper == GT_RET_EXPR);
+        } while (tree->gtOper == GT_RET_EXPR);
     }
 
 #if FEATURE_MULTIREG_RET
@@ -21390,15 +21401,12 @@ Compiler::fgWalkResult      Compiler::fgUpdateInlineReturnExpressionPlaceHolder(
     if ((tree->gtOper == GT_ASG) && (tree->gtOp.gtOp2->gtOper == GT_COMMA))
     {
         GenTreePtr comma;
-        for (comma = tree->gtOp.gtOp2;
-             comma->gtOper == GT_COMMA;
-             comma = comma->gtOp.gtOp2)
+        for (comma = tree->gtOp.gtOp2; comma->gtOper == GT_COMMA; comma = comma->gtOp.gtOp2)
         {
             // empty
         }
 
-        noway_assert(!varTypeIsStruct(comma) ||
-                     comma->gtOper != GT_RET_EXPR ||
+        noway_assert(!varTypeIsStruct(comma) || comma->gtOper != GT_RET_EXPR ||
                      !comp->IsMultiRegReturnedType(comma->gtRetExpr.gtRetClsHnd));
     }
 
@@ -21415,8 +21423,7 @@ Compiler::fgWalkResult      Compiler::fgUpdateInlineReturnExpressionPlaceHolder(
  */
 
 /* static */
-Compiler::fgWalkResult      Compiler::fgDebugCheckInlineCandidates(GenTreePtr* pTree,
-                                                                   fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgDebugCheckInlineCandidates(GenTreePtr* pTree, fgWalkData* data)
 {
     GenTreePtr tree = *pTree;
     if (tree->gtOper == GT_CALL)
@@ -21433,9 +21440,7 @@ Compiler::fgWalkResult      Compiler::fgDebugCheckInlineCandidates(GenTreePtr* p
 
 #endif // DEBUG
 
-
-void       Compiler::fgInvokeInlineeCompiler(GenTreeCall*  call,
-                                             InlineResult* inlineResult)
+void Compiler::fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* inlineResult)
 {
     noway_assert(call->gtOper == GT_CALL);
     noway_assert((call->gtFlags & GTF_CALL_INLINE_CANDIDATE) != 0);
@@ -21478,99 +21483,95 @@ void       Compiler::fgInvokeInlineeCompiler(GenTreeCall*  call,
     // Set the trap to catch all errors (including recoverable ones from the EE)
     struct Param
     {
-        Compiler* pThis;
-        GenTree* call;
+        Compiler*             pThis;
+        GenTree*              call;
         CORINFO_METHOD_HANDLE fncHandle;
-        InlineCandidateInfo* inlineCandidateInfo;
-        InlineInfo* inlineInfo;
+        InlineCandidateInfo*  inlineCandidateInfo;
+        InlineInfo*           inlineInfo;
     } param = {nullptr};
 
-    param.pThis = this;
-    param.call = call;
-    param.fncHandle = fncHandle;
+    param.pThis               = this;
+    param.call                = call;
+    param.fncHandle           = fncHandle;
     param.inlineCandidateInfo = inlineCandidateInfo;
-    param.inlineInfo = &inlineInfo;
-    bool success = eeRunWithErrorTrap<Param>([](Param* pParam)
-    {
-        // Init the local var info of the inlinee
-        pParam->pThis->impInlineInitVars(pParam->inlineInfo);
+    param.inlineInfo          = &inlineInfo;
+    bool success              = eeRunWithErrorTrap<Param>(
+        [](Param* pParam) {
+            // Init the local var info of the inlinee
+            pParam->pThis->impInlineInitVars(pParam->inlineInfo);
 
-        if (pParam->inlineInfo->inlineResult->IsCandidate())
-        {
-            /* Clear the temp table */
-            memset(pParam->inlineInfo->lclTmpNum, -1, sizeof(pParam->inlineInfo->lclTmpNum));
+            if (pParam->inlineInfo->inlineResult->IsCandidate())
+            {
+                /* Clear the temp table */
+                memset(pParam->inlineInfo->lclTmpNum, -1, sizeof(pParam->inlineInfo->lclTmpNum));
 
-            //
-            // Prepare the call to jitNativeCode
-            //
+                //
+                // Prepare the call to jitNativeCode
+                //
 
-            pParam->inlineInfo->InlinerCompiler = pParam->pThis;
-            if (pParam->pThis->impInlineInfo == nullptr)
-            {
-                pParam->inlineInfo->InlineRoot = pParam->pThis;
-            }
-            else
-            {
-                pParam->inlineInfo->InlineRoot = pParam->pThis->impInlineInfo->InlineRoot;
-            }
-            pParam->inlineInfo->argCnt                   = pParam->inlineCandidateInfo->methInfo.args.totalILArgs();
-            pParam->inlineInfo->tokenLookupContextHandle = pParam->inlineCandidateInfo->exactContextHnd;
+                pParam->inlineInfo->InlinerCompiler = pParam->pThis;
+                if (pParam->pThis->impInlineInfo == nullptr)
+                {
+                    pParam->inlineInfo->InlineRoot = pParam->pThis;
+                }
+                else
+                {
+                    pParam->inlineInfo->InlineRoot = pParam->pThis->impInlineInfo->InlineRoot;
+                }
+                pParam->inlineInfo->argCnt                   = pParam->inlineCandidateInfo->methInfo.args.totalILArgs();
+                pParam->inlineInfo->tokenLookupContextHandle = pParam->inlineCandidateInfo->exactContextHnd;
 
-            JITLOG_THIS(pParam->pThis,
-                        (LL_INFO100000,
-                         "INLINER: inlineInfo.tokenLookupContextHandle for %s set to 0x%p:\n",
-                         pParam->pThis->eeGetMethodFullName(pParam->fncHandle),
-                         pParam->pThis->dspPtr(pParam->inlineInfo->tokenLookupContextHandle)));
+                JITLOG_THIS(pParam->pThis,
+                            (LL_INFO100000, "INLINER: inlineInfo.tokenLookupContextHandle for %s set to 0x%p:\n",
+                             pParam->pThis->eeGetMethodFullName(pParam->fncHandle),
+                             pParam->pThis->dspPtr(pParam->inlineInfo->tokenLookupContextHandle)));
 
-            JitFlags compileFlagsForInlinee = *pParam->pThis->opts.jitFlags;
+                JitFlags compileFlagsForInlinee = *pParam->pThis->opts.jitFlags;
 
-            // The following flags are lost when inlining.
-            // (This is checked in Compiler::compInitOptions().)
-            compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBOPT);
-            compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBINSTR);
-            compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_PROF_ENTERLEAVE);
-            compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_EnC);
-            compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_INFO);
+                // The following flags are lost when inlining.
+                // (This is checked in Compiler::compInitOptions().)
+                compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBOPT);
+                compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBINSTR);
+                compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_PROF_ENTERLEAVE);
+                compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_EnC);
+                compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_INFO);
 
-            compileFlagsForInlinee.Set(JitFlags::JIT_FLAG_SKIP_VERIFICATION);
+                compileFlagsForInlinee.Set(JitFlags::JIT_FLAG_SKIP_VERIFICATION);
 
 #ifdef DEBUG
-            if (pParam->pThis->verbose)
-            {
-                printf("\nInvoking compiler for the inlinee method %s :\n",
-                       pParam->pThis->eeGetMethodFullName(pParam->fncHandle));
-            }
+                if (pParam->pThis->verbose)
+                {
+                    printf("\nInvoking compiler for the inlinee method %s :\n",
+                           pParam->pThis->eeGetMethodFullName(pParam->fncHandle));
+                }
 #endif // DEBUG
 
-            int result = jitNativeCode(pParam->fncHandle,
-                          pParam->inlineCandidateInfo->methInfo.scope,
-                          pParam->pThis->info.compCompHnd,
-                          &pParam->inlineCandidateInfo->methInfo,
-                          (void**)pParam->inlineInfo,
-                          nullptr,
-                          &compileFlagsForInlinee,
-                          pParam->inlineInfo);
+                int result =
+                    jitNativeCode(pParam->fncHandle, pParam->inlineCandidateInfo->methInfo.scope,
+                                  pParam->pThis->info.compCompHnd, &pParam->inlineCandidateInfo->methInfo,
+                                  (void**)pParam->inlineInfo, nullptr, &compileFlagsForInlinee, pParam->inlineInfo);
 
-            if (result != CORJIT_OK)
-            {
-                // If we haven't yet determined why this inline fails, use
-                // a catch-all something bad happened observation.
-                InlineResult* innerInlineResult = pParam->inlineInfo->inlineResult;
-
-                if (!innerInlineResult->IsFailure())
+                if (result != CORJIT_OK)
                 {
-                    innerInlineResult->NoteFatal(InlineObservation::CALLSITE_COMPILATION_FAILURE);
+                    // If we haven't yet determined why this inline fails, use
+                    // a catch-all something bad happened observation.
+                    InlineResult* innerInlineResult = pParam->inlineInfo->inlineResult;
+
+                    if (!innerInlineResult->IsFailure())
+                    {
+                        innerInlineResult->NoteFatal(InlineObservation::CALLSITE_COMPILATION_FAILURE);
+                    }
                 }
             }
-        }
-    }, &param);
+        },
+        &param);
     if (!success)
     {
 #ifdef DEBUG
         if (verbose)
         {
-             printf("\nInlining failed due to an exception during invoking the compiler for the inlinee method %s.\n",
-                    eeGetMethodFullName(fncHandle));
+            printf("\nInlining failed due to an exception during invoking the compiler for the inlinee method %s.\n",
+                   eeGetMethodFullName(fncHandle));
         }
 #endif // DEBUG
 
@@ -21590,8 +21591,7 @@ void       Compiler::fgInvokeInlineeCompiler(GenTreeCall*  call,
 #ifdef DEBUG
     if (0 && verbose)
     {
-         printf("\nDone invoking compiler for the inlinee method %s\n",
-                eeGetMethodFullName(fncHandle));
+        printf("\nDone invoking compiler for the inlinee method %s\n", eeGetMethodFullName(fncHandle));
     }
 #endif // DEBUG
 
@@ -21606,7 +21606,7 @@ void       Compiler::fgInvokeInlineeCompiler(GenTreeCall*  call,
         if (verbose)
         {
             printf("\nInlining failed because pInlineInfo->retExpr is not set in the inlinee method %s.\n",
-                    eeGetMethodFullName(fncHandle));
+                   eeGetMethodFullName(fncHandle));
         }
 #endif // DEBUG
         inlineResult->NoteFatal(InlineObservation::CALLEE_LACKS_RETURN);
@@ -21618,7 +21618,8 @@ void       Compiler::fgInvokeInlineeCompiler(GenTreeCall*  call,
         // we defer the call to initClass() until inlining is completed in case it fails. If inlining succeeds,
         // we will call initClass().
         if (!(info.compCompHnd->initClass(nullptr /* field */, fncHandle /* method */,
-                inlineCandidateInfo->exactContextHnd /* context */) & CORINFO_INITCLASS_INITIALIZED))
+                                          inlineCandidateInfo->exactContextHnd /* context */) &
+              CORINFO_INITCLASS_INITIALIZED))
         {
             inlineResult->NoteFatal(InlineObservation::CALLEE_CLASS_INIT_FAILURE);
             return;
@@ -21637,11 +21638,8 @@ void       Compiler::fgInvokeInlineeCompiler(GenTreeCall*  call,
 
     if (verbose || fgPrintInlinedMethods)
     {
-        printf("Successfully inlined %s (%d IL bytes) (depth %d) [%s]\n",
-               eeGetMethodFullName(fncHandle),
-               inlineCandidateInfo->methInfo.ILCodeSize,
-               inlineDepth,
-               inlineResult->ReasonString());
+        printf("Successfully inlined %s (%d IL bytes) (depth %d) [%s]\n", eeGetMethodFullName(fncHandle),
+               inlineCandidateInfo->methInfo.ILCodeSize, inlineDepth, inlineResult->ReasonString());
     }
 
     if (verbose)
@@ -21682,9 +21680,9 @@ void       Compiler::fgInvokeInlineeCompiler(GenTreeCall*  call,
 
 void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
 {
-    GenTreeCall* iciCall     = pInlineInfo->iciCall;
-    GenTreeStmt* iciStmt     = pInlineInfo->iciStmt;
-    BasicBlock*  iciBlock    = pInlineInfo->iciBlock;
+    GenTreeCall* iciCall  = pInlineInfo->iciCall;
+    GenTreeStmt* iciStmt  = pInlineInfo->iciStmt;
+    BasicBlock*  iciBlock = pInlineInfo->iciBlock;
     BasicBlock*  block;
 
     // We can write better assert here. For example, we can check that
@@ -21709,13 +21707,9 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
     // Create a new inline context and mark the inlined statements with it
     InlineContext* calleeContext = m_inlineStrategy->NewSuccess(pInlineInfo);
 
-    for (block = InlineeCompiler->fgFirstBB;
-         block != nullptr;
-         block = block->bbNext)
+    for (block = InlineeCompiler->fgFirstBB; block != nullptr; block = block->bbNext)
     {
-        for (GenTreeStmt* stmt = block->firstStmt();
-             stmt;
-             stmt = stmt->gtNextStmt)
+        for (GenTreeStmt* stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt)
         {
             stmt->gtInlineContext = calleeContext;
         }
@@ -21732,7 +21726,7 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
     }
 #endif // DEBUG
 
-    BasicBlock* topBlock = iciBlock;
+    BasicBlock* topBlock    = iciBlock;
     BasicBlock* bottomBlock = nullptr;
 
     if (InlineeCompiler->fgBBcount == 1)
@@ -21749,9 +21743,7 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
             // Inlinee contains just one BB. So just insert its statement list to topBlock.
             if (InlineeCompiler->fgFirstBB->bbTreeList)
             {
-                stmtAfter = fgInsertStmtListAfter(iciBlock,
-                                                  stmtAfter,
-                                                  InlineeCompiler->fgFirstBB->bbTreeList);
+                stmtAfter = fgInsertStmtListAfter(iciBlock, stmtAfter, InlineeCompiler->fgFirstBB->bbTreeList);
 
                 // Copy inlinee bbFlags to caller bbFlags.
                 const unsigned int inlineeBlockFlags = InlineeCompiler->fgFirstBB->bbFlags;
@@ -21765,7 +21757,7 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
             {
                 noway_assert(currentDumpStmt);
 
-                if  (currentDumpStmt != stmtAfter)
+                if (currentDumpStmt != stmtAfter)
                 {
                     do
                     {
@@ -21778,7 +21770,7 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
                         gtDispTree(currentDumpStmt);
                         printf("\n");
 
-                    }  while (currentDumpStmt != stmtAfter);
+                    } while (currentDumpStmt != stmtAfter);
                 }
             }
 #endif // DEBUG
@@ -21794,8 +21786,8 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
     // ======= Inserting inlinee's basic blocks ===============
     //
 
-    bottomBlock = fgNewBBafter(topBlock->bbJumpKind, topBlock, true);
-    bottomBlock->bbRefs = 1;
+    bottomBlock             = fgNewBBafter(topBlock->bbJumpKind, topBlock, true);
+    bottomBlock->bbRefs     = 1;
     bottomBlock->bbJumpDest = topBlock->bbJumpDest;
     bottomBlock->inheritWeight(topBlock);
 
@@ -21805,7 +21797,7 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
     unsigned originalFlags;
     originalFlags = topBlock->bbFlags;
     noway_assert((originalFlags & BBF_SPLIT_NONEXIST) == 0);
-    topBlock->bbFlags    &= ~(BBF_SPLIT_LOST);
+    topBlock->bbFlags &= ~(BBF_SPLIT_LOST);
     bottomBlock->bbFlags |= originalFlags & BBF_SPLIT_GAINED;
 
     //
@@ -21816,10 +21808,10 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
     GenTreePtr bottomBlock_Begin;
     GenTreePtr bottomBlock_End;
 
-    topBlock_Begin = nullptr;
-    topBlock_End = nullptr;
+    topBlock_Begin    = nullptr;
+    topBlock_End      = nullptr;
     bottomBlock_Begin = nullptr;
-    bottomBlock_End = nullptr;
+    bottomBlock_End   = nullptr;
 
     //
     // First figure out bottomBlock_Begin
@@ -21832,7 +21824,7 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
         // topBlock is empty before the split.
         // In this case, both topBlock and bottomBlock should be empty
         noway_assert(bottomBlock_Begin == nullptr);
-        topBlock->bbTreeList = nullptr;
+        topBlock->bbTreeList    = nullptr;
         bottomBlock->bbTreeList = nullptr;
     }
     else if (topBlock->bbTreeList == bottomBlock_Begin)
@@ -21843,7 +21835,7 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
         // And the split is before the first statement.
         // In this case, topBlock should be empty, and everything else should be moved to the bottonBlock.
         bottomBlock->bbTreeList = topBlock->bbTreeList;
-        topBlock->bbTreeList = nullptr;
+        topBlock->bbTreeList    = nullptr;
     }
     else if (bottomBlock_Begin == nullptr)
     {
@@ -21861,9 +21853,9 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
         noway_assert(bottomBlock_Begin);
 
         // This is the normal case where both blocks should contain at least one statement.
-        topBlock_Begin  = topBlock->bbTreeList;
+        topBlock_Begin = topBlock->bbTreeList;
         noway_assert(topBlock_Begin);
-        topBlock_End    = bottomBlock_Begin->gtPrev;
+        topBlock_End = bottomBlock_Begin->gtPrev;
         noway_assert(topBlock_End);
         bottomBlock_End = topBlock->lastStmt();
         noway_assert(bottomBlock_End);
@@ -21886,25 +21878,23 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
     bool inheritWeight;
     inheritWeight = true; // The firstBB does inherit the weight from the iciBlock
 
-    for (block = InlineeCompiler->fgFirstBB;
-         block != nullptr;
-         block = block->bbNext)
+    for (block = InlineeCompiler->fgFirstBB; block != nullptr; block = block->bbNext)
     {
         noway_assert(!block->hasTryIndex());
         noway_assert(!block->hasHndIndex());
         block->copyEHRegion(iciBlock);
-        block->bbFlags   |=  iciBlock->bbFlags & BBF_BACKWARD_JUMP;
+        block->bbFlags |= iciBlock->bbFlags & BBF_BACKWARD_JUMP;
 
         if (iciStmt->gtStmtILoffsx != BAD_IL_OFFSET)
         {
             block->bbCodeOffs    = jitGetILoffs(iciStmt->gtStmtILoffsx);
-            block->bbCodeOffsEnd = block->bbCodeOffs + 1;  // TODO: is code size of 1 some magic number for inlining?
+            block->bbCodeOffsEnd = block->bbCodeOffs + 1; // TODO: is code size of 1 some magic number for inlining?
         }
         else
         {
-            block->bbCodeOffs     = 0; // TODO: why not BAD_IL_OFFSET?
-            block->bbCodeOffsEnd  = 0;
-            block->bbFlags    |= BBF_INTERNAL;
+            block->bbCodeOffs    = 0; // TODO: why not BAD_IL_OFFSET?
+            block->bbCodeOffsEnd = 0;
+            block->bbFlags |= BBF_INTERNAL;
         }
 
         if (block->bbJumpKind == BBJ_RETURN)
@@ -21918,8 +21908,8 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
 #ifdef DEBUG
                 if (verbose)
                 {
-                    printf("\nConvert bbJumpKind of BB%02u to BBJ_ALWAYS to bottomBlock BB%02u\n",
-                           block->bbNum, bottomBlock->bbNum);
+                    printf("\nConvert bbJumpKind of BB%02u to BBJ_ALWAYS to bottomBlock BB%02u\n", block->bbNum,
+                           bottomBlock->bbNum);
                 }
 #endif // DEBUG
             }
@@ -21973,18 +21963,18 @@ _Done:
     //
     // Copy out some flags
     //
-    compLongUsed              |= InlineeCompiler->compLongUsed;
-    compFloatingPointUsed     |= InlineeCompiler->compFloatingPointUsed;
-    compLocallocUsed          |= InlineeCompiler->compLocallocUsed;
-    compQmarkUsed             |= InlineeCompiler->compQmarkUsed;
-    compUnsafeCastUsed        |= InlineeCompiler->compUnsafeCastUsed;
+    compLongUsed |= InlineeCompiler->compLongUsed;
+    compFloatingPointUsed |= InlineeCompiler->compFloatingPointUsed;
+    compLocallocUsed |= InlineeCompiler->compLocallocUsed;
+    compQmarkUsed |= InlineeCompiler->compQmarkUsed;
+    compUnsafeCastUsed |= InlineeCompiler->compUnsafeCastUsed;
     compNeedsGSSecurityCookie |= InlineeCompiler->compNeedsGSSecurityCookie;
-    compGSReorderStackLayout  |= InlineeCompiler->compGSReorderStackLayout;
+    compGSReorderStackLayout |= InlineeCompiler->compGSReorderStackLayout;
 
     // Update unmanaged call count
-    info.compCallUnmanaged    += InlineeCompiler->info.compCallUnmanaged;
+    info.compCallUnmanaged += InlineeCompiler->info.compCallUnmanaged;
 
-    // Update optMethodFlags
+// Update optMethodFlags
 
 #ifdef DEBUG
     unsigned optMethodFlagsBefore = optMethodFlags;
@@ -21995,8 +21985,8 @@ _Done:
 #ifdef DEBUG
     if (optMethodFlags != optMethodFlagsBefore)
     {
-        JITDUMP("INLINER: Updating optMethodFlags --  root:%0x callee:%0x new:%0x\n",
-                optMethodFlagsBefore, InlineeCompiler->optMethodFlags, optMethodFlags);
+        JITDUMP("INLINER: Updating optMethodFlags --  root:%0x callee:%0x new:%0x\n", optMethodFlagsBefore,
+                InlineeCompiler->optMethodFlags, optMethodFlags);
     }
 #endif
 
@@ -22049,13 +22039,13 @@ _Done:
 
 GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
 {
-    BasicBlock* block = inlineInfo->iciBlock;
-    GenTreeStmt* callStmt  = inlineInfo->iciStmt;
-    IL_OFFSETX callILOffset = callStmt->gtStmtILoffsx;
-    GenTreeStmt* postStmt  = callStmt->gtNextStmt;
-    GenTreePtr afterStmt = callStmt; // afterStmt is the place where the new statements should be inserted after.
-    GenTreePtr newStmt = nullptr;
-    GenTreePtr call = inlineInfo->iciCall;
+    BasicBlock*  block        = inlineInfo->iciBlock;
+    GenTreeStmt* callStmt     = inlineInfo->iciStmt;
+    IL_OFFSETX   callILOffset = callStmt->gtStmtILoffsx;
+    GenTreeStmt* postStmt     = callStmt->gtNextStmt;
+    GenTreePtr   afterStmt    = callStmt; // afterStmt is the place where the new statements should be inserted after.
+    GenTreePtr   newStmt      = nullptr;
+    GenTreePtr   call         = inlineInfo->iciCall;
 
     noway_assert(call->gtOper == GT_CALL);
 
@@ -22070,12 +22060,13 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
 
     // Prepend statements for any initialization / side effects
 
-    InlArgInfo*       inlArgInfo = inlineInfo->inlArgInfo;
-    InlLclVarInfo*    lclVarInfo = inlineInfo->lclVarInfo;
+    InlArgInfo*    inlArgInfo = inlineInfo->inlArgInfo;
+    InlLclVarInfo* lclVarInfo = inlineInfo->lclVarInfo;
 
     GenTreePtr tree;
 
-    // Create the null check statement (but not appending it to the statement list yet) for the 'this' pointer if necessary.
+    // Create the null check statement (but not appending it to the statement list yet) for the 'this' pointer if
+    // necessary.
     // The NULL check should be done after "argument setup statements".
     // The only reason we move it here is for calling "impInlineFetchArg(0,..." to reserve a temp
     // for the "this" pointer.
@@ -22087,8 +22078,7 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
     if (call->gtFlags & GTF_CALL_NULLCHECK && !inlineInfo->thisDereferencedFirst)
     {
         // Call impInlineFetchArg to "reserve" a temp for the "this" pointer.
-        nullcheck = gtNewOperNode(GT_IND, TYP_INT,
-                                  impInlineFetchArg(0, inlArgInfo, lclVarInfo));
+        nullcheck = gtNewOperNode(GT_IND, TYP_INT, impInlineFetchArg(0, inlArgInfo, lclVarInfo));
         nullcheck->gtFlags |= GTF_EXCEPT;
 
         // The NULL-check statement will be inserted to the statement list after those statements
@@ -22126,10 +22116,8 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
 
                 GenTreePtr argSingleUseNode = inlArgInfo[argNum].argBashTmpNode;
 
-                if (argSingleUseNode &&
-                    !(argSingleUseNode->gtFlags & GTF_VAR_CLONED) &&
-                    !inlArgInfo[argNum].argHasLdargaOp &&
-                    !inlArgInfo[argNum].argHasStargOp)
+                if (argSingleUseNode && !(argSingleUseNode->gtFlags & GTF_VAR_CLONED) &&
+                    !inlArgInfo[argNum].argHasLdargaOp && !inlArgInfo[argNum].argHasStargOp)
                 {
                     // Change the temp in-place to the actual argument.
                     // We currently do not support this for struct arguments, so it must not be a GT_OBJ.
@@ -22150,15 +22138,12 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
                         noway_assert(structHnd != NO_CLASS_HANDLE);
                     }
 
-                    // Unsafe value cls check is not needed for argTmpNum here since in-linee compiler instance would have
-                    // iterated over these and marked them accordingly.
-                    impAssignTempGen(inlArgInfo[argNum].argTmpNum,
-                                     inlArgInfo[argNum].argNode,
-                                     structHnd,
-                                     (unsigned)CHECK_SPILL_NONE,
-                                     & afterStmt,
-                                     callILOffset,
-                                     block);
+                    // Unsafe value cls check is not needed for
+                    // argTmpNum here since in-linee compiler instance
+                    // would have iterated over these and marked them
+                    // accordingly.
+                    impAssignTempGen(inlArgInfo[argNum].argTmpNum, inlArgInfo[argNum].argNode, structHnd,
+                                     (unsigned)CHECK_SPILL_NONE, &afterStmt, callILOffset, block);
 
 #ifdef DEBUG
                     if (verbose)
@@ -22166,7 +22151,6 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
                         gtDispTree(afterStmt);
                     }
 #endif // DEBUG
-
                 }
             }
             else if (inlArgInfo[argNum].argIsByRefToStructLocal)
@@ -22177,19 +22161,18 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
             {
                 /* The argument is either not used or a const or lcl var */
 
-                noway_assert(!inlArgInfo[argNum].argIsUsed  ||
-                              inlArgInfo[argNum].argIsInvariant ||
-                              inlArgInfo[argNum].argIsLclVar );
+                noway_assert(!inlArgInfo[argNum].argIsUsed || inlArgInfo[argNum].argIsInvariant ||
+                             inlArgInfo[argNum].argIsLclVar);
 
                 /* Make sure we didnt change argNode's along the way, or else
                    subsequent uses of the arg would have worked with the bashed value */
                 if (inlArgInfo[argNum].argIsInvariant)
                 {
-                    assert(inlArgInfo[argNum].argNode->OperIsConst() ||
-                           inlArgInfo[argNum].argNode->gtOper == GT_ADDR);
+                    assert(inlArgInfo[argNum].argNode->OperIsConst() || inlArgInfo[argNum].argNode->gtOper == GT_ADDR);
                 }
                 noway_assert((inlArgInfo[argNum].argIsLclVar == 0) ==
-                             (inlArgInfo[argNum].argNode->gtOper != GT_LCL_VAR || (inlArgInfo[argNum].argNode->gtFlags & GTF_GLOB_REF)));
+                             (inlArgInfo[argNum].argNode->gtOper != GT_LCL_VAR ||
+                              (inlArgInfo[argNum].argNode->gtFlags & GTF_GLOB_REF)));
 
                 /* If the argument has side effects, append it */
 
@@ -22217,7 +22200,6 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
                         gtDispTree(afterStmt);
                     }
 #endif // DEBUG
-
                 }
             }
         }
@@ -22232,7 +22214,7 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
     if (inlineInfo->inlineCandidateInfo->initClassResult & CORINFO_INITCLASS_USE_HELPER)
     {
         CORINFO_CONTEXT_HANDLE exactContext = inlineInfo->inlineCandidateInfo->exactContextHnd;
-        CORINFO_CLASS_HANDLE exactClass;
+        CORINFO_CLASS_HANDLE   exactClass;
 
         if (((SIZE_T)exactContext & CORINFO_CONTEXTFLAGS_MASK) == CORINFO_CONTEXTFLAGS_CLASS)
         {
@@ -22240,18 +22222,19 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
         }
         else
         {
-            exactClass = info.compCompHnd->getMethodClass(CORINFO_METHOD_HANDLE((SIZE_T)exactContext & ~CORINFO_CONTEXTFLAGS_MASK));
+            exactClass = info.compCompHnd->getMethodClass(
+                CORINFO_METHOD_HANDLE((SIZE_T)exactContext & ~CORINFO_CONTEXTFLAGS_MASK));
         }
 
-        tree = fgGetSharedCCtor(exactClass);
-        newStmt = gtNewStmt(tree, callILOffset);
+        tree      = fgGetSharedCCtor(exactClass);
+        newStmt   = gtNewStmt(tree, callILOffset);
         afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt);
     }
 
     // Insert the nullcheck statement now.
     if (nullcheck)
     {
-        newStmt = gtNewStmt(nullcheck, callILOffset);
+        newStmt   = gtNewStmt(nullcheck, callILOffset);
         afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt);
     }
 
@@ -22264,8 +22247,7 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
     unsigned lclCnt = InlineeMethodInfo->locals.numArgs;
 
     // Does callee contain any zero-init local?
-    if ((lclCnt != 0) &&
-        (InlineeMethodInfo->options & CORINFO_OPT_INIT_LOCALS) != 0)
+    if ((lclCnt != 0) && (InlineeMethodInfo->options & CORINFO_OPT_INIT_LOCALS) != 0)
     {
 
 #ifdef DEBUG
@@ -22277,7 +22259,7 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
 
         for (unsigned lclNum = 0; lclNum < lclCnt; lclNum++)
         {
-            unsigned  tmpNum = inlineInfo->lclTmpNum[lclNum];
+            unsigned tmpNum = inlineInfo->lclTmpNum[lclNum];
 
             // Is the local used at all?
             if (tmpNum != BAD_VAR_NUM)
@@ -22289,25 +22271,21 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
                 {
                     // Unsafe value cls check is not needed here since in-linee compiler instance would have
                     // iterated over locals and marked accordingly.
-                    impAssignTempGen(tmpNum,
-                                     gtNewZeroConNode(genActualType(lclTyp)),
-                                     NO_CLASS_HANDLE,
-                                     (unsigned)CHECK_SPILL_NONE,
-                                     & afterStmt,
-                                     callILOffset,
-                                     block);
+                    impAssignTempGen(tmpNum, gtNewZeroConNode(genActualType(lclTyp)), NO_CLASS_HANDLE,
+                                     (unsigned)CHECK_SPILL_NONE, &afterStmt, callILOffset, block);
                 }
                 else
                 {
-                    CORINFO_CLASS_HANDLE structType = lclVarInfo[lclNum + inlineInfo->argCnt].lclVerTypeInfo.GetClassHandle();
+                    CORINFO_CLASS_HANDLE structType =
+                        lclVarInfo[lclNum + inlineInfo->argCnt].lclVerTypeInfo.GetClassHandle();
 
-                    tree = gtNewBlkOpNode(gtNewLclvNode(tmpNum, lclTyp), // Dest
-                                          gtNewIconNode(0), // Value
+                    tree = gtNewBlkOpNode(gtNewLclvNode(tmpNum, lclTyp),              // Dest
+                                          gtNewIconNode(0),                           // Value
                                           info.compCompHnd->getClassSize(structType), // Size
-                                          false,            // isVolatile
-                                          false);           // not copyBlock
+                                          false,                                      // isVolatile
+                                          false);                                     // not copyBlock
 
-                    newStmt = gtNewStmt(tree, callILOffset);
+                    newStmt   = gtNewStmt(tree, callILOffset);
                     afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt);
                 }
 
@@ -22335,7 +22313,7 @@ GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
 
 //------------------------------------------------------------------------
 // fgInlineAppendStatements: Append statements that are needed
-// after the inlined call. 
+// after the inlined call.
 //
 // Arguments:
 //    inlineInfo - information about the inline
@@ -22353,11 +22331,11 @@ void Compiler::fgInlineAppendStatements(InlineInfo* inlineInfo, BasicBlock* bloc
 
     JITDUMP("Unpin inlinee locals:\n");
 
-    GenTreePtr callStmt  = inlineInfo->iciStmt;
-    IL_OFFSETX callILOffset = callStmt->gtStmt.gtStmtILoffsx;
+    GenTreePtr           callStmt          = inlineInfo->iciStmt;
+    IL_OFFSETX           callILOffset      = callStmt->gtStmt.gtStmtILoffsx;
     CORINFO_METHOD_INFO* InlineeMethodInfo = InlineeCompiler->info.compMethodInfo;
-    unsigned lclCnt = InlineeMethodInfo->locals.numArgs;
-    InlLclVarInfo*    lclVarInfo = inlineInfo->lclVarInfo;
+    unsigned             lclCnt            = InlineeMethodInfo->locals.numArgs;
+    InlLclVarInfo*       lclVarInfo        = inlineInfo->lclVarInfo;
 
     noway_assert(callStmt->gtOper == GT_STMT);
 
@@ -22411,14 +22389,12 @@ void Compiler::fgInlineAppendStatements(InlineInfo* inlineInfo, BasicBlock* bloc
             gtDispTree(unpinStmt);
         }
 #endif // DEBUG
-
     }
 }
 
 /*****************************************************************************/
 /*static*/
-Compiler::fgWalkResult  Compiler::fgChkThrowCB(GenTreePtr* pTree,
-                                               fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgChkThrowCB(GenTreePtr* pTree, fgWalkData* data)
 {
     GenTreePtr tree = *pTree;
 
@@ -22431,28 +22407,30 @@ Compiler::fgWalkResult  Compiler::fgChkThrowCB(GenTreePtr* pTree,
 
     switch (tree->gtOper)
     {
-    case GT_MUL:
-    case GT_ADD:
-    case GT_SUB:
-    case GT_ASG_ADD:
-    case GT_ASG_SUB:
-    case GT_CAST:
-        if (tree->gtOverflow()) {
-            return Compiler::WALK_ABORT;
-}
-        break;
+        case GT_MUL:
+        case GT_ADD:
+        case GT_SUB:
+        case GT_ASG_ADD:
+        case GT_ASG_SUB:
+        case GT_CAST:
+            if (tree->gtOverflow())
+            {
+                return Compiler::WALK_ABORT;
+            }
+            break;
 
-    case GT_INDEX:
-        if (tree->gtFlags & GTF_INX_RNGCHK) {
-            return Compiler::WALK_ABORT;
-}
-        break;
+        case GT_INDEX:
+            if (tree->gtFlags & GTF_INX_RNGCHK)
+            {
+                return Compiler::WALK_ABORT;
+            }
+            break;
 
-    case GT_ARR_BOUNDS_CHECK:
-        return Compiler::WALK_ABORT;
+        case GT_ARR_BOUNDS_CHECK:
+            return Compiler::WALK_ABORT;
 
-    default:
-        break;
+        default:
+            break;
     }
 
     return Compiler::WALK_CONTINUE;
@@ -22460,33 +22438,32 @@ Compiler::fgWalkResult  Compiler::fgChkThrowCB(GenTreePtr* pTree,
 
 /*****************************************************************************/
 /*static*/
-Compiler::fgWalkResult  Compiler::fgChkLocAllocCB(GenTreePtr* pTree,
-                                                  fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgChkLocAllocCB(GenTreePtr* pTree, fgWalkData* data)
 {
     GenTreePtr tree = *pTree;
 
-    if (tree->gtOper == GT_LCLHEAP) {
+    if (tree->gtOper == GT_LCLHEAP)
+    {
         return Compiler::WALK_ABORT;
-}
+    }
 
     return Compiler::WALK_CONTINUE;
 }
 
 /*****************************************************************************/
 /*static*/
-Compiler::fgWalkResult  Compiler::fgChkQmarkCB(GenTreePtr* pTree,
-                                               fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgChkQmarkCB(GenTreePtr* pTree, fgWalkData* data)
 {
     GenTreePtr tree = *pTree;
 
-    if (tree->gtOper == GT_QMARK) {
+    if (tree->gtOper == GT_QMARK)
+    {
         return Compiler::WALK_ABORT;
-}
+    }
 
     return Compiler::WALK_CONTINUE;
 }
 
-
 void Compiler::fgLclFldAssign(unsigned lclNum)
 {
     assert(varTypeIsStruct(lvaTable[lclNum].lvType));
index 05a3a4a..b5390f3 100644 (file)
@@ -4258,6 +4258,8 @@ public:
     GenTreeDynBlk(GenTreePtr addr, GenTreePtr dynamicSize)
         : GenTreeBlk(GT_DYN_BLK, TYP_STRUCT, addr, 0), gtDynamicSize(dynamicSize), gtEvalSizeFirst(false)
     {
+        // Conservatively the 'addr' could be null or point into the global heap.
+        gtFlags |= GTF_EXCEPT | GTF_GLOB_REF;
         gtFlags |= (dynamicSize->gtFlags & GTF_ALL_EFFECT);
     }
 
index c7b0e91..61e70c3 100644 (file)
@@ -2463,7 +2463,7 @@ bool ReplayPolicy::FindMethod()
 
         // See if token matches
         unsigned token = 0;
-        int      count = sscanf(buffer, " <Token>%u</Token> ", &token);
+        int      count = sscanf_s(buffer, " <Token>%u</Token> ", &token);
         if ((count != 1) || (token != methodToken))
         {
             continue;
@@ -2477,7 +2477,7 @@ bool ReplayPolicy::FindMethod()
 
         // See if hash matches
         unsigned hash = 0;
-        count         = sscanf(buffer, " <Hash>%u</Hash> ", &hash);
+        count         = sscanf_s(buffer, " <Hash>%u</Hash> ", &hash);
         if ((count != 1) || (hash != methodHash))
         {
             continue;
@@ -2636,7 +2636,7 @@ bool ReplayPolicy::FindInline(unsigned token, unsigned hash, unsigned offset)
 
         // Match token
         unsigned inlineToken = 0;
-        int      count       = sscanf(buffer, " <Token>%u</Token> ", &inlineToken);
+        int      count       = sscanf_s(buffer, " <Token>%u</Token> ", &inlineToken);
 
         if ((count != 1) || (inlineToken != token))
         {
@@ -2651,7 +2651,7 @@ bool ReplayPolicy::FindInline(unsigned token, unsigned hash, unsigned offset)
 
         // Match hash
         unsigned inlineHash = 0;
-        count               = sscanf(buffer, " <Hash>%u</Hash> ", &inlineHash);
+        count               = sscanf_s(buffer, " <Hash>%u</Hash> ", &inlineHash);
 
         if ((count != 1) || (inlineHash != hash))
         {
@@ -2666,7 +2666,7 @@ bool ReplayPolicy::FindInline(unsigned token, unsigned hash, unsigned offset)
 
         // Match offset
         unsigned inlineOffset = 0;
-        count                 = sscanf(buffer, " <Offset>%u</Offset> ", &inlineOffset);
+        count                 = sscanf_s(buffer, " <Offset>%u</Offset> ", &inlineOffset);
         if ((count != 1) || (inlineOffset != offset))
         {
             continue;
@@ -2685,7 +2685,7 @@ bool ReplayPolicy::FindInline(unsigned token, unsigned hash, unsigned offset)
         if (fgets(buffer, sizeof(buffer), s_ReplayFile) != nullptr)
         {
             unsigned collectData = 0;
-            count                = sscanf(buffer, " <CollectData>%u</CollectData> ", &collectData);
+            count                = sscanf_s(buffer, " <CollectData>%u</CollectData> ", &collectData);
 
             if (count == 1)
             {
index 67cea2f..9092029 100644 (file)
@@ -32,10 +32,76 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 #include "lower.h"
 #include "lsra.h"
 
-/* Lowering of GT_CAST nodes */
+//------------------------------------------------------------------------
+// LowerCast: Lower GT_CAST(srcType, DstType) nodes.
+//
+// Arguments:
+//    tree - GT_CAST node to be lowered
+//
+// Return Value:
+//    None.
+//
+// Notes:
+//    Casts from small int type to float/double are transformed as follows:
+//    GT_CAST(byte, float/double)     =   GT_CAST(GT_CAST(byte, int32), float/double)
+//    GT_CAST(sbyte, float/double)    =   GT_CAST(GT_CAST(sbyte, int32), float/double)
+//    GT_CAST(int16, float/double)    =   GT_CAST(GT_CAST(int16, int32), float/double)
+//    GT_CAST(uint16, float/double)   =   GT_CAST(GT_CAST(uint16, int32), float/double)
+//
+//    Similarly casts from float/double to a smaller int type are transformed as follows:
+//    GT_CAST(float/double, byte)     =   GT_CAST(GT_CAST(float/double, int32), byte)
+//    GT_CAST(float/double, sbyte)    =   GT_CAST(GT_CAST(float/double, int32), sbyte)
+//    GT_CAST(float/double, int16)    =   GT_CAST(GT_CAST(double/double, int32), int16)
+//    GT_CAST(float/double, uint16)   =   GT_CAST(GT_CAST(double/double, int32), uint16)
+//
+//    Note that for the overflow conversions we still depend on helper calls and
+//    don't expect to see them here.
+//    i) GT_CAST(float/double, int type with overflow detection)
+
 void Lowering::LowerCast(GenTree* tree)
 {
-    NYI_ARM("ARM Lowering for cast");
+    assert(tree->OperGet() == GT_CAST);
+
+    JITDUMP("LowerCast for: ");
+    DISPNODE(tree);
+    JITDUMP("\n");
+
+    GenTreePtr op1     = tree->gtOp.gtOp1;
+    var_types  dstType = tree->CastToType();
+    var_types  srcType = op1->TypeGet();
+    var_types  tmpType = TYP_UNDEF;
+
+    // TODO-ARM-Cleanup: Remove following NYI assertions.
+    if (varTypeIsFloating(srcType))
+    {
+        NYI_ARM("Lowering for cast from float"); // Not tested yet.
+        noway_assert(!tree->gtOverflow());
+    }
+
+    // Case of src is a small type and dst is a floating point type.
+    if (varTypeIsSmall(srcType) && varTypeIsFloating(dstType))
+    {
+        NYI_ARM("Lowering for cast from small type to float"); // Not tested yet.
+        // These conversions can never be overflow detecting ones.
+        noway_assert(!tree->gtOverflow());
+        tmpType = TYP_INT;
+    }
+    // case of src is a floating point type and dst is a small type.
+    else if (varTypeIsFloating(srcType) && varTypeIsSmall(dstType))
+    {
+        NYI_ARM("Lowering for cast from float to small type"); // Not tested yet.
+        tmpType = TYP_INT;
+    }
+
+    if (tmpType != TYP_UNDEF)
+    {
+        GenTreePtr tmp = comp->gtNewCastNode(tmpType, op1, tmpType);
+        tmp->gtFlags |= (tree->gtFlags & (GTF_UNSIGNED | GTF_OVERFLOW | GTF_EXCEPT));
+
+        tree->gtFlags &= ~GTF_UNSIGNED;
+        tree->gtOp.gtOp1 = tmp;
+        BlockRange().InsertAfter(op1, tmp);
+    }
 }
 
 void Lowering::LowerRotate(GenTreePtr tree)
index 94410c8..589cef4 100644 (file)
@@ -3659,17 +3659,6 @@ void Lowering::TreeNodeInfoInitCmp(GenTreePtr tree)
                         //
                         assert(!castOp1->gtOverflowEx()); // Must not be an overflow checking operation
 
-                        GenTreePtr removeTreeNode = op1;
-                        tree->gtOp.gtOp1          = castOp1;
-                        op1                       = castOp1;
-                        castOp1->gtType           = TYP_UBYTE;
-
-                        // trim down the value if castOp1 is an int constant since its type changed to UBYTE.
-                        if (castOp1Oper == GT_CNS_INT)
-                        {
-                            castOp1->gtIntCon.gtIconVal = (UINT8)castOp1->gtIntCon.gtIconVal;
-                        }
-
                         // TODO-Cleanup: we're within "if (CheckImmedAndMakeContained(tree, op2))", so isn't
                         // the following condition always true?
                         if (op2->isContainedIntOrIImmed())
@@ -3677,6 +3666,17 @@ void Lowering::TreeNodeInfoInitCmp(GenTreePtr tree)
                             ssize_t val = (ssize_t)op2->AsIntConCommon()->IconValue();
                             if (val >= 0 && val <= 255)
                             {
+                                GenTreePtr removeTreeNode = op1;
+                                tree->gtOp.gtOp1          = castOp1;
+                                op1                       = castOp1;
+                                castOp1->gtType           = TYP_UBYTE;
+
+                                // trim down the value if castOp1 is an int constant since its type changed to UBYTE.
+                                if (castOp1Oper == GT_CNS_INT)
+                                {
+                                    castOp1->gtIntCon.gtIconVal = (UINT8)castOp1->gtIntCon.gtIconVal;
+                                }
+
                                 op2->gtType = TYP_UBYTE;
                                 tree->gtFlags |= GTF_UNSIGNED;
 
@@ -3687,27 +3687,26 @@ void Lowering::TreeNodeInfoInitCmp(GenTreePtr tree)
                                     MakeSrcContained(tree, op1);
                                     op1IsMadeContained = true;
                                 }
-                            }
-                        }
 
-                        BlockRange().Remove(removeTreeNode);
+                                BlockRange().Remove(removeTreeNode);
 
-                        // We've changed the type on op1 to TYP_UBYTE, but we already processed that node. We need to
-                        // go back and mark it byteable.
-                        // TODO-Cleanup: it might be better to move this out of the TreeNodeInfoInit pass to the earlier
-                        // "lower" pass, in which case the byteable check would just fall out. But that is quite
-                        // complex!
-                        TreeNodeInfoInitCheckByteable(op1);
+                                // We've changed the type on op1 to TYP_UBYTE, but we already processed that node.
+                                // We need to go back and mark it byteable.
+                                // TODO-Cleanup: it might be better to move this out of the TreeNodeInfoInit pass to
+                                // the earlier "lower" pass, in which case the byteable check would just fall out.
+                                // But that is quite complex!
+                                TreeNodeInfoInitCheckByteable(op1);
 
 #ifdef DEBUG
-                        if (comp->verbose)
-                        {
-                            printf(
-                                "TreeNodeInfoInitCmp: Removing a GT_CAST to TYP_UBYTE and changing castOp1->gtType to "
-                                "TYP_UBYTE\n");
-                            comp->gtDispTreeRange(BlockRange(), tree);
-                        }
+                                if (comp->verbose)
+                                {
+                                    printf("TreeNodeInfoInitCmp: Removing a GT_CAST to TYP_UBYTE and changing "
+                                           "castOp1->gtType to TYP_UBYTE\n");
+                                    comp->gtDispTreeRange(BlockRange(), tree);
+                                }
 #endif
+                            }
+                        }
                     }
                 }
 
@@ -3834,7 +3833,6 @@ void Lowering::LowerCast(GenTree* tree)
     var_types  dstType = tree->CastToType();
     var_types  srcType = op1->TypeGet();
     var_types  tmpType = TYP_UNDEF;
-    bool       srcUns  = false;
 
     // force the srcType to unsigned if GT_UNSIGNED flag is set
     if (tree->gtFlags & GTF_UNSIGNED)
index 6813beb..10f58dd 100644 (file)
@@ -3684,7 +3684,51 @@ void LinearScan::buildRefPositionsForNode(GenTree*                  tree,
     // (i.e. the target is read-modify-write), preference the dst to op1.
 
     bool hasDelayFreeSrc = tree->gtLsraInfo.hasDelayFreeSrc;
-    if (tree->OperGet() == GT_PUTARG_REG && isCandidateLocalRef(tree->gtGetOp1()) &&
+
+#if defined(DEBUG) && defined(_TARGET_X86_)
+    // On x86, `LSRA_LIMIT_CALLER` is too restrictive to allow the use of special put args: this stress mode
+    // leaves only three registers allocatable--eax, ecx, and edx--of which the latter two are also used for the
+    // first two integral arguments to a call. This can leave us with too few registers to succesfully allocate in
+    // situations like the following:
+    //
+    //     t1026 =    lclVar    ref    V52 tmp35        u:3 REG NA <l:$3a1, c:$98d>
+    //
+    //             /--*  t1026  ref
+    //     t1352 = *  putarg_reg ref    REG NA
+    //
+    //      t342 =    lclVar    int    V14 loc6         u:4 REG NA $50c
+    //
+    //      t343 =    const     int    1 REG NA $41
+    //
+    //             /--*  t342   int
+    //             +--*  t343   int
+    //      t344 = *  +         int    REG NA $495
+    //
+    //      t345 =    lclVar    int    V04 arg4         u:2 REG NA $100
+    //
+    //             /--*  t344   int
+    //             +--*  t345   int
+    //      t346 = *  %         int    REG NA $496
+    //
+    //             /--*  t346   int
+    //     t1353 = *  putarg_reg int    REG NA
+    //
+    //     t1354 =    lclVar    ref    V52 tmp35         (last use) REG NA
+    //
+    //             /--*  t1354  ref
+    //     t1355 = *  lea(b+0)  byref  REG NA
+    //
+    // Here, the first `putarg_reg` would normally be considered a special put arg, which would remove `ecx` from the
+    // set of allocatable registers, leaving only `eax` and `edx`. The allocator will then fail to allocate a register
+    // for the def of `t345` if arg4 is not a register candidate: the corresponding ref position will be constrained to
+    // { `ecx`, `ebx`, `esi`, `edi` }, which `LSRA_LIMIT_CALLER` will further constrain to `ecx`, which will not be
+    // available due to the special put arg.
+    const bool supportsSpecialPutArg = getStressLimitRegs() != LSRA_LIMIT_CALLER;
+#else
+    const bool supportsSpecialPutArg = true;
+#endif
+
+    if (supportsSpecialPutArg && tree->OperGet() == GT_PUTARG_REG && isCandidateLocalRef(tree->gtGetOp1()) &&
         (tree->gtGetOp1()->gtFlags & GTF_VAR_DEATH) == 0)
     {
         // This is the case for a "pass-through" copy of a lclVar.  In the case where it is a non-last-use,
@@ -4854,11 +4898,11 @@ void LinearScan::setFrameType()
     compiler->rpFrameType = frameType;
 }
 
-// Is the copyReg given by this RefPosition still busy at the
+// Is the copyReg/moveReg given by this RefPosition still busy at the
 // given location?
-bool copyRegInUse(RefPosition* ref, LsraLocation loc)
+bool copyOrMoveRegInUse(RefPosition* ref, LsraLocation loc)
 {
-    assert(ref->copyReg);
+    assert(ref->copyReg || ref->moveReg);
     if (ref->getRefEndLocation() >= loc)
     {
         return true;
@@ -4918,14 +4962,15 @@ bool LinearScan::registerIsAvailable(RegRecord*    physRegRecord,
             return false;
         }
 
-        // Is this a copyReg?  It is if the register assignment doesn't match.
-        // (the recentReference may not be a copyReg, because we could have seen another
-        // reference since the copyReg)
+        // Is this a copyReg/moveReg?  It is if the register assignment doesn't match.
+        // (the recentReference may not be a copyReg/moveReg, because we could have seen another
+        // reference since the copyReg/moveReg)
 
         if (!assignedInterval->isAssignedTo(physRegRecord->regNum))
         {
             // Don't reassign it if it's still in use
-            if (recentReference->copyReg && copyRegInUse(recentReference, currentLoc))
+            if ((recentReference->copyReg || recentReference->moveReg) &&
+                copyOrMoveRegInUse(recentReference, currentLoc))
             {
                 return false;
             }
@@ -7191,59 +7236,44 @@ void LinearScan::allocateRegisters()
                 assert(currentInterval != nullptr);
 
                 // It's already in a register, but not one we need.
-                // If it is a fixed use that is not marked "delayRegFree", there is already a FixedReg to ensure that
-                // the needed reg is not otherwise in use, so we can simply ignore it and codegen will do the copy.
-                // The reason we need special handling for the "delayRegFree" case is that we need to mark the
-                // fixed-reg as in-use and delayed (the FixedReg RefPosition doesn't handle the delay requirement).
-                // Otherwise, if this is a pure use localVar or tree temp, we assign a copyReg, but must free both regs
-                // if it is a last use.
-                if (!currentRefPosition->isFixedRegRef || currentRefPosition->delayRegFree)
-                {
-                    if (!RefTypeIsDef(currentRefPosition->refType))
+                if (!RefTypeIsDef(currentRefPosition->refType))
+                {
+                    regNumber copyReg = assignCopyReg(currentRefPosition);
+                    assert(copyReg != REG_NA);
+                    INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_COPY_REG, currentInterval, copyReg));
+                    lastAllocatedRefPosition = currentRefPosition;
+                    if (currentRefPosition->lastUse)
                     {
-                        regNumber copyReg = assignCopyReg(currentRefPosition);
-                        assert(copyReg != REG_NA);
-                        INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_COPY_REG, currentInterval, copyReg));
-                        lastAllocatedRefPosition = currentRefPosition;
-                        if (currentRefPosition->lastUse)
+                        if (currentRefPosition->delayRegFree)
                         {
-                            if (currentRefPosition->delayRegFree)
-                            {
-                                INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE_DELAYED, currentInterval,
-                                                                assignedRegister));
-                                delayRegsToFree |=
-                                    (genRegMask(assignedRegister) | currentRefPosition->registerAssignment);
-                            }
-                            else
-                            {
-                                INDEBUG(
-                                    dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE, currentInterval, assignedRegister));
-                                regsToFree |= (genRegMask(assignedRegister) | currentRefPosition->registerAssignment);
-                            }
+                            INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE_DELAYED, currentInterval,
+                                                            assignedRegister));
+                            delayRegsToFree |= (genRegMask(assignedRegister) | currentRefPosition->registerAssignment);
                         }
-                        // If this is a tree temp (non-localVar) interval, we will need an explicit move.
-                        if (!currentInterval->isLocalVar)
+                        else
                         {
-                            currentRefPosition->moveReg = true;
-                            currentRefPosition->copyReg = false;
+                            INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE, currentInterval, assignedRegister));
+                            regsToFree |= (genRegMask(assignedRegister) | currentRefPosition->registerAssignment);
                         }
-                        continue;
                     }
-                    else
+                    // If this is a tree temp (non-localVar) interval, we will need an explicit move.
+                    if (!currentInterval->isLocalVar)
                     {
-                        INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_NEEDS_NEW_REG, nullptr, assignedRegister));
-                        regsToFree |= genRegMask(assignedRegister);
-                        // We want a new register, but we don't want this to be considered a spill.
-                        assignedRegister = REG_NA;
-                        if (physRegRecord->assignedInterval == currentInterval)
-                        {
-                            unassignPhysRegNoSpill(physRegRecord);
-                        }
+                        currentRefPosition->moveReg = true;
+                        currentRefPosition->copyReg = false;
                     }
+                    continue;
                 }
                 else
                 {
-                    INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_KEPT_ALLOCATION, nullptr, assignedRegister));
+                    INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_NEEDS_NEW_REG, nullptr, assignedRegister));
+                    regsToFree |= genRegMask(assignedRegister);
+                    // We want a new register, but we don't want this to be considered a spill.
+                    assignedRegister = REG_NA;
+                    if (physRegRecord->assignedInterval == currentInterval)
+                    {
+                        unassignPhysRegNoSpill(physRegRecord);
+                    }
                 }
             }
         }
@@ -11725,9 +11755,18 @@ void LinearScan::verifyFinalAllocation()
                     {
                         if (VERBOSE)
                         {
+                            // If refPos is marked as copyReg, then the reg that is spilled
+                            // is the homeReg of the interval not the reg currently assigned
+                            // to refPos.
+                            regNumber spillReg = regNum;
+                            if (currentRefPosition->copyReg)
+                            {
+                                assert(interval != nullptr);
+                                spillReg = interval->physReg;
+                            }
                             dumpRegRecords();
                             dumpEmptyRefPosition();
-                            printf("Spill %-4s ", getRegName(regNum));
+                            printf("Spill %-4s ", getRegName(spillReg));
                         }
                     }
                     else if (currentRefPosition->copyReg)
@@ -11788,15 +11827,14 @@ void LinearScan::verifyFinalAllocation()
                     interval->physReg     = REG_NA;
                     interval->assignedReg = nullptr;
 
-                    // regRegcord could be null if RefPosition is to be allocated a
-                    // reg only if profitable.
+                    // regRegcord could be null if the RefPosition does not require a register.
                     if (regRecord != nullptr)
                     {
                         regRecord->assignedInterval = nullptr;
                     }
                     else
                     {
-                        assert(currentRefPosition->AllocateIfProfitable());
+                        assert(!currentRefPosition->RequiresRegister());
                     }
                 }
             }
@@ -11902,6 +11940,8 @@ void LinearScan::verifyResolutionMove(GenTree* resolutionMove, LsraLocation curr
         assert(leftInterval->physReg == leftRegNum && rightInterval->physReg == rightRegNum);
         leftInterval->physReg                  = rightRegNum;
         rightInterval->physReg                 = leftRegNum;
+        leftInterval->assignedReg              = &physRegs[rightRegNum];
+        rightInterval->assignedReg             = &physRegs[leftRegNum];
         physRegs[rightRegNum].assignedInterval = leftInterval;
         physRegs[leftRegNum].assignedInterval  = rightInterval;
         if (VERBOSE)
index 89abdff..14eba8c 100644 (file)
@@ -481,6 +481,13 @@ void Compiler::unwindSetFrameRegWindows(regNumber reg, unsigned offset)
 }
 
 #ifdef UNIX_AMD64_ABI
+//------------------------------------------------------------------------
+// Compiler::unwindSetFrameRegCFI: Record a cfi info for a frame register set.
+//
+// Arguments:
+//    reg    - The register being set as the frame register.
+//    offset - The offset from the current stack pointer that the frame pointer will point at.
+//
 void Compiler::unwindSetFrameRegCFI(regNumber reg, unsigned offset)
 {
     assert(compGeneratingProlog);
@@ -492,7 +499,13 @@ void Compiler::unwindSetFrameRegCFI(regNumber reg, unsigned offset)
     createCfiCode(func, cbProlog, CFI_DEF_CFA_REGISTER, mapRegNumToDwarfReg(reg));
     if (offset != 0)
     {
-        createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, offset);
+        // before: cfa = rsp + old_cfa_offset;
+        //         rbp = rsp + offset;
+        // after: cfa should be based on rbp, but points to the old address:
+        //         rsp + old_cfa_offset == rbp + old_cfa_offset + adjust;
+        // adjust = -offset;
+        int adjust = -(int)offset;
+        createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, adjust);
     }
 }
 #endif // UNIX_AMD64_ABI
index 6b62cb7..3a45039 100644 (file)
@@ -657,7 +657,7 @@ void dumpILRange(const BYTE* const codeAddr, unsigned codeSize) // in bytes
     for (IL_OFFSET offs = 0; offs < codeSize;)
     {
         char prefix[100];
-        sprintf(prefix, "IL_%04x ", offs);
+        sprintf_s(prefix, _countof(prefix), "IL_%04x ", offs);
         unsigned codeBytesDumped = dumpSingleInstr(codeAddr, offs, prefix);
         offs += codeBytesDumped;
     }
index fee3e46..fc6e13a 100644 (file)
@@ -4,9 +4,6 @@
 #define ENABLE
 #define MINBUFFERS
 using System;
-#if !FEATURE_CORECLR
-using System.Diagnostics.Tracing;
-#endif
 using System.Runtime.InteropServices;
 using System.Runtime.ConstrainedExecution;
 using System.Collections.Generic;
@@ -45,12 +42,6 @@ namespace System
         /// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData)
         /// This is only used in mscorlib.
         /// </summary>
-#if (ENABLE || MINBUFFERS)
-#pragma warning disable 618
-        [EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
-#pragma warning restore 618
-        [System.Security.SecuritySafeCritical]
-#endif
         internal PinnableBufferCache(string cacheName, Func<object> factory)
         {
             m_NotGen2 = new List<object>(DefaultNumberOfBuffers);
@@ -103,7 +94,6 @@ namespace System
         /// <summary>
         /// Get a object from the buffer manager.  If no buffers exist, allocate a new one.
         /// </summary>
-        [System.Security.SecuritySafeCritical]
         internal object Allocate()
         {
 #if ENABLE
@@ -149,7 +139,6 @@ namespace System
         /// <summary>
         /// Return a buffer back to the buffer manager.
         /// </summary>
-        [System.Security.SecuritySafeCritical]
         internal void Free(object buffer)
         {
 #if ENABLE
@@ -188,7 +177,6 @@ namespace System
         /// Called when we don't have any buffers in our free list to give out.    
         /// </summary>
         /// <returns></returns>
-        [System.Security.SecuritySafeCritical]
         private void Restock(out object returnBuffer)
         {
             lock (this)
@@ -241,7 +229,6 @@ namespace System
         /// <summary>
         /// See if we can promote the buffers to the free list.  Returns true if sucessful. 
         /// </summary>
-        [System.Security.SecuritySafeCritical]
         private bool AgePendingBuffers()
         {
             if (m_gen1CountAtLastRestock < GC.CollectionCount(GC.MaxGeneration - 1))
@@ -317,7 +304,6 @@ namespace System
         /// otherwise, we root the cache to the Gen2GcCallback object, and leak the cache even when
         /// the application no longer needs it.
         /// </summary>
-        [System.Security.SecuritySafeCritical]
         private static bool Gen2GcCallbackFunc(object targetObj)
         {
             return ((PinnableBufferCache)(targetObj)).TrimFreeListIfNeeded();
@@ -328,7 +314,6 @@ namespace System
         /// NOTE: DO NOT CALL THIS DIRECTLY FROM THE GEN2GCCALLBACK.  INSTEAD CALL IT VIA A STATIC FUNCTION (SEE ABOVE).
         /// If you register a non-static function as a callback, then this object will be leaked.
         /// </summary>
-        [System.Security.SecuritySafeCritical]
         private bool TrimFreeListIfNeeded()
         {
             int curMSec = Environment.TickCount;
@@ -481,7 +466,6 @@ namespace System
     /// </summary>
     internal sealed class Gen2GcCallback : CriticalFinalizerObject
     {
-        [System.Security.SecuritySafeCritical]
         public Gen2GcCallback()
             : base()
         {
@@ -506,14 +490,12 @@ namespace System
         private Func<object, bool> m_callback;
         private GCHandle m_weakTargetObj;
 
-        [System.Security.SecuritySafeCritical]
         private void Setup(Func<object, bool> callback, object targetObj)
         {
             m_callback = callback;
             m_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak);
         }
 
-        [System.Security.SecuritySafeCritical]
         ~Gen2GcCallback()
         {
             // Check to see if the target object is still alive.
@@ -549,8 +531,6 @@ namespace System
         #endregion
     }
 
-
-#if FEATURE_CORECLR
     internal sealed class PinnableBufferCacheEventSource
     {
         public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource();
@@ -581,86 +561,9 @@ namespace System
             return 0;
         }
 
-        [System.Security.SecuritySafeCritical]
         static internal unsafe long AddressOfObject(byte[] array)
         {
             return 0;
         }
     }
-#else
-    /// <summary>
-    /// PinnableBufferCacheEventSource is a private eventSource that we are using to
-    /// debug and monitor the effectiveness of PinnableBufferCache
-    /// </summary>
-#if PINNABLEBUFFERCACHE_MSCORLIB
-    [EventSource(Name = "Microsoft-DotNETRuntime-PinnableBufferCache")]
-#else
-    [EventSource(Name = "Microsoft-DotNETRuntime-PinnableBufferCache-System")]
-#endif
-    internal sealed class PinnableBufferCacheEventSource : EventSource
-    {
-        public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource();
-
-        [Event(1, Level = EventLevel.Verbose)]
-        public void DebugMessage(string message) { if (IsEnabled()) WriteEvent(1, message); }
-        [Event(2, Level = EventLevel.Verbose)]
-        public void DebugMessage1(string message, long value) { if (IsEnabled()) WriteEvent(2, message, value); }
-        [Event(3, Level = EventLevel.Verbose)]
-        public void DebugMessage2(string message, long value1, long value2) { if (IsEnabled()) WriteEvent(3, message, value1, value2); }
-        [Event(18, Level = EventLevel.Verbose)]
-        public void DebugMessage3(string message, long value1, long value2, long value3) { if (IsEnabled()) WriteEvent(18, message, value1, value2, value3); }
-
-        [Event(4)]
-        public void Create(string cacheName) { if (IsEnabled()) WriteEvent(4, cacheName); }
-
-        [Event(5, Level = EventLevel.Verbose)]
-        public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { if (IsEnabled()) WriteEvent(5, cacheName, objectId, objectHash, objectGen, freeCountAfter); }
-        [Event(6)]
-        public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { if (IsEnabled()) WriteEvent(6, cacheName, notGen2CountAfter); }
-        [Event(7)]
-        public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { if (IsEnabled()) WriteEvent(7, cacheName, totalBuffsBefore, objectCount); }
-        [Event(8)]
-        public void AllocateBufferAged(string cacheName, int agedCount) { if (IsEnabled()) WriteEvent(8, cacheName, agedCount); }
-        [Event(9)]
-        public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(9, cacheName, notGen2CountBefore); }
-
-        [Event(10, Level = EventLevel.Verbose)]
-        public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { if (IsEnabled()) WriteEvent(10, cacheName, objectId, objectHash, freeCountBefore); }
-        [Event(11)]
-        public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(11, cacheName, notGen2CountBefore); }
-
-        [Event(13)]
-        public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { if (IsEnabled()) WriteEvent(13, cacheName, totalBuffs, neededMoreThanFreeList, deltaMSec); }
-        [Event(14)]
-        public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { if (IsEnabled()) WriteEvent(14, cacheName, totalBuffs, freeListCount, toBeFreed); }
-        [Event(15)]
-        public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { if (IsEnabled()) WriteEvent(15, cacheName, totalBuffs, freeListCount, numTrimTrial); }
-        [Event(16)]
-        public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { if (IsEnabled()) WriteEvent(16, cacheName, totalBuffs, freeListCount); }
-        [Event(17)]
-        public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(17, cacheName, totalBuffs, freeListCount, notGen2CountBefore); }
-        [Event(20)]
-        public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { if (IsEnabled()) WriteEvent(20, cacheName, promotedToFreeListCount, heldBackCount); }
-        [Event(21)]
-        public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { if (IsEnabled()) WriteEvent(21, cacheName, freeListCount, gen0BuffersInFreeList); }
-
-
-        static internal ulong AddressOf(object obj)
-        {
-            var asByteArray = obj as byte[];
-            if (asByteArray != null)
-                return (ulong)AddressOfByteArray(asByteArray);
-            return 0;
-        }
-
-        [System.Security.SecuritySafeCritical]
-        static internal unsafe long AddressOfByteArray(byte[] array)
-        {
-            if (array == null)
-                return 0;
-            fixed (byte* ptr = array)
-                return (long)(ptr - 2 * sizeof(void*));
-        }
-    }
-#endif
 }
index d1849ac..edfc66d 100644 (file)
@@ -18,7 +18,6 @@ internal partial class Interop
         /// "lpt1:", etc.  Use this to avoid security problems, like allowing a web client asking a server
         /// for "http://server/com1.aspx" and then causing a worker process to hang.
         /// </summary>
-        [System.Security.SecurityCritical]  // auto-generated
         internal static SafeFileHandle SafeCreateFile(
             String lpFileName,
             int dwDesiredAccess,
index 375acc6..e7e4f05 100644 (file)
@@ -10,7 +10,6 @@ internal partial class Interop
 {
     internal partial class mincore
     {
-        [System.Security.SecurityCritical]  // auto-generated
         internal static SafeFileHandle UnsafeCreateFile(
             string lpFileName,
             int dwDesiredAccess,
index 6dc6072..7d4dd44 100644 (file)
@@ -10,7 +10,6 @@ using Microsoft.Win32;
 
 namespace Microsoft.Win32.SafeHandles
 {
-    [System.Security.SecurityCritical]  // auto-generated_required
     public sealed class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
         private bool? _isAsync;
@@ -42,7 +41,6 @@ namespace Microsoft.Win32.SafeHandles
 
         internal ThreadPoolBoundHandle ThreadPoolBinding { get; set; }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return Interop.mincore.CloseHandle(handle);
index f71556c..78e9f00 100644 (file)
@@ -2,9 +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;
-using System.Runtime.CompilerServices;
-using System.Globalization;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.Serialization;
 
@@ -212,7 +210,7 @@ namespace System.Globalization
                 // The following code assumes that the current era value can not be -1.
                 if (_currentEraValue == -1)
                 {
-                    Contract.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
+                    Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
                     _currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
                 }
                 return (_currentEraValue);
@@ -527,7 +525,7 @@ namespace System.Globalization
             // this value can be less than 0.  It's fine since we are making it positive again in calculating offset.
             int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
             int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
-            Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
+            Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
             return ((dayOfYear + offset) / 7 + 1);
         }
 
index 6c6a18e..270d62f 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Security;
@@ -200,7 +201,7 @@ namespace System.Globalization
                         break;
                     default:
                         const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
-                        Contract.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
+                        Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
                             string.Format(CultureInfo.InvariantCulture,
                                 "Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.", 
                                 input[index]));
index 2dbd1b8..d22bd67 100644 (file)
@@ -2,11 +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;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Diagnostics.Contracts;
-using System.Collections.Generic;
+using System.Diagnostics;
 
 namespace System.Globalization
 {
@@ -108,7 +104,7 @@ namespace System.Globalization
 
             if (!LoadCalendarDataFromSystem(localeName, calendarId))
             {
-                Contract.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
+                Debug.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
 
                 // Something failed, try invariant for missing parts
                 // This is really not good, but we don't want the callers to crash.
index ba7601b..149e63c 100644 (file)
@@ -2,8 +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;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
 
 namespace System.Globalization
 {
@@ -126,7 +125,7 @@ namespace System.Globalization
             return longitude;
         }
 
-        static public double AsDayFraction(double longitude)
+        public static double AsDayFraction(double longitude)
         {
             return longitude / FullCircleOfArc;
         }
@@ -153,7 +152,7 @@ namespace System.Globalization
         // the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges
         private static double DefaultEphemerisCorrection(int gregorianYear)
         {
-            Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
+            Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
             long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
             double daysSinceStartOf1810 = january1stOfYear - StartOf1810;
             double x = TwelveHours + daysSinceStartOf1810;
@@ -162,34 +161,34 @@ namespace System.Globalization
 
         private static double EphemerisCorrection1988to2019(int gregorianYear)
         {
-            Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
+            Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
             return (double)(gregorianYear - 1933) / SecondsPerDay;
         }
 
         private static double EphemerisCorrection1900to1987(int gregorianYear)
         {
-            Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
+            Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
             double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
             return PolynomialSum(s_coefficients1900to1987, centuriesFrom1900);
         }
 
         private static double EphemerisCorrection1800to1899(int gregorianYear)
         {
-            Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
+            Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
             double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
             return PolynomialSum(s_coefficients1800to1899, centuriesFrom1900);
         }
 
         private static double EphemerisCorrection1700to1799(int gregorianYear)
         {
-            Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
+            Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
             double yearsSince1700 = gregorianYear - 1700;
             return PolynomialSum(s_coefficients1700to1799, yearsSince1700) / SecondsPerDay;
         }
 
         private static double EphemerisCorrection1620to1699(int gregorianYear)
         {
-            Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
+            Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
             double yearsSince1600 = gregorianYear - 1600;
             return PolynomialSum(s_coefficients1620to1699, yearsSince1600) / SecondsPerDay;
         }
@@ -216,11 +215,11 @@ namespace System.Globalization
                 }
             }
 
-            Contract.Assert(false, "Not expected to come here");
+            Debug.Assert(false, "Not expected to come here");
             return DefaultEphemerisCorrection(year);
         }
 
-        static public double JulianCenturies(double moment)
+        public static double JulianCenturies(double moment)
         {
             double dynamicalMoment = moment + EphemerisCorrection(moment);
             return (dynamicalMoment - Noon2000Jan01) / DaysInUniformLengthCentury;
@@ -274,7 +273,7 @@ namespace System.Globalization
         }
 
         // midday
-        static public double Midday(double date, double longitude)
+        public static double Midday(double date, double longitude)
         {
             return AsLocalTime(date + TwelveHours, longitude) - AsDayFraction(longitude);
         }
@@ -285,7 +284,7 @@ namespace System.Globalization
         }
 
         // midday-in-tehran
-        static public double MiddayAtPersianObservationSite(double date)
+        public static double MiddayAtPersianObservationSite(double date)
         {
             return Midday(date, InitLongitude(52.5)); // 52.5 degrees east - longitude of UTC+3:30 which defines Iranian Standard Time
         }
@@ -362,7 +361,7 @@ namespace System.Globalization
             return (-0.004778 * SinOfDegree(a)) - (0.0003667 * SinOfDegree(b));
         }
 
-        static public double Compute(double time)
+        public static double Compute(double time)
         {
             double julianCenturies = JulianCenturies(time);
             double lambda = 282.7771834
@@ -373,7 +372,7 @@ namespace System.Globalization
             return InitLongitude(longitude);
         }
 
-        static public double AsSeason(double longitude)
+        public static double AsSeason(double longitude)
         {
             return (longitude < 0) ? (longitude + FullCircleOfArc) : longitude;
         }
@@ -405,7 +404,7 @@ namespace System.Globalization
                     break;
                 }
             }
-            Contract.Assert(day != upperBoundNewYearDay);
+            Debug.Assert(day != upperBoundNewYearDay);
 
             return day - 1;
         }
index d3a591e..dc38ca4 100644 (file)
 //
 ////////////////////////////////////////////////////////////////////////////
 
-using System;
-using System.Threading;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Reflection;
-using System.Security;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Globalization
@@ -59,8 +54,8 @@ namespace System.Globalization
 
         internal static int InternalConvertToUtf32(String s, int index)
         {
-            Contract.Assert(s != null, "s != null");
-            Contract.Assert(index >= 0 && index < s.Length, "index < s.Length");
+            Debug.Assert(s != null, "s != null");
+            Debug.Assert(index >= 0 && index < s.Length, "index < s.Length");
             if (index < s.Length - 1)
             {
                 int temp1 = (int)s[index] - HIGH_SURROGATE_START;
@@ -100,9 +95,9 @@ namespace System.Globalization
 
         internal static int InternalConvertToUtf32(String s, int index, out int charLength)
         {
-            Contract.Assert(s != null, "s != null");
-            Contract.Assert(s.Length > 0, "s.Length > 0");
-            Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+            Debug.Assert(s != null, "s != null");
+            Debug.Assert(s.Length > 0, "s.Length > 0");
+            Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
             charLength = 1;
             if (index < s.Length - 1)
             {
@@ -131,8 +126,8 @@ namespace System.Globalization
 
         internal static bool IsWhiteSpace(String s, int index)
         {
-            Contract.Assert(s != null, "s!=null");
-            Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+            Debug.Assert(s != null, "s!=null");
+            Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
 
             UnicodeCategory uc = GetUnicodeCategory(s, index);
             // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
@@ -170,9 +165,9 @@ namespace System.Globalization
         //
         // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
         //
-        internal unsafe static double InternalGetNumericValue(int ch)
+        internal static unsafe double InternalGetNumericValue(int ch)
         {
-            Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+            Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
             // Get the level 2 item from the highest 12 bit (8 - 19) of ch.
             ushort index = s_pNumericLevel1Index[ch >> 8];
             // Get the level 2 WORD offset from the 4 - 7 bit of ch.  This provides the base offset of the level 3 table.
@@ -191,9 +186,9 @@ namespace System.Globalization
             }
         }
 
-        internal unsafe static ushort InternalGetDigitValues(int ch)
+        internal static unsafe ushort InternalGetDigitValues(int ch)
         {
-            Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+            Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
             // Get the level 2 item from the highest 12 bit (8 - 19) of ch.
             ushort index = s_pNumericLevel1Index[ch >> 8];
             // Get the level 2 WORD offset from the 4 - 7 bit of ch.  This provides the base offset of the level 3 table.
@@ -302,7 +297,7 @@ namespace System.Globalization
             return InternalGetUnicodeCategory(s, index);
         }
 
-        internal unsafe static UnicodeCategory InternalGetUnicodeCategory(int ch)
+        internal static unsafe UnicodeCategory InternalGetUnicodeCategory(int ch)
         {
             return ((UnicodeCategory)InternalGetCategoryValue(ch, UNICODE_CATEGORY_OFFSET));
         }
@@ -322,9 +317,9 @@ namespace System.Globalization
         //
         ////////////////////////////////////////////////////////////////////////
 
-        internal unsafe static byte InternalGetCategoryValue(int ch, int offset)
+        internal static unsafe byte InternalGetCategoryValue(int ch, int offset)
         {
-            Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+            Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
             // Get the level 2 item from the highest 12 bit (8 - 19) of ch.
             ushort index = s_pCategoryLevel1Index[ch >> 8];
             // Get the level 2 WORD offset from the 4 - 7 bit of ch.  This provides the base offset of the level 3 table.
@@ -341,7 +336,7 @@ namespace System.Globalization
                 // Make sure that OtherNotAssigned is the last category in UnicodeCategory.
                 // If that changes, change the following assertion as well.
                 //
-                //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
+                //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
                 return (uc);
             }
         }
@@ -361,8 +356,8 @@ namespace System.Globalization
 
         internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index)
         {
-            Contract.Assert(value != null, "value can not be null");
-            Contract.Assert(index < value.Length, "index < value.Length");
+            Debug.Assert(value != null, "value can not be null");
+            Debug.Assert(index < value.Length, "index < value.Length");
 
             return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
         }
@@ -376,16 +371,16 @@ namespace System.Globalization
 
         internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength)
         {
-            Contract.Assert(str != null, "str can not be null");
-            Contract.Assert(str.Length > 0, "str.Length > 0"); ;
-            Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
+            Debug.Assert(str != null, "str can not be null");
+            Debug.Assert(str.Length > 0, "str.Length > 0"); ;
+            Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
 
             return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
         }
 
         internal static bool IsCombiningCategory(UnicodeCategory uc)
         {
-            Contract.Assert(uc >= 0, "uc >= 0");
+            Debug.Assert(uc >= 0, "uc >= 0");
             return (
                 uc == UnicodeCategory.NonSpacingMark ||
                 uc == UnicodeCategory.SpacingCombiningMark ||
index 01483b2..21c3c9f 100644 (file)
@@ -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.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
@@ -41,8 +42,8 @@ namespace System.Globalization
 
         internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
         {
-            Contract.Assert(source != null);
-            Contract.Assert(value != null);
+            Debug.Assert(source != null);
+            Debug.Assert(value != null);
 
             if (value.Length == 0)
             {
@@ -85,8 +86,8 @@ namespace System.Globalization
 
         internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
         {
-            Contract.Assert(source != null);
-            Contract.Assert(value != null);
+            Debug.Assert(source != null);
+            Debug.Assert(value != null);
 
             if (value.Length == 0)
             {
@@ -132,8 +133,8 @@ namespace System.Globalization
 
         private int GetHashCodeOfStringCore(string source, CompareOptions options)
         {
-            Contract.Assert(source != null);
-            Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+            Debug.Assert(source != null);
+            Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
 
             return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
         }
@@ -145,9 +146,9 @@ namespace System.Globalization
 
         private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
         {
-            Contract.Assert(string1 != null);
-            Contract.Assert(string2 != null);
-            Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+            Debug.Assert(string1 != null);
+            Debug.Assert(string2 != null);
+            Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
 
             fixed (char* pString1 = string1)
             {
@@ -160,9 +161,9 @@ namespace System.Globalization
 
         private unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
         {
-            Contract.Assert(!string.IsNullOrEmpty(source));
-            Contract.Assert(target != null);
-            Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+            Debug.Assert(!string.IsNullOrEmpty(source));
+            Debug.Assert(target != null);
+            Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
 
             if (target.Length == 0)
             {
@@ -189,9 +190,9 @@ namespace System.Globalization
 
         private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
         {
-            Contract.Assert(!string.IsNullOrEmpty(source));
-            Contract.Assert(target != null);
-            Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+            Debug.Assert(!string.IsNullOrEmpty(source));
+            Debug.Assert(target != null);
+            Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
 
             if (target.Length == 0)
             {
@@ -222,9 +223,9 @@ namespace System.Globalization
 
         private bool StartsWith(string source, string prefix, CompareOptions options)
         {
-            Contract.Assert(!string.IsNullOrEmpty(source));
-            Contract.Assert(!string.IsNullOrEmpty(prefix));
-            Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+            Debug.Assert(!string.IsNullOrEmpty(source));
+            Debug.Assert(!string.IsNullOrEmpty(prefix));
+            Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
 
             if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort())
             {
@@ -236,9 +237,9 @@ namespace System.Globalization
 
         private bool EndsWith(string source, string suffix, CompareOptions options)
         {
-            Contract.Assert(!string.IsNullOrEmpty(source));
-            Contract.Assert(!string.IsNullOrEmpty(suffix));
-            Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+            Debug.Assert(!string.IsNullOrEmpty(source));
+            Debug.Assert(!string.IsNullOrEmpty(suffix));
+            Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
 
             if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort())
             {
@@ -320,8 +321,8 @@ namespace System.Globalization
 
         internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
         {
-            Contract.Assert(source != null);
-            Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+            Debug.Assert(source != null);
+            Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
 
             if (source.Length == 0)
             {
@@ -378,7 +379,7 @@ namespace System.Globalization
 
             int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0);
 
-            Contract.Assert(bytesWritten == byteLen);
+            Debug.Assert(bytesWritten == byteLen);
 
             return buffer;
         }
index 9676dcc..4ebaf9c 100644 (file)
@@ -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.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Globalization
@@ -53,24 +54,24 @@ namespace System.Globalization
 
         internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
         {
-            Contract.Assert(source != null);
-            Contract.Assert(value != null);
+            Debug.Assert(source != null);
+            Debug.Assert(value != null);
 
             return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
         }
 
         internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
         {
-            Contract.Assert(source != null);
-            Contract.Assert(value != null);
+            Debug.Assert(source != null);
+            Debug.Assert(value != null);
 
             return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
         }
 
         private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
         {
-            Contract.Assert(source != null);
-            Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+            Debug.Assert(source != null);
+            Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
 
             if (source.Length == 0)
             {
@@ -102,9 +103,9 @@ namespace System.Globalization
 
         private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
         {
-            Contract.Assert(string1 != null);
-            Contract.Assert(string2 != null);
-            Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+            Debug.Assert(string1 != null);
+            Debug.Assert(string2 != null);
+            Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
 
             string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
 
@@ -167,9 +168,9 @@ namespace System.Globalization
 
         private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
         {
-            Contract.Assert(!string.IsNullOrEmpty(source));
-            Contract.Assert(target != null);
-            Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+            Debug.Assert(!string.IsNullOrEmpty(source));
+            Debug.Assert(target != null);
+            Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
 
             // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
             // and add a precondition that target is not empty. 
@@ -200,9 +201,9 @@ namespace System.Globalization
 
         private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
         {
-            Contract.Assert(!string.IsNullOrEmpty(source));
-            Contract.Assert(target != null);
-            Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+            Debug.Assert(!string.IsNullOrEmpty(source));
+            Debug.Assert(target != null);
+            Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
 
             // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
             // and add a precondition that target is not empty. 
@@ -234,9 +235,9 @@ namespace System.Globalization
 
         private bool StartsWith(string source, string prefix, CompareOptions options)
         {
-            Contract.Assert(!string.IsNullOrEmpty(source));
-            Contract.Assert(!string.IsNullOrEmpty(prefix));
-            Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+            Debug.Assert(!string.IsNullOrEmpty(source));
+            Debug.Assert(!string.IsNullOrEmpty(prefix));
+            Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
 
             return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options),
                                                    source,
@@ -249,9 +250,9 @@ namespace System.Globalization
 
         private bool EndsWith(string source, string suffix, CompareOptions options)
         {
-            Contract.Assert(!string.IsNullOrEmpty(source));
-            Contract.Assert(!string.IsNullOrEmpty(suffix));
-            Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+            Debug.Assert(!string.IsNullOrEmpty(source));
+            Debug.Assert(!string.IsNullOrEmpty(suffix));
+            Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
 
             return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options),
                                                    source,
@@ -280,14 +281,10 @@ namespace System.Globalization
 
             int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex;
 
-#if !TEST_CODEGEN_OPTIMIZATION
             fixed (char* pSource = source, spTarget = target)
             {
                 char* spSubSource = pSource + sourceStartIndex;
-#else
-                String.StringPointer spSubSource = source.GetStringPointer(sourceStartIndex);
-                String.StringPointer spTarget = target.GetStringPointer();
-#endif
+
                 if (findLastIndex)
                 {
                     int startPattern = (sourceCount - 1) - targetCount + 1;
@@ -347,11 +344,9 @@ namespace System.Globalization
                         retValue += startIndex;
                     }
                 }
-#if !TEST_CODEGEN_OPTIMIZATION
             }
 
             return retValue;
-#endif // TEST_CODEGEN_OPTIMIZATION
         }
 
         private unsafe SortKey CreateSortKey(String source, CompareOptions options)
@@ -361,13 +356,13 @@ namespace System.Globalization
 
             if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
             {
-                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
+                throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
             }
 
             throw new NotImplementedException();
         }
 
-        private unsafe static bool IsSortable(char *text, int length)
+        private static unsafe bool IsSortable(char *text, int length)
         {
             // CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
             // return (InternalIsSortable(c.m_dataHandle, c.m_handleOrigin, c.m_sortName, text, text.Length));
@@ -401,7 +396,7 @@ namespace System.Globalization
             // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
             if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
 
-            Contract.Assert(((options & ~(CompareOptions.IgnoreCase |
+            Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
                                           CompareOptions.IgnoreKanaType |
                                           CompareOptions.IgnoreNonSpace |
                                           CompareOptions.IgnoreSymbols |
@@ -411,7 +406,7 @@ namespace System.Globalization
 
             return nativeCompareFlags;
         }
-        
+
         private SortVersion GetSortVersion()
         {
             throw new NotImplementedException();
index a82f705..64dbfe8 100644 (file)
 //
 ////////////////////////////////////////////////////////////////////////////
 
-using System;
 using System.Reflection;
-using System.Collections;
-using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
-using System.Threading;
 
 namespace System.Globalization
 {
@@ -173,13 +168,13 @@ namespace System.Globalization
             return CultureInfo.GetCultureInfo(name).CompareInfo;
         }
 
-        public unsafe static bool IsSortable(char ch)
+        public static unsafe bool IsSortable(char ch)
         {
             char *pChar = &ch;
             return IsSortable(pChar, 1);
         }
 
-        public unsafe static bool IsSortable(string text)
+        public static unsafe bool IsSortable(string text)
         {
             if (text == null) 
             {
@@ -245,7 +240,7 @@ namespace System.Globalization
         {
             get
             {
-                Contract.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
+                Debug.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
                 if (_name == "zh-CHT" || _name == "zh-CHS")
                 {
                     return _name;
@@ -428,8 +423,8 @@ namespace System.Globalization
         //
         internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
         {
-            Contract.Assert(indexA + lengthA <= strA.Length);
-            Contract.Assert(indexB + lengthB <= strB.Length);
+            Debug.Assert(indexA + lengthA <= strA.Length);
+            Debug.Assert(indexB + lengthB <= strB.Length);
 
             int length = Math.Min(lengthA, lengthB);
             int range = length;
index 5742ff8..7f2f17d 100644 (file)
@@ -4,6 +4,7 @@
 
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Security;
@@ -26,7 +27,7 @@ namespace System.Globalization
         [SecuritySafeCritical]
         private unsafe bool InitCultureData()
         {
-            Contract.Assert(_sRealName != null);
+            Debug.Assert(_sRealName != null);
             
             string alternateSortName = string.Empty;
             string realNameBuffer = _sRealName;
@@ -122,7 +123,7 @@ namespace System.Globalization
         
         private string GetLocaleInfo(LocaleStringData type)
         {
-            Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
+            Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
             return GetLocaleInfo(_sWindowsName, type);
         }
 
@@ -131,7 +132,7 @@ namespace System.Globalization
         [SecuritySafeCritical]
         private string GetLocaleInfo(string localeName, LocaleStringData type)
         {
-            Contract.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
+            Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
 
             switch (type)
             {
@@ -148,7 +149,7 @@ namespace System.Globalization
             {
                 // Failed, just use empty string
                 StringBuilderCache.Release(sb);
-                Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
+                Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
                 return String.Empty;
             }
             return StringBuilderCache.GetStringAndRelease(sb);
@@ -157,7 +158,7 @@ namespace System.Globalization
         [SecuritySafeCritical]
         private int GetLocaleInfo(LocaleNumberData type)
         {
-            Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
+            Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
 
             switch (type)
             {
@@ -172,7 +173,7 @@ namespace System.Globalization
             if (!result)
             {
                 // Failed, just use 0
-                Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
+                Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
             }
 
             return value;
@@ -181,14 +182,14 @@ namespace System.Globalization
         [SecuritySafeCritical]
         private int[] GetLocaleInfo(LocaleGroupingData type)
         {
-            Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
+            Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
 
             int primaryGroupingSize = 0;
             int secondaryGroupingSize = 0;
             bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
             if (!result)
             {
-                Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
+                Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
             }
 
             if (secondaryGroupingSize == 0)
@@ -207,7 +208,7 @@ namespace System.Globalization
         [SecuritySafeCritical]
         private string GetTimeFormatString(bool shortFormat)
         {
-            Contract.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
+            Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
 
             StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
 
@@ -216,7 +217,7 @@ namespace System.Globalization
             {
                 // Failed, just use empty string
                 StringBuilderCache.Release(sb);
-                Contract.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
+                Debug.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
                 return String.Empty;
             }
 
index 481e1a1..d1c99da 100644 (file)
@@ -3,10 +3,13 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Collections.Generic;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
 using System.Runtime.InteropServices;
 using System.Text;
+
+#if ENABLE_WINRT
 using Internal.Runtime.Augments;
+#endif
 
 namespace System.Globalization
 {
@@ -158,7 +161,7 @@ namespace System.Globalization
 
         private string GetLocaleInfo(LocaleStringData type)
         {
-            Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already");
+            Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already");
             return GetLocaleInfo(_sWindowsName, type);
         }
 
@@ -183,7 +186,7 @@ namespace System.Globalization
 
             // Ask OS for data, note that we presume it returns success, so we have to know that
             // sWindowsName is valid before calling.
-            Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
+            Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
             int result = Interop.mincore.GetLocaleInfoExInt(_sWindowsName, lctype);
 
             return result;
@@ -203,7 +206,7 @@ namespace System.Globalization
 
         private int GetFirstDayOfWeek()
         {
-            Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
+            Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
 
             const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
 
@@ -216,7 +219,7 @@ namespace System.Globalization
         private String[] GetTimeFormats()
         {
             // Note that this gets overrides for us all the time
-            Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already");
+            Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already");
             String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride));
 
             return result;
@@ -225,7 +228,7 @@ namespace System.Globalization
         private String[] GetShortTimeFormats()
         {
             // Note that this gets overrides for us all the time
-            Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already");
+            Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already");
             String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, TIME_NOSECONDS, UseUserOverride));
 
             return result;
@@ -235,7 +238,7 @@ namespace System.Globalization
         // region name match the requested region name
         private static CultureData GetCultureDataFromRegionName(String regionName)
         {
-            Contract.Assert(regionName != null);
+            Debug.Assert(regionName != null);
 
             const uint LOCALE_SUPPLEMENTAL = 0x00000002;
             const uint LOCALE_SPECIFICDATA = 0x00000020;
@@ -264,26 +267,64 @@ namespace System.Globalization
             return null;
         }
 
-        private static string GetLanguageDisplayName(string cultureName)
+        private string GetLanguageDisplayName(string cultureName)
         {
+#if ENABLE_WINRT
             return WinRTInterop.Callbacks.GetLanguageDisplayName(cultureName);
+#else
+            // Usually the UI culture shouldn't be different than what we got from WinRT except
+            // if DefaultThreadCurrentUICulture was set
+            CultureInfo ci;
+
+            if (CultureInfo.DefaultThreadCurrentUICulture != null &&
+                ((ci = GetUserDefaultCulture()) != null) &&
+                !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name))
+            {
+                return SNATIVEDISPLAYNAME;
+            }
+            else
+            {
+                return GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
+            }
+#endif // ENABLE_WINRT
         }
 
-        private static string GetRegionDisplayName(string isoCountryCode)
+        private string GetRegionDisplayName(string isoCountryCode)
         {
+#if ENABLE_WINRT
             return WinRTInterop.Callbacks.GetRegionDisplayName(isoCountryCode);
+#else
+            // Usually the UI culture shouldn't be different than what we got from WinRT except
+            // if DefaultThreadCurrentUICulture was set
+            CultureInfo ci;
+
+            if (CultureInfo.DefaultThreadCurrentUICulture != null &&
+                ((ci = GetUserDefaultCulture()) != null) &&
+                !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name))
+            {
+                return SNATIVECOUNTRY;
+            }
+            else
+            {
+                return GetLocaleInfo(LocaleStringData.LocalizedCountryName);
+            }
+#endif // ENABLE_WINRT
         }
 
         private static CultureInfo GetUserDefaultCulture()
         {
+#if ENABLE_WINRT
             return (CultureInfo)WinRTInterop.Callbacks.GetUserDefaultCulture();
+#else
+            return CultureInfo.GetUserDefaultCulture();
+#endif // ENABLE_WINRT
         }
 
         // PAL methods end here.
 
         private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride)
         {
-            Contract.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
+            Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
 
             // Fix lctype if we don't want overrides
             if (!useUserOveride)
@@ -557,50 +598,50 @@ namespace System.Globalization
 
             return null;
         }
-        
-        private static int LocaleNameToLCID(string cultureName)
+
+        private int LocaleNameToLCID(string cultureName)
         {
-            throw new NotImplementedException();
+            return GetLocaleInfo(LocaleNumberData.LanguageId);
         }
-        
+
         private static string LCIDToLocaleName(int culture)
         {
             throw new NotImplementedException();
         }
-        
-        private static int GetAnsiCodePage(string cultureName)
+
+        private int GetAnsiCodePage(string cultureName)
         {
-            throw new NotImplementedException();
+            return GetLocaleInfo(LocaleNumberData.AnsiCodePage);
         }
 
-        private static int GetOemCodePage(string cultureName)
+        private int GetOemCodePage(string cultureName)
         {
-            throw new NotImplementedException();
+            return GetLocaleInfo(LocaleNumberData.OemCodePage);
         }
 
-        private static int GetMacCodePage(string cultureName)
+        private int GetMacCodePage(string cultureName)
         {
-            throw new NotImplementedException();
+            return GetLocaleInfo(LocaleNumberData.MacCodePage);
         }
 
-        private static int GetEbcdicCodePage(string cultureName)
+        private int GetEbcdicCodePage(string cultureName)
         {
-            throw new NotImplementedException();
+            return GetLocaleInfo(LocaleNumberData.EbcdicCodePage);
         }
 
-        private static int GetGeoId(string cultureName)
+        private int GetGeoId(string cultureName)
         {
-            throw new NotImplementedException();
+            return GetLocaleInfo(LocaleNumberData.GeoId);
         }
-        
-        private static int GetDigitSubstitution(string cultureName)
+
+        private int GetDigitSubstitution(string cultureName)
         {
-            throw new NotImplementedException();
+            return GetLocaleInfo(LocaleNumberData.DigitSubstitution);
         }
-        
-        private static string GetThreeLetterWindowsLanguageName(string cultureName)
+
+        private string GetThreeLetterWindowsLanguageName(string cultureName)
         {
-            throw new NotImplementedException();
+            return GetLocaleInfo(cultureName, LocaleStringData.AbbreviatedWindowsLanguageName);
         }
 
         private static CultureInfo[] EnumCultures(CultureTypes types)
@@ -608,22 +649,22 @@ namespace System.Globalization
             throw new NotImplementedException();
         }
 
-        private static string GetConsoleFallbackName(string cultureName)
+        private string GetConsoleFallbackName(string cultureName)
         {
-            throw new NotImplementedException();
+            return GetLocaleInfo(cultureName, LocaleStringData.ConsoleFallbackName);
         }
 
-        private bool IsSupplementalCustomCulture
+        internal bool IsFramework
         {
             get { throw new NotImplementedException(); }
         }
-        
-        private bool IsWin32Installed
+
+        internal bool IsWin32Installed
         {
             get { throw new NotImplementedException(); }
         }
         
-        private bool IsReplacementCulture
+        internal bool IsReplacementCulture
         {
             get { throw new NotImplementedException(); }
         }
index 3bc63c8..c15a77c 100644 (file)
@@ -2,14 +2,10 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
-using System;
-using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Text;
 using System.Threading;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
 
 namespace System.Globalization
 {
@@ -470,21 +466,21 @@ namespace System.Globalization
 
                     // Language
                     invariant._sISO639Language = "iv";                   // ISO 639 Language Name
-                           invariant._sISO639Language2 = "ivl";                  // 3 char ISO 639 lang name 2
+                    invariant._sISO639Language2 = "ivl";                  // 3 char ISO 639 lang name 2
                     invariant._sLocalizedLanguage = "Invariant Language";   // Display name for this Language
                     invariant._sEnglishLanguage = "Invariant Language";   // English name for this language
                     invariant._sNativeLanguage = "Invariant Language";   // Native name of this language
-                           invariant._sAbbrevLang = "IVL";                  // abbreviated language name (Windows Language Name)
-                           invariant._sConsoleFallbackName = "";            // The culture name for the console fallback UI culture
-                           invariant._iInputLanguageHandle = 0x07F;         // input language handle
+                    invariant._sAbbrevLang = "IVL";                  // abbreviated language name (Windows Language Name)
+                    invariant._sConsoleFallbackName = "";            // The culture name for the console fallback UI culture
+                    invariant._iInputLanguageHandle = 0x07F;         // input language handle
 
                     // Region
                     invariant._sRegionName = "IV";                    // (RegionInfo)
                     invariant._sEnglishCountry = "Invariant Country"; // english country name (RegionInfo)
                     invariant._sNativeCountry = "Invariant Country";  // native country name (Windows Only)
                     invariant._sISO3166CountryName = "IV";            // (RegionInfo), ie: US
-                           invariant._sISO3166CountryName2 = "ivc";          // 3 char ISO 3166 country name 2 2(RegionInfo)
-                           invariant._iGeoId = 244;                          // GeoId (Windows Only)
+                    invariant._sISO3166CountryName2 = "ivc";          // 3 char ISO 3166 country name 2 2(RegionInfo)
+                    invariant._iGeoId = 244;                          // GeoId (Windows Only)
 
                     // Numbers
                     invariant._sPositiveSign = "+";                    // positive sign
@@ -708,7 +704,7 @@ namespace System.Globalization
         {
             get
             {
-                Contract.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already");
+                Debug.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already");
                 // since windows doesn't know about zh-CHS and zh-CHT,
                 // we leave sRealName == zh-Hanx but we still need to
                 // pretend that it was zh-CHX.
@@ -926,7 +922,7 @@ namespace System.Globalization
             get
             {
                 // This got populated during the culture initialization
-                Contract.Assert(_sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by culture data initialization already");
+                Debug.Assert(_sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by culture data initialization already");
                 return _sSpecificCulture;
             }
         }
@@ -974,7 +970,6 @@ namespace System.Globalization
             }
         }
 
-
         // Localized name for this language (Windows Only) ie: Inglis
         // This is only valid for Windows 8 and higher neutrals:
         internal String SLOCALIZEDLANGUAGE
@@ -1717,7 +1712,7 @@ namespace System.Globalization
                     // We then have to copy that list to a new array of the right size.
                     // Default calendar should be first
                     CalendarId[] calendars = new CalendarId[23];
-                    Contract.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already");
+                    Debug.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already");
                     int count = CalendarData.GetCalendars(_sWindowsName, _bUseOverrides, calendars);
 
                     // See if we had a calendar to add.
@@ -1789,7 +1784,7 @@ namespace System.Globalization
 
         internal CalendarData GetCalendar(CalendarId calendarId)
         {
-            Contract.Assert(calendarId > 0 && calendarId <= CalendarId.LAST_CALENDAR,
+            Debug.Assert(calendarId > 0 && calendarId <= CalendarId.LAST_CALENDAR,
                 "[CultureData.GetCalendar] Expect calendarId to be in a valid range");
 
             // arrays are 0 based, calendarIds are 1 based
@@ -1808,7 +1803,7 @@ namespace System.Globalization
             // Make sure that calendar has data
             if (calendarData == null)
             {
-                Contract.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already");
+                Debug.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already");
                 calendarData = new CalendarData(_sWindowsName, calendarId, this.UseUserOverride);
                 _calendars[calendarIndex] = calendarData;
             }
@@ -1848,7 +1843,7 @@ namespace System.Globalization
             {
                 if (_iReadingLayout == undef)
                 {
-                    Contract.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already");
+                    Debug.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already");
                     _iReadingLayout = GetLocaleInfo(LocaleNumberData.ReadingLayout);
                 }
 
@@ -1869,7 +1864,7 @@ namespace System.Globalization
             {
                 // Note: Custom cultures might point at another culture's textinfo, however windows knows how
                 // to redirect it to the desired textinfo culture, so this is OK.
-                Contract.Assert(_sRealName != null, "[CultureData.STEXTINFO] Expected _sRealName to be populated by already");
+                Debug.Assert(_sRealName != null, "[CultureData.STEXTINFO] Expected _sRealName to be populated by already");
                 return (_sRealName);
             }
         }
@@ -1879,7 +1874,7 @@ namespace System.Globalization
         {
             get
             {
-                Contract.Assert(_sRealName != null, "[CultureData.SCOMPAREINFO] Expected _sRealName to be populated by already");
+                Debug.Assert(_sRealName != null, "[CultureData.SCOMPAREINFO] Expected _sRealName to be populated by already");
                 return (_sRealName);
             }
         }
@@ -1946,7 +1941,7 @@ namespace System.Globalization
             {
                 if (_iLanguage == 0)
                 {
-                    Contract.Assert(_sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+                    Debug.Assert(_sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
                     _iLanguage = LocaleNameToLCID(_sRealName);
                 }
                 return _iLanguage;
@@ -1989,21 +1984,21 @@ namespace System.Globalization
         // All of our era names
         internal String[] EraNames(CalendarId calendarId)
         {
-            Contract.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
+            Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
 
             return this.GetCalendar(calendarId).saEraNames;
         }
 
         internal String[] AbbrevEraNames(CalendarId calendarId)
         {
-            Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+            Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
 
             return this.GetCalendar(calendarId).saAbbrevEraNames;
         }
 
         internal String[] AbbreviatedEnglishEraNames(CalendarId calendarId)
         {
-            Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+            Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
 
             return this.GetCalendar(calendarId).saAbbrevEnglishEraNames;
         }
@@ -2063,9 +2058,9 @@ namespace System.Globalization
         ////////////////////////////////////////////////////////////////////////////
         private static String UnescapeNlsString(String str, int start, int end)
         {
-            Contract.Requires(str != null);
-            Contract.Requires(start >= 0);
-            Contract.Requires(end >= 0);
+            Debug.Assert(str != null);
+            Debug.Assert(start >= 0);
+            Debug.Assert(end >= 0);
             StringBuilder result = null;
 
             for (int i = start; i < str.Length && i <= end; i++)
@@ -2163,8 +2158,8 @@ namespace System.Globalization
 
         private static int IndexOfTimePart(string format, int startIndex, string timeParts)
         {
-            Contract.Assert(startIndex >= 0, "startIndex cannot be negative");
-            Contract.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
+            Debug.Assert(startIndex >= 0, "startIndex cannot be negative");
+            Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
             bool inQuote = false;
             for (int i = startIndex; i < format.Length; ++i)
             {
@@ -2226,7 +2221,7 @@ namespace System.Globalization
             }
             else
             {
-                Contract.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already");
+                Debug.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already");
                 // String values
                 nfi.positiveSign = GetLocaleInfo(LocaleStringData.PositiveSign);
                 nfi.negativeSign = GetLocaleInfo(LocaleStringData.NegativeSign);
@@ -2251,7 +2246,7 @@ namespace System.Globalization
                 {
                     nfi.nativeDigits[i] = new string(digits[i], 1);
                 }
-                
+
                 nfi.digitSubstitution = GetDigitSubstitution(_sRealName);
             }
 
@@ -2345,10 +2340,14 @@ namespace System.Globalization
             EnglishLanguageName = 0x00001001,
             /// <summary>native name of language, eg "Deutsch" (coresponds to LOCALE_SNATIVELANGUAGENAME)</summary>
             NativeLanguageName = 0x00000004,
+            /// <summary>localized name of country, eg "Germany" in UI language (coresponds to LOCALE_SLOCALIZEDCOUNTRYNAME)</summary>
+            LocalizedCountryName = 0x00000006,
             /// <summary>English name of country, eg "Germany" (coresponds to LOCALE_SENGLISHCOUNTRYNAME)</summary>
             EnglishCountryName = 0x00001002,
             /// <summary>native name of country, eg "Deutschland" (coresponds to LOCALE_SNATIVECOUNTRYNAME)</summary>
             NativeCountryName = 0x00000008,
+            /// <summary>abbreviated language name (coresponds to LOCALE_SABBREVLANGNAME)</summary>
+            AbbreviatedWindowsLanguageName = 0x00000003,
             /// <summary>list item separator (coresponds to LOCALE_SLIST)</summary>
             ListSeparator = 0x0000000C,
             /// <summary>decimal separator (coresponds to LOCALE_SDECIMAL)</summary>
@@ -2381,6 +2380,8 @@ namespace System.Globalization
             Iso639LanguageTwoLetterName = 0x00000059,
             /// <summary>ISO abbreviated country name (coresponds to LOCALE_SISO639LANGNAME2)</summary>
             Iso639LanguageThreeLetterName = 0x00000067,
+            /// <summary>ISO abbreviated language name (coresponds to LOCALE_SISO639LANGNAME)</summary>
+            Iso639LanguageName = 0x00000059,
             /// <summary>ISO abbreviated country name (coresponds to LOCALE_SISO3166CTRYNAME)</summary>
             Iso3166CountryName = 0x0000005A,
             /// <summary>3 letter ISO country code (coresponds to LOCALE_SISO3166CTRYNAME2)</summary>
@@ -2393,6 +2394,8 @@ namespace System.Globalization
             NegativeInfinitySymbol = 0x0000006b,
             /// <summary>Fallback name for resources (coresponds to LOCALE_SPARENT)</summary>
             ParentName = 0x0000006d,
+            /// <summary>Fallback name for within the console (coresponds to LOCALE_SCONSOLEFALLBACKNAME)</summary>
+            ConsoleFallbackName = 0x0000006e,
             /// <summary>Returns the percent symbol (coresponds to LOCALE_SPERCENT)</summary>
             PercentSymbol = 0x00000076,
             /// <summary>Returns the permille (U+2030) symbol (coresponds to LOCALE_SPERMILLE)</summary>
@@ -2419,6 +2422,10 @@ namespace System.Globalization
         {
             /// <summary>language id (coresponds to LOCALE_ILANGUAGE)</summary>
             LanguageId = 0x00000001,
+            /// <summary>geographical location id, (coresponds to LOCALE_IGEOID)</summary>
+            GeoId = 0x00000008,
+            /// <summary>0 = context, 1 = none, 2 = national (coresponds to LOCALE_IDIGITSUBSTITUTION)</summary>
+            DigitSubstitution = 0x00001014,
             /// <summary>0 = metric, 1 = US (coresponds to LOCALE_IMEASURE)</summary>
             MeasurementSystem = 0x0000000D,
             /// <summary>number of fractional digits (coresponds to LOCALE_IDIGITS)</summary>
@@ -2449,7 +2456,15 @@ namespace System.Globalization
             /// <summary>Returns 0-11 for the negative percent format (coresponds to LOCALE_INEGATIVEPERCENT)</summary>
             NegativePercentFormat = 0x00000074,
             /// <summary>Returns 0-3 for the positive percent format (coresponds to LOCALE_IPOSITIVEPERCENT)</summary>
-            PositivePercentFormat = 0x00000075
+            PositivePercentFormat = 0x00000075,
+            /// <summary>default ansi code page (coresponds to LOCALE_IDEFAULTCODEPAGE)</summary>
+            OemCodePage = 0x0000000B,
+            /// <summary>default ansi code page (coresponds to LOCALE_IDEFAULTANSICODEPAGE)</summary>
+            AnsiCodePage = 0x00001004,
+            /// <summary>default mac code page (coresponds to LOCALE_IDEFAULTMACCODEPAGE)</summary>
+            MacCodePage = 0x00001011,
+            /// <summary>default ebcdic code page (coresponds to LOCALE_IDEFAULTEBCDICCODEPAGE)</summary>
+            EbcdicCodePage = 0x00001012,
         }
     }
 }
index 16c8a06..c019eb2 100644 (file)
@@ -2,7 +2,9 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#if ENABLE_WINRT
 using Internal.Runtime.Augments;
+#endif
 
 namespace System.Globalization
 {
@@ -16,16 +18,18 @@ namespace System.Globalization
         /// </remarks>
         private static CultureInfo GetUserDefaultCultureCacheOverride()
         {
+#if ENABLE_WINRT
             WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
             if (callbacks != null && callbacks.IsAppxModel())
             {
                 return (CultureInfo)callbacks.GetUserDefaultCulture();
             }
+#endif
 
             return null;
         }
 
-        private static CultureInfo GetUserDefaultCulture()
+        internal static CultureInfo GetUserDefaultCulture()
         {
             const uint LOCALE_SNAME = 0x0000005c;
             const string LOCALE_NAME_USER_DEFAULT = null;
index ceee47c..da084d1 100644 (file)
 //
 ////////////////////////////////////////////////////////////////////////////
 
-using System;
-using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
-using System.Runtime;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
-using System.Security;
 using System.Threading;
 
 namespace System.Globalization
@@ -434,7 +429,7 @@ namespace System.Globalization
         [OnDeserialized]
         private void OnDeserialized(StreamingContext ctx)
         {
-            Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
+            Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
             InitializeFromName(m_name, m_useUserOverride);
         }
 
@@ -486,7 +481,7 @@ namespace System.Globalization
                     Init();
                 }
 
-                Contract.Assert(s_userDefaultCulture != null);
+                Debug.Assert(s_userDefaultCulture != null);
                 return s_userDefaultCulture;
             }
 
@@ -534,7 +529,7 @@ namespace System.Globalization
                     Init();
                 }
 
-                Contract.Assert(s_userDefaultCulture != null);
+                Debug.Assert(s_userDefaultCulture != null);
                 return s_userDefaultCulture;
             }
 
@@ -566,7 +561,7 @@ namespace System.Globalization
                 {
                     Init();
                 }
-                Contract.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null");
+                Debug.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null");
                 return s_userDefaultCulture;
             }
         }
@@ -765,7 +760,7 @@ namespace System.Globalization
             get
             {
                 Contract.Ensures(Contract.Result<String>() != null);
-                Contract.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set");
+                Debug.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set");
 
                 return m_cultureData.SLOCALIZEDDISPLAYNAME;
             }
@@ -1108,7 +1103,7 @@ namespace System.Globalization
         //calendars unless they're required.
         internal static Calendar GetCalendarInstanceRare(CalendarId calType)
         {
-            Contract.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN");
+            Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN");
 
             switch (calType)
             {
@@ -1152,7 +1147,7 @@ namespace System.Globalization
             {
                 if (calendar == null)
                 {
-                    Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
+                    Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
                     // Get the default calendar for this culture.  Note that the value can be
                     // from registry if this is a user default culture.
                     Calendar newObj = this.m_cultureData.DefaultCalendar;
index 577a95e..216fc60 100644 (file)
@@ -2,15 +2,10 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
-using System;
-using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
-using System.Security;
-using System.Text;
-using System.Threading;
 
 namespace System.Globalization
 {
@@ -55,7 +50,7 @@ namespace System.Globalization
 
 
     [Serializable]
-    public sealed partial class DateTimeFormatInfo : IFormatProvider, ICloneable
+    public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable
     {
         // cache for the invariant culture.
         // invariantInfo is constant irrespective of your current culture.
@@ -227,7 +222,7 @@ namespace System.Globalization
             {
                 // Get the abbreviated day names for our current calendar
                 this.abbreviatedDayNames = _cultureData.AbbreviatedDayNames(Calendar.ID);
-                Contract.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
+                Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
             }
             return (this.abbreviatedDayNames);
         }
@@ -251,7 +246,7 @@ namespace System.Globalization
             {
                 // Get the super short day names for our current calendar
                 this.m_superShortDayNames = _cultureData.SuperShortDayNames(Calendar.ID);
-                Contract.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
+                Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
             }
             return (this.m_superShortDayNames);
         }
@@ -268,7 +263,7 @@ namespace System.Globalization
             {
                 // Get the day names for our current calendar
                 this.dayNames = _cultureData.DayNames(Calendar.ID);
-                Contract.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
+                Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
             }
             return (this.dayNames);
         }
@@ -285,7 +280,7 @@ namespace System.Globalization
             {
                 // Get the month names for our current calendar
                 this.abbreviatedMonthNames = _cultureData.AbbreviatedMonthNames(Calendar.ID);
-                Contract.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
+                Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
                     "[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year");
             }
             return (this.abbreviatedMonthNames);
@@ -304,7 +299,7 @@ namespace System.Globalization
             {
                 // Get the month names for our current calendar
                 this.monthNames = _cultureData.MonthNames(Calendar.ID);
-                Contract.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
+                Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
                     "[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year");
             }
 
@@ -323,8 +318,8 @@ namespace System.Globalization
 
         internal DateTimeFormatInfo(CultureData cultureData, Calendar cal)
         {
-            Contract.Requires(cultureData != null);
-            Contract.Requires(cal != null);
+            Debug.Assert(cultureData != null);
+            Debug.Assert(cal != null);
 
             // Remember our culture
             _cultureData = cultureData;
@@ -334,8 +329,8 @@ namespace System.Globalization
 
         private void InitializeOverridableProperties(CultureData cultureData, CalendarId calendarId)
         {
-            Contract.Requires(cultureData != null);
-            Contract.Assert(calendarId != CalendarId.UNINITIALIZED_VALUE, "[DateTimeFormatInfo.Populate] Expected initalized calendarId");
+            Debug.Assert(cultureData != null);
+            Debug.Assert(calendarId != CalendarId.UNINITIALIZED_VALUE, "[DateTimeFormatInfo.Populate] Expected initalized calendarId");
 
             if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; }
             if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; }
@@ -346,19 +341,19 @@ namespace System.Globalization
             if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarId); }
 
             this.allLongTimePatterns = _cultureData.LongTimes;
-            Contract.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
+            Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
 
             this.allShortTimePatterns = _cultureData.ShortTimes;
-            Contract.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
+            Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
 
             this.allLongDatePatterns = cultureData.LongDates(calendarId);
-            Contract.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
+            Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
 
             this.allShortDatePatterns = cultureData.ShortDates(calendarId);
-            Contract.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
+            Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
 
             this.allYearMonthPatterns = cultureData.YearMonths(calendarId);
-            Contract.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
+            Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
         }
 
         [OptionalField(VersionAdded = 1)]
@@ -526,7 +521,7 @@ namespace System.Globalization
                 {
                     this.amDesignator = _cultureData.SAM1159;
                 }
-                Contract.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
+                Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
                 return (this.amDesignator);
             }
 
@@ -552,7 +547,7 @@ namespace System.Globalization
             {
                 Contract.Ensures(Contract.Result<Calendar>() != null);
 
-                Contract.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
+                Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
                 return (this.calendar);
             }
 
@@ -799,7 +794,7 @@ namespace System.Globalization
             {
                 if (this.m_abbrevEnglishEraNames == null)
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
                     this.m_abbrevEnglishEraNames = _cultureData.AbbreviatedEnglishEraNames(Calendar.ID);
                 }
                 return (this.m_abbrevEnglishEraNames);
@@ -816,10 +811,9 @@ namespace System.Globalization
                 {
                     dateSeparator = _cultureData.DateSeparator(Calendar.ID);
                 }
-                Contract.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
+                Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
                 return dateSeparator;
             }
-           
             set
             {
                 if (IsReadOnly)
@@ -843,7 +837,7 @@ namespace System.Globalization
                 {
                     this.firstDayOfWeek = _cultureData.IFIRSTDAYOFWEEK;
                 }
-                Contract.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
+                Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
 
                 return ((DayOfWeek)this.firstDayOfWeek);
             }
@@ -873,7 +867,7 @@ namespace System.Globalization
                 {
                     this.calendarWeekRule = _cultureData.IFIRSTWEEKOFYEAR;
                 }
-                Contract.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
+                Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
                 return ((CalendarWeekRule)this.calendarWeekRule);
             }
 
@@ -1012,10 +1006,10 @@ namespace System.Globalization
             {
                 if (this.monthDayPattern == null)
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
                     this.monthDayPattern = _cultureData.MonthDay(Calendar.ID);
                 }
-                Contract.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
+                Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
                 return (this.monthDayPattern);
             }
 
@@ -1044,7 +1038,7 @@ namespace System.Globalization
                 {
                     this.pmDesignator = _cultureData.SPM2359;
                 }
-                Contract.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
+                Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
                 return (this.pmDesignator);
             }
 
@@ -1285,7 +1279,7 @@ namespace System.Globalization
                 {
                     timeSeparator = _cultureData.TimeSeparator;
                 }
-                Contract.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
+                Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
                 return (timeSeparator);
             }
 
@@ -1356,8 +1350,8 @@ namespace System.Globalization
         //
         private static void CheckNullValue(String[] values, int length)
         {
-            Contract.Requires(values != null, "value != null");
-            Contract.Requires(values.Length >= length);
+            Debug.Assert(values != null, "value != null");
+            Debug.Assert(values.Length >= length);
             for (int i = 0; i < length; i++)
             {
                 if (values[i] == null)
@@ -1587,7 +1581,7 @@ namespace System.Globalization
                 if (this.m_genitiveAbbreviatedMonthNames == null)
                 {
                     this.m_genitiveAbbreviatedMonthNames = _cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID);
-                    Contract.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
+                    Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
                         "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year");
                 }
                 return (this.m_genitiveAbbreviatedMonthNames);
@@ -1596,7 +1590,7 @@ namespace System.Globalization
             if (this.genitiveMonthNames == null)
             {
                 this.genitiveMonthNames = _cultureData.GenitiveMonthNames(this.Calendar.ID);
-                Contract.Assert(this.genitiveMonthNames.Length == 13,
+                Debug.Assert(this.genitiveMonthNames.Length == 13,
                     "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year");
             }
             return (this.genitiveMonthNames);
@@ -1613,9 +1607,9 @@ namespace System.Globalization
         {
             if (this.leapYearMonthNames == null)
             {
-                Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
+                Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
                 this.leapYearMonthNames = _cultureData.LeapYearMonthNames(Calendar.ID);
-                Contract.Assert(this.leapYearMonthNames.Length == 13,
+                Debug.Assert(this.leapYearMonthNames.Length == 13,
                     "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names");
             }
             return (leapYearMonthNames);
@@ -1658,8 +1652,8 @@ namespace System.Globalization
         // Get all possible combination of inputs
         private static String[] GetCombinedPatterns(String[] patterns1, String[] patterns2, String connectString)
         {
-            Contract.Requires(patterns1 != null);
-            Contract.Requires(patterns2 != null);
+            Debug.Assert(patterns1 != null);
+            Debug.Assert(patterns2 != null);
 
             // Get array size
             String[] result = new String[patterns1.Length * patterns2.Length];
@@ -1807,9 +1801,9 @@ namespace System.Globalization
         // The resulting [] can get returned to the calling app, so clone it.
         private static string[] GetMergedPatterns(string[] patterns, string defaultPattern)
         {
-            Contract.Assert(patterns != null && patterns.Length > 0,
+            Debug.Assert(patterns != null && patterns.Length > 0,
                             "[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern");
-            Contract.Assert(defaultPattern != null,
+            Debug.Assert(defaultPattern != null,
                             "[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string");
 
             // If the default happens to be the first in the list just return (a cloned) copy
@@ -1910,9 +1904,9 @@ namespace System.Globalization
             {
                 if (this.allYearMonthPatterns == null)
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
                     this.allYearMonthPatterns = _cultureData.YearMonths(this.Calendar.ID);
-                    Contract.Assert(this.allYearMonthPatterns.Length > 0,
+                    Debug.Assert(this.allYearMonthPatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns");
                 }
 
@@ -1929,9 +1923,9 @@ namespace System.Globalization
             {
                 if (allShortDatePatterns == null)
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
                     this.allShortDatePatterns = _cultureData.ShortDates(this.Calendar.ID);
-                    Contract.Assert(this.allShortDatePatterns.Length > 0,
+                    Debug.Assert(this.allShortDatePatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns");
                 }
 
@@ -1947,9 +1941,9 @@ namespace System.Globalization
             {
                 if (allLongDatePatterns == null)
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
                     this.allLongDatePatterns = _cultureData.LongDates(this.Calendar.ID);
-                    Contract.Assert(this.allLongDatePatterns.Length > 0,
+                    Debug.Assert(this.allLongDatePatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns");
                 }
 
@@ -1966,7 +1960,7 @@ namespace System.Globalization
                 if (this.allShortTimePatterns == null)
                 {
                     this.allShortTimePatterns = _cultureData.ShortTimes;
-                    Contract.Assert(this.allShortTimePatterns.Length > 0,
+                    Debug.Assert(this.allShortTimePatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns");
                 }
 
@@ -1983,7 +1977,7 @@ namespace System.Globalization
                 if (this.allLongTimePatterns == null)
                 {
                     this.allLongTimePatterns = _cultureData.LongTimes;
-                    Contract.Assert(this.allLongTimePatterns.Length > 0,
+                    Debug.Assert(this.allLongTimePatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns");
                 }
 
@@ -2767,7 +2761,7 @@ namespace System.Globalization
             } while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber));
 
             // When we are here, we are either at the end of the string, or we find a valid Hebrew number.
-            Contract.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
+            Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
                 "Invalid returned state from HebrewNumber.ParseByChar()");
 
             if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber)
@@ -2802,7 +2796,7 @@ namespace System.Globalization
             tokenValue = 0;
 
             TokenHashValue value;
-            Contract.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
+            Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
 
             char ch = str.m_current;
             bool isLetter = Char.IsLetter(ch);
@@ -2925,7 +2919,7 @@ namespace System.Globalization
                 }
                 previousNode = temp;
             };
-            Contract.Assert(false, "The hashtable is full.  This should not happen.");
+            Debug.Assert(false, "The hashtable is full.  This should not happen.");
         }
 
         private void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue)
@@ -3013,7 +3007,7 @@ namespace System.Globalization
                 hashcode += hashProbe;
                 if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
             } while (i < TOKEN_HASH_SIZE);
-            Contract.Assert(false, "The hashtable is full.  This should not happen.");
+            Debug.Assert(false, "The hashtable is full.  This should not happen.");
         }
 
         private bool CompareStringIgnoreCaseOptimized(string string1, int offset1, int length1, string string2, int offset2, int length2)
index 2345fb5..6ec9d6a 100644 (file)
@@ -9,11 +9,11 @@ namespace System.Globalization
     // This class represents a starting/ending time for a period of daylight saving time.
 
     [Serializable]
-    public partial class DaylightTime
+    public class DaylightTime
     {
-        internal DateTime m_start;
-        internal DateTime m_end;
-        internal TimeSpan m_delta;
+        private readonly DateTime _start;
+        private readonly DateTime _end;
+        private readonly TimeSpan _delta;
 
         private DaylightTime()
         {
@@ -21,36 +21,33 @@ namespace System.Globalization
 
         public DaylightTime(DateTime start, DateTime end, TimeSpan delta)
         {
-            m_start = start;
-            m_end = end;
-            m_delta = delta;
+            _start = start;
+            _end = end;
+            _delta = delta;
         }
 
         // The start date of a daylight saving period.
-        public DateTime Start
-        {
-            get
-            {
-                return m_start;
-            }
-        }
+        public DateTime Start => _start;
 
         // The end date of a daylight saving period.
-        public DateTime End
-        {
-            get
-            {
-                return m_end;
-            }
-        }
+        public DateTime End => _end;
 
         // Delta to stardard offset in ticks.
-        public TimeSpan Delta
+        public TimeSpan Delta => _delta;
+    }
+
+    // Value type version of DaylightTime
+    internal struct DaylightTimeStruct
+    {
+        public DaylightTimeStruct(DateTime start, DateTime end, TimeSpan delta)
         {
-            get
-            {
-                return m_delta;
-            }
+            Start = start;
+            End = end;
+            Delta = delta;
         }
+
+        public readonly DateTime Start;
+        public readonly DateTime End;
+        public readonly TimeSpan Delta;
     }
 }
index c43cd78..7e63708 100644 (file)
@@ -2,8 +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;
-using System.Text;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Globalization
@@ -65,7 +64,7 @@ namespace System.Globalization
 
     [Serializable]
     [System.Runtime.InteropServices.ComVisible(true)]
-    public partial class HebrewCalendar : Calendar
+    public class HebrewCalendar : Calendar
     {
         public static readonly int HebrewEra = 1;
 
@@ -603,7 +602,7 @@ namespace System.Globalization
             //  is true.
             //
             NumDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month] - lunarDate.day);
-            Contract.Assert(NumDays >= 1, "NumDays >= 1");
+            Debug.Assert(NumDays >= 1, "NumDays >= 1");
 
             // If NumDays is 1, then we are done.  Otherwise, find the correct Hebrew month
             // and day.
@@ -827,7 +826,7 @@ namespace System.Globalization
             int hebrewYearType = GetHebrewYearType(year, era);
             CheckHebrewMonthValue(year, month, era);
 
-            Contract.Assert(hebrewYearType >= 1 && hebrewYearType <= 6,
+            Debug.Assert(hebrewYearType >= 1 && hebrewYearType <= 6,
                 "hebrewYearType should be from  1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year);
             int monthDays = s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + month];
             if (monthDays == 0)
index 8fc264b..01e251d 100644 (file)
@@ -2,18 +2,11 @@
 // 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.Diagnostics;
-using System.Diagnostics.Contracts;
 
 namespace System.Globalization
 {
-
-#if INSIDE_CLR
-    using Debug = BCLDebug;
-#endif
-
     ////////////////////////////////////////////////////////////////////////////
     //
     // Used in HebrewNumber.ParseByChar to maintain the context information (
@@ -110,7 +103,7 @@ namespace System.Globalization
                 Number -= 5000;
             }
 
-            Contract.Assert(Number > 0 && Number <= 999, "Number is out of range."); ;
+            Debug.Assert(Number > 0 && Number <= 999, "Number is out of range."); ;
 
             //
             //  Get the Hundreds.
@@ -335,7 +328,7 @@ namespace System.Globalization
         // 
         // The state machine for Hebrew number pasing.
         //
-        private readonly static HS[] s_numberPasingState =
+        private static readonly HS[] s_numberPasingState =
         {
             // 400            300/200         100             90~10           8~1      6,       7,       9,          '           "
             /* 0 */
diff --git a/src/mscorlib/corefx/System/Globalization/HijriCalendar.Win32.cs b/src/mscorlib/corefx/System/Globalization/HijriCalendar.Win32.cs
new file mode 100644 (file)
index 0000000..5f46dce
--- /dev/null
@@ -0,0 +1,86 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32;
+
+namespace System.Globalization
+{
+    public partial class HijriCalendar : Calendar
+    {
+        private static int GetHijriDateAdjustment()
+        {
+            if (_hijriAdvance == Int32.MinValue) {
+                // Never been set before.  Use the system value from registry.
+                _hijriAdvance = GetAdvanceHijriDate();
+            }
+            return (_hijriAdvance);
+        }
+
+        private const String InternationalRegKey = "Control Panel\\International";
+        private const String HijriAdvanceRegKeyEntry = "AddHijriDate";
+
+        /*=================================GetAdvanceHijriDate==========================
+        **Action: Gets the AddHijriDate value from the registry.
+        **Returns:
+        **Arguments:    None.
+        **Exceptions:
+        **Note:
+        **  The HijriCalendar has a user-overidable calculation.  That is, use can set a value from the control
+        **  panel, so that the calculation of the Hijri Calendar can move ahead or backwards from -2 to +2 days.
+        **
+        **  The valid string values in the registry are:
+        **      "AddHijriDate-2"  =>  Add -2 days to the current calculated Hijri date.
+        **      "AddHijriDate"    =>  Add -1 day to the current calculated Hijri date.
+        **      ""              =>  Add 0 day to the current calculated Hijri date.
+        **      "AddHijriDate+1"  =>  Add +1 days to the current calculated Hijri date.
+        **      "AddHijriDate+2"  =>  Add +2 days to the current calculated Hijri date.
+        ============================================================================*/
+        private static int GetAdvanceHijriDate() {
+            int hijriAdvance = 0;
+            Microsoft.Win32.RegistryKey key = null;
+
+            try {
+                // Open in read-only mode.
+                // Use InternalOpenSubKey so that we avoid the security check.
+                key = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_USER).OpenSubKey(InternationalRegKey, false);
+            }
+            //If this fails for any reason, we'll just return 0.
+            catch (ObjectDisposedException) { return 0; }
+            catch (ArgumentException) { return 0; }
+
+            if (key != null) {
+                try {
+                    Object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false);
+                    if (value == null) {
+                        return (0);
+                    }
+                    String str = value.ToString();
+                    if (String.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0) {
+                        if (str.Length == HijriAdvanceRegKeyEntry.Length)
+                            hijriAdvance = -1;
+                        else {
+                            str = str.Substring(HijriAdvanceRegKeyEntry.Length);
+                            try {
+                                int advance = Int32.Parse(str.ToString(), CultureInfo.InvariantCulture);
+                                if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri)) {
+                                    hijriAdvance = advance;
+                                }
+                            }
+                            // If we got garbage from registry just ignore it.
+                            // hijriAdvance = 0 because of declaraction assignment up above.
+                            catch (ArgumentException) { }
+                            catch (FormatException) { }
+                            catch (OverflowException) { }
+                        }
+                    }
+                }
+                finally {
+                    key.Close();
+                }
+
+            }
+            return (hijriAdvance);
+        }
+    }
+}
@@ -8,7 +8,7 @@ namespace System.Globalization
 {
     public partial class HijriCalendar : Calendar
     {
-        public static int GetHijriDateAdjustment()
+        private static int GetHijriDateAdjustment()
         {
             return WinRTInterop.Callbacks.GetHijriDateAdjustment();
         }
index 12f430c..b9bd94a 100644 (file)
@@ -3,13 +3,11 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Collections.Generic;
-using System.Security;
 
 namespace System.Globalization
 {
     public partial class JapaneseCalendar : Calendar
     {
-        [SecuritySafeCritical]
         private static EraInfo[] GetJapaneseEras()
         {
             string[] eraNames;
@@ -66,7 +64,6 @@ namespace System.Globalization
             return eraNames[eraIndex].Substring(0, 1);
         }
 
-        [SecuritySafeCritical]
         private static bool GetJapaneseEraStartDate(int era, out DateTime dateTime)
         {
             dateTime = default(DateTime);
diff --git a/src/mscorlib/corefx/System/Globalization/JapaneseCalendar.Win32.cs b/src/mscorlib/corefx/System/Globalization/JapaneseCalendar.Win32.cs
new file mode 100644 (file)
index 0000000..bbde320
--- /dev/null
@@ -0,0 +1,209 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+
+using Microsoft.Win32;
+
+namespace System.Globalization
+{
+    public partial class JapaneseCalendar : Calendar
+    {
+        private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
+        private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
+
+        // We know about 4 built-in eras, however users may add additional era(s) from the
+        // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
+        //
+        // Registry values look like:
+        //      yyyy.mm.dd=era_abbrev_english_englishabbrev
+        //
+        // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
+        // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
+        // era is the Japanese Era name
+        // abbrev is the Abbreviated Japanese Era Name
+        // english is the English name for the Era (unused)
+        // englishabbrev is the Abbreviated English name for the era.
+        // . is a delimiter, but the value of . doesn't matter.
+        // '_' marks the space between the japanese era name, japanese abbreviated era name
+        //     english name, and abbreviated english names.
+        private static EraInfo[] GetJapaneseEras()
+        {
+            // Look in the registry key and see if we can find any ranges
+            int iFoundEras = 0;
+            EraInfo[] registryEraRanges = null;
+            
+            try
+            {
+                // Need to access registry
+                RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false);
+
+                // Abort if we didn't find anything
+                if (key == null) return null;
+
+                // Look up the values in our reg key
+                String[] valueNames = key.GetValueNames();
+                if (valueNames != null && valueNames.Length > 0)
+                {
+                    registryEraRanges = new EraInfo[valueNames.Length];
+
+                    // Loop through the registry and read in all the values
+                    for (int i = 0; i < valueNames.Length; i++)
+                    {
+                        // See if the era is a valid date
+                        EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
+
+                        // continue if not valid
+                        if (era == null) continue;
+
+                        // Remember we found one.
+                        registryEraRanges[iFoundEras] = era;
+                        iFoundEras++;                        
+                    }
+                }
+            }
+            catch (System.Security.SecurityException)
+            {
+                // If we weren't allowed to read, then just ignore the error
+                return null;
+            }
+            catch (System.IO.IOException)
+            {
+                // If key is being deleted just ignore the error
+                return null;
+            }
+            catch (System.UnauthorizedAccessException)
+            {
+                // Registry access rights permissions, just ignore the error
+                return null;
+            }
+
+            //
+            // If we didn't have valid eras, then fail
+            // should have at least 4 eras
+            //
+            if (iFoundEras < 4) return null;
+
+            //
+            // Now we have eras, clean them up.
+            //
+            // Clean up array length
+            Array.Resize(ref registryEraRanges, iFoundEras);
+
+            // Sort them
+            Array.Sort(registryEraRanges, CompareEraRanges);
+
+            // Clean up era information
+            for (int i = 0; i < registryEraRanges.Length; i++)
+            {
+                // eras count backwards from length to 1 (and are 1 based indexes into string arrays)
+                registryEraRanges[i].era = registryEraRanges.Length - i;
+
+                // update max era year
+                if (i == 0)
+                {
+                    // First range is 'til the end of the calendar
+                    registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset;
+                }
+                else
+                {
+                    // Rest are until the next era (remember most recent era is first in array)
+                    registryEraRanges[i].maxEraYear = registryEraRanges[i-1].yearOffset + 1 - registryEraRanges[i].yearOffset;
+                }
+            }
+
+            // Return our ranges
+            return registryEraRanges;
+        }
+
+        //
+        // Compare two era ranges, eg just the ticks
+        // Remember the era array is supposed to be in reverse chronological order
+        //
+        private static int CompareEraRanges(EraInfo a, EraInfo b)
+        {
+            return b.ticks.CompareTo(a.ticks);
+        }
+
+        //
+        // GetEraFromValue
+        //
+        // Parse the registry value name/data pair into an era
+        //
+        // Registry values look like:
+        //      yyyy.mm.dd=era_abbrev_english_englishabbrev
+        //
+        // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
+        // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
+        // era is the Japanese Era name
+        // abbrev is the Abbreviated Japanese Era Name
+        // english is the English name for the Era (unused)
+        // englishabbrev is the Abbreviated English name for the era.
+        // . is a delimiter, but the value of . doesn't matter.
+        // '_' marks the space between the japanese era name, japanese abbreviated era name
+        //     english name, and abbreviated english names.
+        private static EraInfo GetEraFromValue(String value, String data)
+        {
+            // Need inputs
+            if (value == null || data == null) return null;
+            
+            //
+            // Get Date
+            //
+            // Need exactly 10 characters in name for date
+            // yyyy.mm.dd although the . can be any character
+            if (value.Length != 10) return null;
+
+            int year;
+            int month;
+            int day;
+
+            if (!Int32.TryParse(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) ||
+                !Int32.TryParse(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) ||
+                !Int32.TryParse(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day))
+            {
+                // Couldn't convert integer, fail
+                return null;
+            }
+
+            //
+            // Get Strings
+            //
+            // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
+            String[] names = data.Split(new char[] {'_'});
+
+            // Should have exactly 4 parts
+            // 0 - Era Name
+            // 1 - Abbreviated Era Name
+            // 2 - English Era Name
+            // 3 - Abbreviated English Era Name
+            if (names.Length != 4) return null;
+
+            // Each part should have data in it
+            if (names[0].Length == 0 ||
+                names[1].Length == 0 ||
+                names[2].Length == 0 ||
+                names[3].Length == 0)
+                return null;
+
+            //
+            // Now we have an era we can build
+            // Note that the era # and max era year need cleaned up after sorting
+            // Don't use the full English Era Name (names[2])
+            //
+            return new EraInfo( 0, year, month, day, year - 1, 1, 0, 
+                                names[0], names[1], names[3]);
+        }
+
+        // PAL Layer ends here
+
+        private static string[] JapaneseErasEnglishNames = new String[] { "M", "T", "S", "H" };
+
+        private static string GetJapaneseEnglishEraName(int era)
+        {
+            Debug.Assert(era > 0);
+            return era <= JapaneseErasEnglishNames.Length ? JapaneseErasEnglishNames[era - 1] : " ";
+        }
+    }
+}
index 7cefb75..0b0fa77 100644 (file)
@@ -9,11 +9,6 @@ using System.Diagnostics.Contracts;
 
 namespace System.Globalization
 {
-
-#if INSIDE_CLR
-    using Debug = BCLDebug;
-#endif
-
     /*=================================JapaneseCalendar==========================
     **
     ** JapaneseCalendar is based on Gregorian calendar.  The month and day values are the same as
index 690a461..d4c58d8 100644 (file)
@@ -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.Diagnostics;
 using System.Diagnostics.Contracts;
 
 // This file contains the handling of Windows OS specific culture features.  
@@ -4424,7 +4425,7 @@ namespace System.Globalization
             int right = s_lcids.Length - 1;
             int index;
 
-            Contract.Assert(s_lcids.Length == s_lcidToCultureNameIndices.Length);
+            Debug.Assert(s_lcids.Length == s_lcidToCultureNameIndices.Length);
 
             while (left <= right)
             {
@@ -4433,7 +4434,7 @@ namespace System.Globalization
                 if (culture == s_lcids[index])
                 {
                     int indexToLocaleNamesIndices = s_lcidToCultureNameIndices[index];
-                    Contract.Assert(indexToLocaleNamesIndices < s_localeNamesIndices.Length - 1);
+                    Debug.Assert(indexToLocaleNamesIndices < s_localeNamesIndices.Length - 1);
                     
                     return c_localeNames.Substring(s_localeNamesIndices[indexToLocaleNamesIndices], 
                                                                          s_localeNamesIndices[indexToLocaleNamesIndices + 1] - 
@@ -4460,7 +4461,7 @@ namespace System.Globalization
                 return -1; 
             }
             
-            Contract.Assert((s_localeNamesIndices.Length-1 == (s_nameIndexToNumericData.Length/NUMERIC_LOCALE_DATA_COUNT_PER_ROW)) && 
+            Debug.Assert((s_localeNamesIndices.Length-1 == (s_nameIndexToNumericData.Length/NUMERIC_LOCALE_DATA_COUNT_PER_ROW)) && 
                             index < s_localeNamesIndices.Length);
             
             return s_nameIndexToNumericData[index * NUMERIC_LOCALE_DATA_COUNT_PER_ROW + (int) part];
@@ -4474,7 +4475,7 @@ namespace System.Globalization
                 return null;
             }
             
-            Contract.Assert(s_localeNamesIndices.Length-1 == (c_threeLetterWindowsLanguageName.Length / 3));
+            Debug.Assert(s_localeNamesIndices.Length-1 == (c_threeLetterWindowsLanguageName.Length / 3));
             return c_threeLetterWindowsLanguageName.Substring(index * 3, 3); 
         }
         
@@ -4486,7 +4487,7 @@ namespace System.Globalization
                 return ""; // fallback to invariant
             }
             
-            Contract.Assert(indexToIndicesTable < s_localeNamesIndices.Length-1);
+            Debug.Assert(indexToIndicesTable < s_localeNamesIndices.Length-1);
             
             return c_localeNames.Substring(s_localeNamesIndices[indexToIndicesTable], 
                                            s_localeNamesIndices[indexToIndicesTable+1] - s_localeNamesIndices[indexToIndicesTable]);
@@ -4511,7 +4512,7 @@ namespace System.Globalization
             int index;
             int result;
 
-            Contract.Assert(s_localeNamesIndices[s_localeNamesIndices.Length - 1] == c_localeNames.Length);
+            Debug.Assert(s_localeNamesIndices[s_localeNamesIndices.Length - 1] == c_localeNames.Length);
 
             name = CultureData.AnsiToLower(name);
 
@@ -4521,7 +4522,7 @@ namespace System.Globalization
             {
                 index = ((right - left) / 2) + left;
 
-                Contract.Assert(index < s_localeNamesIndices.Length - 1);
+                Debug.Assert(index < s_localeNamesIndices.Length - 1);
                 result = CompareOrdinal(name, c_localeNames, s_localeNamesIndices[index], s_localeNamesIndices[index + 1] - s_localeNamesIndices[index]);
                 if (result == 0)
                 {
@@ -4540,7 +4541,7 @@ namespace System.Globalization
             // Walk the remaining elements (it'll be 3 or fewer).
             for (; left <= right; left++)
             {
-                Contract.Assert(left < s_localeNamesIndices.Length - 1);
+                Debug.Assert(left < s_localeNamesIndices.Length - 1);
                 if (CompareOrdinal(name, c_localeNames, s_localeNamesIndices[left], s_localeNamesIndices[left + 1] - s_localeNamesIndices[left]) == 0)
                 {
                     return (left);
index fd5b3a6..813554f 100644 (file)
@@ -42,7 +42,7 @@ namespace System.Globalization
     //
 
     [Serializable]
-    sealed public partial class NumberFormatInfo : IFormatProvider, ICloneable
+    sealed public class NumberFormatInfo : IFormatProvider, ICloneable
     {
         // invariantInfo is constant irrespective of your current culture.
         private static volatile NumberFormatInfo s_invariantInfo;
index 30269a0..b8b3da6 100644 (file)
@@ -2,7 +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;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Globalization
@@ -180,7 +180,7 @@ namespace System.Globalization
 
         private static int MonthFromOrdinalDay(int ordinalDay)
         {
-            Contract.Assert(ordinalDay <= 366);
+            Debug.Assert(ordinalDay <= 366);
             int index = 0;
             while (ordinalDay > DaysToMonth[index])
                 index++;
@@ -190,7 +190,7 @@ namespace System.Globalization
 
         private static int DaysInPreviousMonths(int month)
         {
-            Contract.Assert(1 <= month && month <= 12);
+            Debug.Assert(1 <= month && month <= 12);
             --month; // months are one based but for calculations use 0 based
             return DaysToMonth[month];
         }
@@ -221,7 +221,7 @@ namespace System.Globalization
 
             long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
             int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
-            Contract.Assert(y >= 1);
+            Debug.Assert(y >= 1);
 
             if (part == DatePartYear)
             {
@@ -240,16 +240,16 @@ namespace System.Globalization
             }
 
             int m = MonthFromOrdinalDay(ordinalDay);
-            Contract.Assert(ordinalDay >= 1);
-            Contract.Assert(m >= 1 && m <= 12);
+            Debug.Assert(ordinalDay >= 1);
+            Debug.Assert(m >= 1 && m <= 12);
             if (part == DatePartMonth)
             {
                 return m;
             }
 
             int d = ordinalDay - DaysInPreviousMonths(m);
-            Contract.Assert(1 <= d);
-            Contract.Assert(d <= 31);
+            Debug.Assert(1 <= d);
+            Debug.Assert(d <= 31);
 
             //
             //  Calculate the Persian Day.
@@ -385,7 +385,7 @@ namespace System.Globalization
             int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
             if ((month == MonthsPerYear) && !IsLeapYear(year))
             {
-                Contract.Assert(daysInMonth == 30);
+                Debug.Assert(daysInMonth == 30);
                 --daysInMonth;
             }
             return daysInMonth;
index 5e33294..0645ded 100644 (file)
 //
 ////////////////////////////////////////////////////////////////////////////
 
-using System;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.Serialization;
 
 namespace System.Globalization
 {
     [Serializable]
-    public partial class RegionInfo
+    public class RegionInfo
     {
         //--------------------------------------------------------------------//
         //                        Internal Information                        //
@@ -185,7 +185,7 @@ namespace System.Globalization
         {
             get
             {
-                Contract.Assert(_name != null, "Expected RegionInfo._name to be populated already");
+                Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already");
                 return (_name);
             }
         }
index ccb1e8f..fc151fa 100644 (file)
@@ -16,6 +16,7 @@ namespace System.Globalization {
     using System;
     using System.Runtime.CompilerServices;
     using System.Runtime.Serialization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [System.Runtime.InteropServices.ComVisible(true)]
@@ -125,8 +126,8 @@ namespace System.Globalization {
             byte[] key1Data = sortkey1._keyData;
             byte[] key2Data = sortkey2._keyData;
     
-            Contract.Assert(key1Data != null, "key1Data != null");
-            Contract.Assert(key2Data != null, "key2Data != null");
+            Debug.Assert(key1Data != null, "key1Data != null");
+            Debug.Assert(key2Data != null, "key2Data != null");
 
             if (key1Data.Length == 0)
             {
index 1acef44..7558002 100644 (file)
@@ -13,6 +13,7 @@
 ////////////////////////////////////////////////////////////////////////////
 
 using System;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.Serialization;
 
@@ -20,7 +21,7 @@ namespace System.Globalization
 {
     [Serializable]
     [System.Runtime.InteropServices.ComVisible(true)]
-    public partial class StringInfo
+    public class StringInfo
     {
         [OptionalField(VersionAdded = 2)] 
         private string _str;
@@ -213,8 +214,8 @@ namespace System.Globalization
 
         internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
         {
-            Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
-            Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+            Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+            Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
             if (index + currentCharCount == len)
             {
                 // This is the last character/surrogate in the string.
index 487ef11..c0ffc65 100644 (file)
@@ -11,7 +11,7 @@
 ////////////////////////////////////////////////////////////////////////////
 
 using System.Collections;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
 using System.Runtime.Serialization;
 
 namespace System.Globalization
@@ -42,9 +42,9 @@ namespace System.Globalization
 
         internal TextElementEnumerator(String str, int startIndex, int strLen)
         {
-            Contract.Assert(str != null, "TextElementEnumerator(): str != null");
-            Contract.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
-            Contract.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
+            Debug.Assert(str != null, "TextElementEnumerator(): str != null");
+            Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
+            Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
             _str = str;
             _startIndex = startIndex;
             _strLen = strLen;
@@ -125,7 +125,7 @@ namespace System.Globalization
         }
 
         //
-        // Get the starting _index of the current text element.
+        // Get the starting index of the current text element.
         //
 
         public int ElementIndex
index 8490057..3d9b777 100644 (file)
@@ -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.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Security;
 using System.Text;
@@ -35,7 +36,7 @@ namespace System.Globalization
         [SecuritySafeCritical]
         private unsafe string ChangeCase(string s, bool toUpper)
         {
-            Contract.Assert(s != null);
+            Debug.Assert(s != null);
 
             if (s.Length == 0)
             {
@@ -93,7 +94,7 @@ namespace System.Globalization
 
         private bool NeedsTurkishCasing(string localeName)
         {
-            Contract.Assert(localeName != null);
+            Debug.Assert(localeName != null);
 
             return CultureInfo.GetCultureInfo(localeName).CompareInfo.Compare("\u0131", "I", CompareOptions.IgnoreCase) == 0;
         }
index 238c512..b2f692e 100644 (file)
@@ -2,7 +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.Diagnostics.Contracts;
+using System.Diagnostics;
 
 namespace System.Globalization
 {
@@ -35,7 +35,7 @@ namespace System.Globalization
 
         private unsafe string ChangeCase(string s, bool toUpper)
         {
-            Contract.Assert(s != null);
+            Debug.Assert(s != null);
 
             //
             //  Get the length of the string.
@@ -80,7 +80,7 @@ namespace System.Globalization
                     throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
                 }
 
-                Contract.Assert(ret == nLengthInput, "Expected getting the same length of the original string");
+                Debug.Assert(ret == nLengthInput, "Expected getting the same length of the original string");
                 return result;
             }
         }
index 44c0759..5bb376f 100644 (file)
 //
 ////////////////////////////////////////////////////////////////////////////
 
-using System;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
-using System.Runtime;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
-using System.Security;
 using System.Text;
-using System.Threading;
 
 namespace System.Globalization
 {
@@ -235,10 +230,10 @@ namespace System.Globalization
         ////
         ////  Clone
         ////
-        ////  Is the implementation of IColnable.
+        ////  Is the implementation of ICloneable.
         ////
         //////////////////////////////////////////////////////////////////////////
-        public virtual Object Clone()
+        public virtual object Clone()
         {
             object o = MemberwiseClone();
             ((TextInfo)o).SetReadOnlyState(false);
@@ -375,7 +370,7 @@ namespace System.Globalization
             return c;
         }
 
-        static private bool IsAscii(Char c)
+        private static bool IsAscii(Char c)
         {
             return c < 0x80;
         }
@@ -582,7 +577,7 @@ namespace System.Globalization
 
         private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
         {
-            Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+            Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
             if (charLen == 2)
             {
                 // Surrogate pair
@@ -598,7 +593,7 @@ namespace System.Globalization
 
         private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
         {
-            Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+            Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
 
             // for surrogate pairs do a simple ToUpper operation on the substring
             if (charLen == 2) 
@@ -735,7 +730,7 @@ namespace System.Globalization
 
         private unsafe int GetCaseInsensitiveHashCodeSlow(String str)
         {
-            Contract.Assert(str != null);
+            Debug.Assert(str != null);
 
             string upper = ToUpper(str);
 
index 3ab516e..997c5f2 100644 (file)
@@ -2,7 +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;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Globalization
@@ -317,9 +317,9 @@ namespace System.Globalization
         =========================ConvertHijriToGregorian============================*/
         private static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg)
         {
-            Contract.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
-            Contract.Assert(HijriMonth >= 1, "Hijri month is out of range.");
-            Contract.Assert(HijriDay >= 1, "Hijri day is out of range.");
+            Debug.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
+            Debug.Assert(HijriMonth >= 1, "Hijri month is out of range.");
+            Debug.Assert(HijriDay >= 1, "Hijri day is out of range.");
             int index, b, nDays = HijriDay - 1;
             DateTime dt;
 
@@ -417,7 +417,7 @@ namespace System.Globalization
             TimeSpan ts;
             int yh1 = 0, mh1 = 0, dh1 = 0;
 
-            Contract.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
+            Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
 
             // Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo.
             // A Hijri year is 354 or 355 days.  Use 355 days so that we will search from a lower index.
@@ -630,7 +630,7 @@ namespace System.Globalization
         {
             int days = 0, b;
 
-            Contract.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
+            Debug.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
 
             b = s_hijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags;
 
@@ -639,7 +639,7 @@ namespace System.Globalization
                 days = days + 29 + (b & 1);   /* Add the months lengths before mh */
                 b = b >> 1;
             }
-            Contract.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days.");
+            Debug.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days.");
             return days;
         }
 
index 6f8efb8..532dbb0 100644 (file)
@@ -58,7 +58,7 @@ namespace System.IO
 
             internal NativeOverlapped* Overlapped
             {
-                [SecurityCritical]get { return _overlapped; }
+                get { return _overlapped; }
             }
 
             public void SetCompletedSynchronously(int numBytes)
index 8dce4f0..29cef08 100644 (file)
@@ -117,7 +117,6 @@ namespace System.Runtime.InteropServices
         /// <summary>
         /// True if the buffer contains the given character.
         /// </summary>
-        [System.Security.SecurityCritical]
         public unsafe bool Contains(char value)
         {
             char* start = CharPointer;
index 6535087..104fc6e 100644 (file)
         <Member Name="get_Array" />
         <Member Name="get_Count" />
         <Member Name="get_Offset" />
+        <Member Name="GetEnumerator" />
         <Member Name="GetHashCode" />
         <Member Name="op_Equality(System.ArraySegment&lt;T&gt;,System.ArraySegment&lt;T&gt;)" />
         <Member Name="op_Inequality(System.ArraySegment&lt;T&gt;,System.ArraySegment&lt;T&gt;)" />
         <Member MemberType="Property" Name="Count" />
         <Member MemberType="Property" Name="Offset" />
     </Type>
+    <Type Name="System.ArraySegment&lt;T&gt;+Enumerator">
+      <Member Name="Dispose" />
+      <Member Name="get_Current" />
+      <Member Name="MoveNext" />
+      <Member MemberType="Property" Name="Current" />
+      <Member Name="System.Collections.IEnumerator.Reset" />
+    </Type>
     <Type Name="System.ArrayTypeMismatchException">
       <Member Name="#ctor" />
       <Member Name="#ctor(System.String)" />
     <Type Name="System.Runtime.CompilerServices.ConditionalWeakTable&lt;TKey,TValue&gt;">
       <Member Name="#ctor" />
       <Member Name="Add(TKey,TValue)" />
+      <Member Name="AddOrUpdate(TKey,TValue)" />
       <Member Name="Remove(TKey)" />
       <Member Name="TryGetValue(TKey,TValue@)" />
       <Member Name="GetValue(TKey,System.Runtime.CompilerServices.ConditionalWeakTable+CreateValueCallback)" />
       <Member Name="AppendFormat(System.String,System.Object,System.Object)" />
       <Member Name="AppendFormat(System.String,System.Object,System.Object,System.Object)" />
       <Member Name="AppendFormat(System.String,System.Object[])" />
+      <Member Name="AppendJoin&lt;T&gt;(System.Char,System.Collections.Generic.IEnumerable&lt;T&gt;)" />
+      <Member Name="AppendJoin&lt;T&gt;(System.Char,T[])" />
+      <Member Name="AppendJoin&lt;T&gt;(System.String,System.Collections.Generic.IEnumerable&lt;T&gt;)" />
+      <Member Name="AppendJoin&lt;T&gt;(System.String,T[])" />
       <Member Name="AppendLine" />
       <Member Name="AppendLine(System.String)" />
       <Member Name="Clear" />
       <Member Name="DangerousGetPinnableReference" />
       <Member Name="op_Implicit(T[])" ReturnType="System.Span&lt;T&gt;" />
       <Member Name="op_Implicit(System.ArraySegment&lt;T&gt;)" ReturnType="System.Span&lt;T&gt;" />
+      <Member Name="op_Equality(System.Span&lt;T&gt;,System.Span&lt;T&gt;)" />
+      <Member Name="op_Inequality(System.Span&lt;T&gt;,System.Span&lt;T&gt;)" />
       <Member Name="get_Length" />
       <Member Name="get_Empty" />
       <Member Name="get_IsEmpty" />
       <Member Name="Slice(System.Int32)" />
       <Member Name="Slice(System.Int32,System.Int32)" />
       <Member Name="Equals(System.Span&lt;T&gt;)" />
+      <Member Name="Equals(System.Object)" />
+      <Member Name="GetHashCode" />
+      <Member Name="CopyTo(System.Span&lt;T&gt;)" />
       <Member Name="TryCopyTo(System.Span&lt;T&gt;)" />
-      <Member Name="Set(System.ReadOnlySpan&lt;T&gt;)" />
     </Type>
     <Type Name="System.ReadOnlySpan&lt;T&gt;" Condition="FEATURE_SPAN_OF_T">
       <Member Name="#ctor(T[])" />
index 8d4142e..4761b8d 100644 (file)
     <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\IRegistrationServices.cs" />
     <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ITypeLibConverter.cs" />
     <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\RegistrationServices.cs" />
-    <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\TypeLibConverter.cs" />
     <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIBindCtx.cs" />
     <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIConnectionPointContainer.cs" />
     <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIConnectionPoint.cs" />
   <ItemGroup Condition="'$(TargetsUnix)' == 'true'">
     <SafehandleSources Include="$(CoreFxSourcesRoot)\Microsoft\Win32\SafeHandles\SafeFileHandle.Unix.cs" />
     <FileStreamSources Include="$(CoreFxSourcesRoot)\System\IO\FileStream.Unix.cs" />
-    <SystemSources Include="$(BclSourcesRoot)\System\Environment.Unix.cs" />
   </ItemGroup>
   <ItemGroup Condition="'$(TargetsUnix)' != 'true'">
     <SafehandleSources Include="$(CoreFxSourcesRoot)\Microsoft\Win32\SafeHandles\SafeFileHandle.Windows.cs" />
     <FileStreamSources Include="$(CoreFxSourcesRoot)\System\IO\FileStream.Win32.cs" />
     <FileStreamSources Include="$(CoreFxSourcesRoot)\System\IO\FileStreamCompletionSource.Win32.cs" />
     <FileStreamSources Include="$(CoreFxSourcesRoot)\System\IO\Win32Marshal.cs" />
-    <SystemSources Include="$(BclSourcesRoot)\System\Environment.Win32.cs" />
   </ItemGroup>
   <ItemGroup>
     <IoSources Include="$(CoreFxSourcesRoot)\System\IO\Path.cs" />
index 419ad92..3aafe01 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.CompilerServices;
 using System.Runtime.ConstrainedExecution;
@@ -22,7 +23,7 @@ namespace Internal.Runtime.Augments
 
         private Thread AsThread()
         {
-            Contract.Assert(this is Thread);
+            Debug.Assert(this is Thread);
             return (Thread)this;
         }
 
@@ -33,7 +34,6 @@ namespace Internal.Runtime.Augments
         =========================================================================*/
         public extern bool IsAlive
         {
-            [SecuritySafeCritical]  // auto-generated
             [MethodImpl(MethodImplOptions.InternalCall)]
             get;
         }
@@ -46,18 +46,13 @@ namespace Internal.Runtime.Augments
         =========================================================================*/
         public bool IsBackground
         {
-            [SecuritySafeCritical]  // auto-generated
             get { return IsBackgroundNative(); }
-            [SecuritySafeCritical]  // auto-generated
-            [HostProtection(SelfAffectingThreading = true)]
             set { SetBackgroundNative(value); }
         }
 
-        [SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         private extern bool IsBackgroundNative();
 
-        [SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         private extern void SetBackgroundNative(bool isBackground);
 
@@ -66,7 +61,6 @@ namespace Internal.Runtime.Augments
         =========================================================================*/
         public extern bool IsThreadPoolThread
         {
-            [SecuritySafeCritical]  // auto-generated
             [MethodImpl(MethodImplOptions.InternalCall)]
             get;
         }
@@ -81,18 +75,13 @@ namespace Internal.Runtime.Augments
         =========================================================================*/
         public ThreadPriority Priority
         {
-            [SecuritySafeCritical]  // auto-generated
             get { return (ThreadPriority)GetPriorityNative(); }
-            [SecuritySafeCritical]  // auto-generated
-            [HostProtection(SelfAffectingThreading = true)]
             set { SetPriorityNative((int)value); }
         }
 
-        [SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         private extern int GetPriorityNative();
 
-        [SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         private extern void SetPriorityNative(int priority);
 
@@ -102,21 +91,18 @@ namespace Internal.Runtime.Augments
         =========================================================================*/
         public ThreadState ThreadState
         {
-            [SecuritySafeCritical]  // auto-generated
             get { return (ThreadState)GetThreadStateNative(); }
         }
 
-        [SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         private extern int GetThreadStateNative();
 
-        [SecuritySafeCritical]  // auto-generated
         public ApartmentState GetApartmentState()
         {
 #if FEATURE_COMINTEROP_APARTMENT_SUPPORT
             return (ApartmentState)GetApartmentStateNative();
 #else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
-            Contract.Assert(false); // the Thread class in CoreFX should have handled this case
+            Debug.Assert(false); // the Thread class in CoreFX should have handled this case
             return ApartmentState.MTA;
 #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
         }
@@ -125,20 +111,17 @@ namespace Internal.Runtime.Augments
         ** An unstarted thread can be marked to indicate that it will host a
         ** single-threaded or multi-threaded apartment.
         =========================================================================*/
-        [SecuritySafeCritical]  // auto-generated
-        [HostProtection(Synchronization = true, SelfAffectingThreading = true)]
         public bool TrySetApartmentState(ApartmentState state)
         {
 #if FEATURE_COMINTEROP_APARTMENT_SUPPORT
             return SetApartmentStateHelper(state, false);
 #else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
-            Contract.Assert(false); // the Thread class in CoreFX should have handled this case
+            Debug.Assert(false); // the Thread class in CoreFX should have handled this case
             return false;
 #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
         }
 
 #if FEATURE_COMINTEROP_APARTMENT_SUPPORT
-        [SecurityCritical]  // auto-generated
         internal bool SetApartmentStateHelper(ApartmentState state, bool fireMDAOnMismatch)
         {
             ApartmentState retState = (ApartmentState)SetApartmentStateNative((int)state, fireMDAOnMismatch);
@@ -156,26 +139,22 @@ namespace Internal.Runtime.Augments
             return true;
         }
 
-        [SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         internal extern int GetApartmentStateNative();
 
-        [SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         internal extern int SetApartmentStateNative(int state, bool fireMDAOnMismatch);
 #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
 
 #if FEATURE_COMINTEROP
-        [SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [MethodImpl(MethodImplOptions.InternalCall)]
         public extern void DisableComObjectEagerCleanup();
 #else // !FEATURE_COMINTEROP
-        [SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public void DisableComObjectEagerCleanup()
         {
-            Contract.Assert(false); // the Thread class in CoreFX should have handled this case
+            Debug.Assert(false); // the Thread class in CoreFX should have handled this case
         }
 #endif // FEATURE_COMINTEROP
 
@@ -184,19 +163,12 @@ namespace Internal.Runtime.Augments
         ** thread is not currently blocked in that manner, it will be interrupted
         ** when it next begins to block.
         =========================================================================*/
-#if FEATURE_CORECLR
-        [SecurityCritical] // auto-generated
-#else
-        [SecuritySafeCritical] // auto-generated
-#endif
 #pragma warning disable 618 // obsolete types: SecurityPermissionAttribute, SecurityAction
-        [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
 #pragma warning restore 618 // obsolete types: SecurityPermissionAttribute, SecurityAction
         public void Interrupt() => InterruptInternal();
 
         // Internal helper (since we can't place security demands on
         // ecalls/fcalls).
-        [SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         private extern void InterruptInternal();
 
@@ -209,15 +181,10 @@ namespace Internal.Runtime.Augments
         **             ThreadInterruptedException if the thread is interrupted while waiting.
         **             ThreadStateException if the thread has not been started yet.
         =========================================================================*/
-        [SecuritySafeCritical]
-        [HostProtection(Synchronization = true, ExternalThreading = true)]
         public void Join() => JoinInternal(Timeout.Infinite);
 
-        [SecuritySafeCritical]
-        [HostProtection(Synchronization = true, ExternalThreading = true)]
         public bool Join(int millisecondsTimeout) => JoinInternal(millisecondsTimeout);
 
-        [SecurityCritical]
         [MethodImpl(MethodImplOptions.InternalCall)]
         private extern bool JoinInternal(int millisecondsTimeout);
 
index 254b2f6..6c2c6e9 100644 (file)
@@ -73,7 +73,6 @@ namespace Microsoft.Win32 {
          * Variant and the types that CLR supports explicitly in the 
          * CLR Variant class.  
          */
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Variant ChangeType(Variant source, Type targetClass, short options, CultureInfo culture)
         {
             if (targetClass == null)
@@ -125,7 +124,6 @@ namespace Microsoft.Win32 {
 
         #region Private FCalls
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void ChangeTypeEx(ref Variant result, ref Variant source, int lcid, IntPtr typeHandle, int cvType, short flags);
 
index a8ec83f..3ee5f46 100644 (file)
@@ -17,7 +17,6 @@ namespace Microsoft.Win32 {
     //This class contains only static members and does not need to be serializable.
     [ComVisible(true)]
     public static class Registry {
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static Registry()
         { 
         }
@@ -63,17 +62,6 @@ namespace Microsoft.Win32 {
          * This is where current configuration information is stored.
          */
         public static readonly RegistryKey CurrentConfig      = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_CONFIG);
-        
-#if !FEATURE_CORECLR
-        /**
-         * Dynamic Data Root Key.
-         * 
-         * LEGACY: This is where dynamic performance data is stored on Win9X.
-         * This does not exist on NT.
-         */
-        [Obsolete("The DynData registry key only works on Win9x, which is no longer supported by the CLR.  On NT-based operating systems, use the PerformanceData registry key instead.")]
-        public static readonly RegistryKey DynData            = RegistryKey.GetBaseKey(RegistryKey.HKEY_DYN_DATA);
-#endif
 
         //
         // Following function will parse a keyName and returns the basekey for it.
@@ -81,7 +69,6 @@ namespace Microsoft.Win32 {
         // If the keyName is not valid, we will throw ArgumentException.
         // The return value shouldn't be null. 
         //
-        [System.Security.SecurityCritical]  // auto-generated
         private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subKeyName) {
             if( keyName == null) {
                 throw new ArgumentNullException(nameof(keyName));
@@ -116,11 +103,6 @@ namespace Microsoft.Win32 {
                 case "HKEY_CURRENT_CONFIG": 
                     basekey = Registry.CurrentConfig;
                     break;
-#if !FEATURE_CORECLR
-                case "HKEY_DYN_DATA": 
-                    basekey = RegistryKey.GetBaseKey(RegistryKey.HKEY_DYN_DATA);
-                    break;                    
-#endif
                 default:
                     throw new ArgumentException(Environment.GetResourceString("Arg_RegInvalidKeyName", nameof(keyName)));
             }            
@@ -133,7 +115,6 @@ namespace Microsoft.Win32 {
             return basekey;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static object GetValue(string keyName, string valueName, object defaultValue ) {
             string subKeyName;
             RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName);
@@ -154,7 +135,6 @@ namespace Microsoft.Win32 {
             SetValue(keyName, valueName, value, RegistryValueKind.Unknown);            
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void SetValue(string keyName, string valueName, object value, RegistryValueKind valueKind ) {
             string subKeyName; 
             RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName);
index dd75310..ff678f1 100644 (file)
 */
 
 
-namespace Microsoft.Win32 {
-
+namespace Microsoft.Win32
+{
     using System;
     using System.Collections;
     using System.Collections.Generic;
     using System.Security;
-#if FEATURE_MACL
-    using System.Security.AccessControl;
-#endif
     using System.Security.Permissions;
     using System.Text;
     using System.Threading;
@@ -74,7 +71,7 @@ namespace Microsoft.Win32 {
      * Registry hive values.  Useful only for GetRemoteBaseKey
      */
     [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public enum RegistryHive
     {
         ClassesRoot = unchecked((int)0x80000000),
@@ -83,9 +80,6 @@ namespace Microsoft.Win32 {
         Users = unchecked((int)0x80000003),
         PerformanceData = unchecked((int)0x80000004),
         CurrentConfig = unchecked((int)0x80000005),
-#if !FEATURE_CORECLR
-        DynData = unchecked((int)0x80000006),
-#endif
     }
 
     /**
@@ -107,9 +101,6 @@ namespace Microsoft.Win32 {
         internal static readonly IntPtr HKEY_USERS                = new IntPtr(unchecked((int)0x80000003));
         internal static readonly IntPtr HKEY_PERFORMANCE_DATA     = new IntPtr(unchecked((int)0x80000004));
         internal static readonly IntPtr HKEY_CURRENT_CONFIG       = new IntPtr(unchecked((int)0x80000005));
-#if !FEATURE_CORECLR
-        internal static readonly IntPtr HKEY_DYN_DATA             = new IntPtr(unchecked((int)0x80000006));
-#endif
 
         // Dirty indicates that we have munged data that should be potentially
         // written to disk.
@@ -137,9 +128,6 @@ namespace Microsoft.Win32 {
                 "HKEY_USERS",
                 "HKEY_PERFORMANCE_DATA",
                 "HKEY_CURRENT_CONFIG",
-#if !FEATURE_CORECLR
-                "HKEY_DYN_DATA"
-#endif
                 };
 
         // MSDN defines the following limits for registry key names & values:
@@ -149,7 +137,6 @@ namespace Microsoft.Win32 {
         private const int MaxKeyLength = 255;
         private const int MaxValueLength = 16383;
 
-        [System.Security.SecurityCritical] // auto-generated
         private volatile SafeRegistryHandle hkey = null;
         private volatile int state = 0;
         private volatile String keyName;
@@ -183,7 +170,6 @@ namespace Microsoft.Win32 {
          * This key is bound to hkey, if writable is <b>false</b> then no write operations
          * will be allowed.
          */
-        [System.Security.SecurityCritical]  // auto-generated
         private RegistryKey(SafeRegistryHandle  hkey, bool writable, RegistryView view)
             : this(hkey, writable, false, false, false, view) {
         }
@@ -198,7 +184,6 @@ namespace Microsoft.Win32 {
          * The remoteKey flag when set to true indicates that we are dealing with registry entries
          * on a remote machine and requires the program making these calls to have full trust.
          */
-        [System.Security.SecurityCritical]  // auto-generated
         private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) {
             this.hkey = hkey;
             this.keyName = "";
@@ -222,7 +207,6 @@ namespace Microsoft.Win32 {
             Dispose(true);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private void Dispose(bool disposing) {
             if (hkey != null) {
 
@@ -255,7 +239,6 @@ namespace Microsoft.Win32 {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Flush() {
             if (hkey != null) {
                  if (IsDirty()) {
@@ -264,11 +247,7 @@ namespace Microsoft.Win32 {
             }
         }
 
-#if FEATURE_CORECLR
         void IDisposable.Dispose()
-#else
-        public void Dispose()
-#endif
         {
             Dispose(true);
         }
@@ -309,22 +288,6 @@ namespace Microsoft.Win32 {
             return CreateSubKeyInternal(subkey, writable ? RegistryKeyPermissionCheck.ReadWriteSubTree : RegistryKeyPermissionCheck.ReadSubTree, null, options);
         }
 
-
-#if FEATURE_MACL
-        [ComVisible(false)]
-        public unsafe RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck,  RegistrySecurity registrySecurity) 
-        {
-            return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, RegistryOptions.None);
-        }
-        
-        [ComVisible(false)]
-        public unsafe RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck,  RegistryOptions registryOptions, RegistrySecurity registrySecurity) 
-        {
-            return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, registryOptions);
-        }        
-#endif
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ComVisible(false)]
         private unsafe RegistryKey CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions)
         {
@@ -346,23 +309,9 @@ namespace Microsoft.Win32 {
             }
 
             CheckPermission(RegistryInternalCheck.CheckSubKeyCreatePermission, subkey, false, RegistryKeyPermissionCheck.Default);      
-            
+
             Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
-#if FEATURE_MACL
-            RegistrySecurity registrySecurity = (RegistrySecurity)registrySecurityObj;
-            // For ACL's, get the security descriptor from the RegistrySecurity.
-            if (registrySecurity != null) {
-                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
-                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
-                byte[] sd = registrySecurity.GetSecurityDescriptorBinaryForm();
-                // We allocate memory on the stack to improve the speed.
-                // So this part of code can't be refactored into a method.
-                byte* pSecDescriptor = stackalloc byte[sd.Length];
-                Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
-                secAttrs.pSecurityDescriptor = pSecDescriptor;
-            }
-#endif
+
             int disposition = 0;
 
             // By default, the new key will be writable.
@@ -407,7 +356,6 @@ namespace Microsoft.Win32 {
             DeleteSubKey(subkey, true);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void DeleteSubKey(String subkey, bool throwOnMissingSubKey) {
             ValidateKeyName(subkey);        
             EnsureWriteable();
@@ -461,7 +409,6 @@ namespace Microsoft.Win32 {
             DeleteSubKeyTree(subkey, true /*throwOnMissingSubKey*/);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ComVisible(false)]
         public void DeleteSubKeyTree(String subkey, Boolean throwOnMissingSubKey) {
             ValidateKeyName(subkey);
@@ -509,7 +456,6 @@ namespace Microsoft.Win32 {
 
         // An internal version which does no security checks or argument checking.  Skipping the 
         // security checks should give us a slight perf gain on large trees. 
-        [System.Security.SecurityCritical]  // auto-generated
         private void DeleteSubKeyTreeInternal(string subkey) {
             RegistryKey key = InternalOpenSubKey(subkey, true);
             if (key != null) {
@@ -536,7 +482,7 @@ namespace Microsoft.Win32 {
                 if (ret!=0) Win32Error(ret, null);
             }
             else {
-                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);                
+                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);
             }
         }
         
@@ -549,7 +495,6 @@ namespace Microsoft.Win32 {
             DeleteValue(name, true);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void DeleteValue(String name, bool throwOnMissingValue) {
             EnsureWriteable();
             CheckPermission(RegistryInternalCheck.CheckValueWritePermission, name, false, RegistryKeyPermissionCheck.Default);            
@@ -587,12 +532,10 @@ namespace Microsoft.Win32 {
          *
          * @return the RegistryKey requested.
          */
-        [System.Security.SecurityCritical]  // auto-generated
         internal static RegistryKey GetBaseKey(IntPtr hKey) {
             return GetBaseKey(hKey, RegistryView.Default);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view) {
 
             int index = ((int)hKey) & 0x0FFFFFFF;
@@ -610,7 +553,6 @@ namespace Microsoft.Win32 {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ComVisible(false)]
         public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) {
             ValidateKeyView(view);
@@ -640,7 +582,6 @@ namespace Microsoft.Win32 {
             return OpenRemoteBaseKey(hKey, machineName, RegistryView.Default);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ComVisible(false)]
         public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, String machineName, RegistryView view) {
             if (machineName==null)
@@ -682,11 +623,6 @@ namespace Microsoft.Win32 {
          *
          * @return the Subkey requested, or <b>null</b> if the operation failed.
          */
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         public RegistryKey OpenSubKey(string name, bool writable ) {
             ValidateKeyName(name);
             EnsureNotDisposed();
@@ -717,63 +653,8 @@ namespace Microsoft.Win32 {
             return null;
         }
 
-#if FEATURE_MACL
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [ComVisible(false)]
-        public RegistryKey OpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck) { 
-            ValidateKeyMode(permissionCheck);            
-            return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck));
-        }
-
-        [System.Security.SecuritySafeCritical]
-        [ComVisible(false)]
-        public RegistryKey OpenSubKey(String name, RegistryRights rights)
-        {
-            return InternalOpenSubKey(name, this.checkMode, (int)rights);
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [ComVisible(false)]
-        public RegistryKey OpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights) {
-            return InternalOpenSubKey(name, permissionCheck, (int)rights);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private RegistryKey InternalOpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, int rights) {
-            ValidateKeyName(name);
-            ValidateKeyMode(permissionCheck);            
-
-            ValidateKeyRights(rights);
-
-            EnsureNotDisposed();
-            name = FixupName(name); // Fixup multiple slashes to a single slash
-
-            CheckPermission(RegistryInternalCheck.CheckOpenSubKeyPermission, name, false, permissionCheck);                        
-            CheckPermission(RegistryInternalCheck.CheckSubTreePermission, name, false, permissionCheck);
-            SafeRegistryHandle result = null;
-            int ret = Win32Native.RegOpenKeyEx(hkey, name, 0, (rights | (int)regView), out result);
-            if (ret == 0 && !result.IsInvalid) {
-                RegistryKey key = new RegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, remoteKey, false, regView);
-                key.keyName = keyName + "\\" + name;
-                key.checkMode = permissionCheck;
-                return key;
-            }
-
-            // Return null if we didn't find the key.
-            if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) {
-                // We need to throw SecurityException here for compatiblity reason,
-                // although UnauthorizedAccessException will make more sense.
-                ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission);                
-            }
-            
-            return null;                        
-        }    
-#endif
-
         // This required no security checks. This is to get around the Deleting SubKeys which only require
         // write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks
-        [System.Security.SecurityCritical]  // auto-generated
         internal RegistryKey InternalOpenSubKey(String name, bool writable) {
             ValidateKeyName(name);
             EnsureNotDisposed();
@@ -800,9 +681,6 @@ namespace Microsoft.Win32 {
          *
          * @return the Subkey requested, or <b>null</b> if the operation failed.
          */
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] 
-#endif
         public RegistryKey OpenSubKey(String name) {
             return OpenSubKey(name, false);
         }
@@ -813,7 +691,6 @@ namespace Microsoft.Win32 {
          * @return a count of subkeys.
          */
         public int SubKeyCount {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
                 return InternalSubKeyCount();
@@ -822,90 +699,12 @@ namespace Microsoft.Win32 {
 
         [ComVisible(false)]
         public RegistryView View {
-            [System.Security.SecuritySafeCritical]
             get {
                 EnsureNotDisposed();
                 return regView;
             }
         }
 
-#if !FEATURE_CORECLR
-        [ComVisible(false)]
-        public SafeRegistryHandle Handle {
-            [System.Security.SecurityCritical]
-            [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-            get {
-                EnsureNotDisposed();
-                int ret = Win32Native.ERROR_INVALID_HANDLE;
-                if (IsSystemKey()) {
-                    IntPtr baseKey = (IntPtr)0;
-                    switch (keyName) {
-                        case "HKEY_CLASSES_ROOT":
-                            baseKey = HKEY_CLASSES_ROOT;
-                            break;
-                        case "HKEY_CURRENT_USER":
-                            baseKey = HKEY_CURRENT_USER;
-                            break;
-                        case "HKEY_LOCAL_MACHINE":
-                            baseKey = HKEY_LOCAL_MACHINE;
-                            break;
-                        case "HKEY_USERS":
-                            baseKey = HKEY_USERS;
-                            break;
-                        case "HKEY_PERFORMANCE_DATA":
-                            baseKey = HKEY_PERFORMANCE_DATA;
-                            break;
-                        case "HKEY_CURRENT_CONFIG":
-                            baseKey = HKEY_CURRENT_CONFIG;
-                            break;
-                        case "HKEY_DYN_DATA":
-                            baseKey = HKEY_DYN_DATA;
-                            break;
-                        default:
-                            Win32Error(ret, null);
-                            break;
-                    }
-                    // open the base key so that RegistryKey.Handle will return a valid handle
-                    SafeRegistryHandle result;
-                    ret = Win32Native.RegOpenKeyEx(baseKey,
-                        null,
-                        0,
-                        GetRegistryKeyAccess(IsWritable()) | (int)regView,
-                        out result);
-
-                    if (ret == 0 && !result.IsInvalid) {
-                        return result;
-                    }
-                    else {
-                        Win32Error(ret, null);
-                    }
-                }
-                else {
-                    return hkey;
-                }
-                throw new IOException(Win32Native.GetMessage(ret), ret);
-            }
-        }
-
-        [System.Security.SecurityCritical]
-        [ComVisible(false)]
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-        public static RegistryKey FromHandle(SafeRegistryHandle handle) {
-            return FromHandle(handle, RegistryView.Default);
-        }
-
-        [System.Security.SecurityCritical]
-        [ComVisible(false)]
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-        public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view) {
-            if (handle == null) throw new ArgumentNullException(nameof(handle));
-            ValidateKeyView(view);
-
-            return new RegistryKey(handle, true /* isWritable */, view);
-        }
-#endif
-
-        [System.Security.SecurityCritical]  // auto-generated
         internal int InternalSubKeyCount() {
                 EnsureNotDisposed();
 
@@ -934,17 +733,11 @@ namespace Microsoft.Win32 {
          *
          * @return all subkey names.
          */
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         public String[] GetSubKeyNames() {
             CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
             return InternalGetSubKeyNames();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe String[] InternalGetSubKeyNames() {
             EnsureNotDisposed();
             int subkeys = InternalSubKeyCount();
@@ -983,14 +776,12 @@ namespace Microsoft.Win32 {
          * @return a count of values.
          */
         public int ValueCount {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
                 return InternalValueCount();
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal int InternalValueCount() {
             EnsureNotDisposed();
             int values = 0;
@@ -1017,7 +808,6 @@ namespace Microsoft.Win32 {
          *
          * @return all value names.
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe String[] GetValueNames() {
             CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
             EnsureNotDisposed();
@@ -1068,7 +858,6 @@ namespace Microsoft.Win32 {
          *
          * @return the data associated with the value.
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Object GetValue(String name) {
             CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);        
             return InternalGetValue(name, null, false, true);
@@ -1089,21 +878,11 @@ namespace Microsoft.Win32 {
          *
          * @return the data associated with the value.
          */
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         public Object GetValue(String name, Object defaultValue) {
             CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);        
             return InternalGetValue(name, defaultValue, false, true);
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         [ComVisible(false)]
         public Object GetValue(String name, Object defaultValue, RegistryValueOptions options) {
             if( options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) {
@@ -1114,7 +893,6 @@ namespace Microsoft.Win32 {
             return InternalGetValue(name, defaultValue, doNotExpand, true);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal Object InternalGetValue(String name, Object defaultValue, bool doNotExpand, bool checkSecurity) {            
             if (checkSecurity) {       
                 // Name can be null!  It's the most common use of RegQueryValueEx
@@ -1333,7 +1111,6 @@ namespace Microsoft.Win32 {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ComVisible(false)]
         public RegistryValueKind GetValueKind(string name) {
             CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
@@ -1377,7 +1154,6 @@ namespace Microsoft.Win32 {
         }
 
         public String Name {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { 
                 EnsureNotDisposed();
                 return keyName; 
@@ -1398,7 +1174,6 @@ namespace Microsoft.Win32 {
             SetValue(name, value, RegistryValueKind.Unknown);
         }
 
-        [System.Security.SecuritySafeCritical] //auto-generated
         [ComVisible(false)]
         public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind) {
             if (value==null)
@@ -1570,33 +1345,11 @@ namespace Microsoft.Win32 {
          *
          * @return a string representing the key.
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             EnsureNotDisposed();
             return keyName;
         }
 
-#if FEATURE_MACL
-        public RegistrySecurity GetAccessControl() {
-            return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public RegistrySecurity GetAccessControl(AccessControlSections includeSections) {
-            EnsureNotDisposed();
-            return new RegistrySecurity(hkey, keyName, includeSections);
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public void SetAccessControl(RegistrySecurity registrySecurity) {
-            EnsureWriteable();
-            if (registrySecurity == null)
-                throw new ArgumentNullException(nameof(registrySecurity));
-
-            registrySecurity.Persist(hkey, keyName);
-        }
-#endif
-
         /**
          * After calling GetLastWin32Error(), it clears the last error field,
          * so you must save the HResult and pass it to this method.  This method
@@ -1604,7 +1357,6 @@ namespace Microsoft.Win32 {
          * error, and depending on the error, insert a string into the message
          * gotten from the ResourceManager.
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal void Win32Error(int errorCode, String str) {
             switch (errorCode) {
                 case Win32Native.ERROR_ACCESS_DENIED:
@@ -1640,7 +1392,6 @@ namespace Microsoft.Win32 {
             }
         }
 
-        [SecuritySafeCritical]
         internal static void Win32ErrorStatic(int errorCode, String str) {
             switch (errorCode) {
                 case Win32Native.ERROR_ACCESS_DENIED:
@@ -1773,18 +1524,12 @@ namespace Microsoft.Win32 {
            path   = keyName + "\\.";
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
-        private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck) {
+        private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck)
+        {
             bool demand = false;
             RegistryPermissionAccess access = RegistryPermissionAccess.NoAccess;
             string path = null;
 
-#if !FEATURE_CORECLR
-            if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) {
-                return; // full trust fast path
-            }
-#endif // !FEATURE_CORECLR
-    
             switch (check) {
                 //
                 // Read/Write/Create SubKey Permission
@@ -2015,14 +1760,12 @@ namespace Microsoft.Win32 {
             }
         }
      
-        [System.Security.SecurityCritical]  // auto-generated
         static private void  CheckUnmanagedCodePermission() {               
 #pragma warning disable 618
             new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();        
 #pragma warning restore 618
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private bool ContainsRegistryValue(string name) {
                 int type = 0;
                 int datasize = 0;
@@ -2030,14 +1773,12 @@ namespace Microsoft.Win32 {
                 return retval == 0;            
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void EnsureNotDisposed(){
             if (hkey == null) {
                 ThrowHelper.ThrowObjectDisposedException(keyName, ExceptionResource.ObjectDisposed_RegKeyClosed);
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void EnsureWriteable() {
             EnsureNotDisposed();
             if (!IsWritable()) {
@@ -2129,16 +1870,6 @@ namespace Microsoft.Win32 {
             }
         }
 
-
-#if FEATURE_MACL
-        static private void ValidateKeyRights(int rights) {
-            if(0 != (rights & ~((int)RegistryRights.FullControl))) {
-                // We need to throw SecurityException here for compatiblity reason,
-                // although UnauthorizedAccessException will make more sense.
-                ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission);           
-            }            
-        }
-#endif
         // Win32 constants for error handling
         private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
         private const int FORMAT_MESSAGE_FROM_SYSTEM    = 0x00001000;
index 5e1b510..cb915fe 100644 (file)
@@ -20,20 +20,16 @@ using System.Runtime.Versioning;
 
 namespace Microsoft.Win32.SafeHandles
 {
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
-        [System.Security.SecurityCritical]  // auto-generated_required
         internal SafeFileMappingHandle() : base(true) {}
 
         // 0 is an Invalid Handle
-        [System.Security.SecurityCritical]  // auto-generated_required
         internal SafeFileMappingHandle(IntPtr handle, bool ownsHandle) : base (ownsHandle)
         {
             SetHandle(handle);
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return Win32Native.CloseHandle(handle);
index b24535f..219fb77 100644 (file)
@@ -20,13 +20,10 @@ using System.Runtime.ConstrainedExecution;
 using Microsoft.Win32;
 
 namespace Microsoft.Win32.SafeHandles {
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
-        [System.Security.SecurityCritical]  // auto-generated_required
         internal SafeFindHandle() : base(true) {}
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return Win32Native.FindClose(handle);
index d2ea42b..2363198 100644 (file)
@@ -3,24 +3,12 @@
 // See the LICENSE file in the project root for more information.
 
 namespace Microsoft.Win32 {
-    using Microsoft.Win32;
     using Microsoft.Win32.SafeHandles;
-    using System;
-    using System.Runtime.CompilerServices;
-    using System.Runtime.ConstrainedExecution;
-    using System.Runtime.InteropServices;
-    using System.Runtime.Serialization;
-    using System.Runtime.Versioning;
-    using System.Security;
     using System.Security.Permissions;
-    using System.Text;
 
-    [System.Security.SecurityCritical]  // auto-generated
-    [HostProtectionAttribute(MayLeakOnAbort = true)]
     sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid {
         internal SafeLibraryHandle() : base(true) {}
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return UnsafeNativeMethods.FreeLibrary(handle);
index 3eea2b9..d6c1577 100644 (file)
@@ -1,13 +1,14 @@
 // 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 Microsoft.Win32.SafeHandles {
+
+namespace Microsoft.Win32.SafeHandles
+{
     using System;
     using System.Runtime.CompilerServices;
     using System.Runtime.InteropServices;
     using System.Runtime.ConstrainedExecution;
 
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeLocalAllocHandle : SafeBuffer {
         private SafeLocalAllocHandle () : base(true) {}
 
@@ -20,7 +21,6 @@ namespace Microsoft.Win32.SafeHandles {
             get { return new SafeLocalAllocHandle(IntPtr.Zero); }
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return Win32Native.LocalFree(handle) == IntPtr.Zero;
index d0e3f04..4f96b81 100644 (file)
@@ -17,17 +17,13 @@ namespace Microsoft.Win32.SafeHandles {
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
 
-    [System.Security.SecurityCritical]
     public sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid {
-        [System.Security.SecurityCritical]
         internal SafeRegistryHandle() : base(true) {}
 
-        [System.Security.SecurityCritical]
         public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
             SetHandle(preexistingHandle);
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle() {
             return (RegCloseKey(handle) == Win32Native.ERROR_SUCCESS);
         }
index 01ec4d2..38a9323 100644 (file)
@@ -22,19 +22,15 @@ using Microsoft.Win32.SafeHandles;
 
 namespace Microsoft.Win32.SafeHandles
 {
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeViewOfFileHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
-        [System.Security.SecurityCritical]  // auto-generated_required
         internal SafeViewOfFileHandle() : base(true) {}
 
         // 0 is an Invalid Handle
-        [System.Security.SecurityCritical]  // auto-generated_required
         internal SafeViewOfFileHandle(IntPtr handle, bool ownsHandle) : base (ownsHandle) {
             SetHandle(handle);
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             if (Win32Native.UnmapViewOfFile(handle))
index fa24c96..0e57136 100644 (file)
@@ -24,7 +24,6 @@ using System.Threading;
 
 namespace Microsoft.Win32.SafeHandles {
  
-    [System.Security.SecurityCritical]  // auto-generated_required
     public sealed class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
         // Called by P/Invoke marshaler
@@ -38,7 +37,6 @@ namespace Microsoft.Win32.SafeHandles {
             SetHandle(existingHandle);
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return Win32Native.CloseHandle(handle);
index 6f7dddf..08ae095 100644 (file)
@@ -22,10 +22,6 @@ namespace Microsoft.Win32.SafeHandles
     using System.Runtime.ConstrainedExecution;
 
     // Class of safe handle which uses 0 or -1 as an invalid handle.
-    [System.Security.SecurityCritical]  // auto-generated_required
-#if !FEATURE_CORECLR
-    [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
     public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle
     {
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
@@ -33,25 +29,18 @@ namespace Microsoft.Win32.SafeHandles
         {
         }
 
-#if FEATURE_CORECLR
         // A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime
         protected SafeHandleZeroOrMinusOneIsInvalid()
         {
             throw new NotImplementedException();
         }
-#endif // FEATURE_CORECLR
 
         public override bool IsInvalid {
-            [System.Security.SecurityCritical]
             get { return handle.IsNull() || handle == new IntPtr(-1); }
         }
     }
 
     // Class of safe handle which uses only -1 as an invalid handle.
-    [System.Security.SecurityCritical]  // auto-generated_required
-#if !FEATURE_CORECLR
-    [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
     public abstract class SafeHandleMinusOneIsInvalid : SafeHandle
     {
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
@@ -59,25 +48,18 @@ namespace Microsoft.Win32.SafeHandles
         {
         }
 
-#if FEATURE_CORECLR
         // A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime
         protected SafeHandleMinusOneIsInvalid()
         {
             throw new NotImplementedException();
         }
-#endif // FEATURE_CORECLR
 
         public override bool IsInvalid {
-            [System.Security.SecurityCritical]
             get { return handle == new IntPtr(-1); }
         }
     }
 
     // Class of critical handle which uses 0 or -1 as an invalid handle.
-    [System.Security.SecurityCritical]  // auto-generated_required
-#if !FEATURE_CORECLR
-    [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
     public abstract class CriticalHandleZeroOrMinusOneIsInvalid : CriticalHandle
     {
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
@@ -86,16 +68,11 @@ namespace Microsoft.Win32.SafeHandles
         }
 
         public override bool IsInvalid {
-            [System.Security.SecurityCritical]
             get { return handle.IsNull() || handle == new IntPtr(-1); }
         }
     }
 
     // Class of critical handle which uses only -1 as an invalid handle.
-    [System.Security.SecurityCritical]  // auto-generated_required
-#if !FEATURE_CORECLR
-    [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
     public abstract class CriticalHandleMinusOneIsInvalid : CriticalHandle
     {
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
@@ -104,7 +81,6 @@ namespace Microsoft.Win32.SafeHandles
         }
 
         public override bool IsInvalid {
-            [System.Security.SecurityCritical]
             get { return handle == new IntPtr(-1); }
         }
     }
index 9da9811..19d638d 100644 (file)
@@ -16,7 +16,6 @@ namespace Microsoft.Win32 {
     using System.Text;
     using System.Diagnostics.Tracing;
 
-    [System.Security.SecurityCritical]  // auto-generated
     [SuppressUnmanagedCodeSecurityAttribute()]
     internal static class UnsafeNativeMethods {
 
@@ -64,7 +63,6 @@ namespace Microsoft.Win32 {
         internal static extern bool FreeLibrary(IntPtr hModule);
 
 
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurityAttribute()]
         internal static unsafe class ManifestEtw
         {
@@ -96,7 +94,6 @@ namespace Microsoft.Win32 {
             //
             // Callback
             //
-            [SecurityCritical]
             internal unsafe delegate void EtwEnableCallback(
                 [In] ref Guid sourceId,
                 [In] int isEnabled,
@@ -110,7 +107,6 @@ namespace Microsoft.Win32 {
             //
             // Registration APIs
             //
-            [SecurityCritical]
             [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
             internal static extern unsafe uint EventRegister(
                         [In] ref Guid providerId,
@@ -120,7 +116,6 @@ namespace Microsoft.Win32 {
                         );
 
             // 
-            [SecurityCritical]
             [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
             [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
             internal static extern uint EventUnregister([In] long registrationHandle);
@@ -129,7 +124,6 @@ namespace Microsoft.Win32 {
             // Writing (Publishing/Logging) APIs
             //
             // 
-            [SecurityCritical]
             [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
             [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
             internal static extern unsafe int EventWrite(
@@ -139,7 +133,6 @@ namespace Microsoft.Win32 {
                     [In] EventProvider.EventData* userData
                     );
 
-            [SecurityCritical]
             [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
             [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
             internal static extern unsafe int EventWriteString(
@@ -270,7 +263,6 @@ namespace Microsoft.Win32 {
 
         }
 #if FEATURE_COMINTEROP
-        [SecurityCritical]
         [DllImport("combase.dll", PreserveSig = true)]
         internal static extern int RoGetActivationFactory(
             [MarshalAs(UnmanagedType.HString)] string activatableClassId,
index 98ee8ff..b5b808b 100644 (file)
@@ -110,7 +110,6 @@ namespace Microsoft.Win32 {
     // Remove the default demands for all P/Invoke methods with this
     // global declaration on the class.
 
-    [System.Security.SecurityCritical]
     [SuppressUnmanagedCodeSecurityAttribute()]
     internal static class Win32Native {
 
@@ -451,7 +450,6 @@ namespace Microsoft.Win32 {
             internal int fileSizeHigh;
             internal int fileSizeLow;
 
-            [System.Security.SecurityCritical]
             internal void PopulateFrom(WIN32_FIND_DATA findData) {
                 // Copy the information to data
                 fileAttributes = findData.dwFileAttributes; 
@@ -513,7 +511,6 @@ namespace Microsoft.Win32 {
             ///     strings created with this version of the constructor will be unsafe to use after the buffer
             ///     has been freed.
             /// </remarks>
-            [System.Security.SecurityCritical]  // auto-generated
             internal UNICODE_INTPTR_STRING (int stringBytes, SafeLocalAllocHandle buffer) {
                 BCLDebug.Assert(buffer == null || (stringBytes >= 0 && (ulong)stringBytes <= buffer.ByteLength),
                                 "buffer == null || (stringBytes >= 0 && stringBytes <= buffer.ByteLength)");
@@ -799,7 +796,6 @@ namespace Microsoft.Win32 {
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private static extern IntPtr GetModuleHandle(String moduleName);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool DoesWin32MethodExist(String moduleName, String methodName)
         {
             // GetModuleHandle does not increment the module's ref count, so we don't need to call FreeLibrary.
@@ -907,58 +903,6 @@ namespace Microsoft.Win32 {
         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
         internal static extern uint GetLongPathNameW(string lpszShortPath, SafeHandle lpszLongPath, uint cchBuffer);
 
-#if !FEATURE_CORECLR
-        // Disallow access to all non-file devices from methods that take
-        // a String.  This disallows DOS devices like "con:", "com1:", 
-        // "lpt1:", etc.  Use this to avoid security problems, like allowing
-        // a web client asking a server for "http://server/com1.aspx" and
-        // then causing a worker process to hang.
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static SafeFileHandle SafeCreateFile(String lpFileName,
-                    int dwDesiredAccess, System.IO.FileShare dwShareMode,
-                    SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
-                    int dwFlagsAndAttributes, IntPtr hTemplateFile)
-        {
-            SafeFileHandle handle = CreateFile( lpFileName, dwDesiredAccess, dwShareMode,
-                                securityAttrs, dwCreationDisposition,
-                                dwFlagsAndAttributes, hTemplateFile );
-
-            if (!handle.IsInvalid)
-            {
-                int fileType = Win32Native.GetFileType(handle);
-                if (fileType != Win32Native.FILE_TYPE_DISK) {
-                    handle.Dispose();
-                    throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"));
-                }
-            }
-
-            return handle;
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static SafeFileHandle UnsafeCreateFile(String lpFileName,
-                    int dwDesiredAccess, System.IO.FileShare dwShareMode,
-                    SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
-                    int dwFlagsAndAttributes, IntPtr hTemplateFile)
-        {
-            SafeFileHandle handle = CreateFile( lpFileName, dwDesiredAccess, dwShareMode,
-                                securityAttrs, dwCreationDisposition,
-                                dwFlagsAndAttributes, hTemplateFile );
-
-            return handle;
-        }
-
-        // Do not use these directly, use the safe or unsafe versions above.
-        // The safe version does not support devices (aka if will only open
-        // files on disk), while the unsafe version give you the full semantic
-        // of the native version.
-        [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
-        private static extern SafeFileHandle CreateFile(String lpFileName,
-                    int dwDesiredAccess, System.IO.FileShare dwShareMode,
-                    SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
-                    int dwFlagsAndAttributes, IntPtr hTemplateFile);
-#endif
-
         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
         internal static extern SafeFileMappingHandle CreateFileMapping(SafeFileHandle hFile, IntPtr lpAttributes, uint fProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, String lpName);
 
@@ -987,7 +931,6 @@ namespace Microsoft.Win32 {
         [DllImport(KERNEL32, SetLastError=true, EntryPoint="SetFilePointer")]
         private unsafe static extern int SetFilePointerWin32(SafeFileHandle handle, int lo, int * hi, int origin);
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static long SetFilePointer(SafeFileHandle handle, long offset, System.IO.SeekOrigin origin, out int hr) {
             hr = 0;
             int lo = (int) offset;
@@ -1794,18 +1737,11 @@ namespace Microsoft.Win32 {
             [In]     uint       dwFlags);
 #endif // FEATURE_LEGACYSURFACE
 
-#if FEATURE_CORECLR 
         [DllImport(NTDLL, CharSet=CharSet.Unicode, SetLastError=true)]
         internal static extern
         int RtlNtStatusToDosError (
             [In]    int         status);
-#else
-        // identical to RtlNtStatusToDosError, but we are in ask mode for desktop CLR
-        [DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)]
-        internal static extern
-        int LsaNtStatusToWinError (
-            [In]    int         status);
-#endif
+
         // Get the current FIPS policy setting on Vista and above
         [DllImport("bcrypt.dll")]
         internal static extern uint BCryptGetFipsAlgorithmMode(
@@ -2352,7 +2288,6 @@ namespace Microsoft.Win32 {
             byte[] dacl,
             byte[] sacl );
 
-#if FEATURE_CORECLR
         [DllImport(KERNEL32, CharSet=CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurityAttribute()]
         internal  unsafe static extern int WideCharToMultiByte(
@@ -2374,13 +2309,11 @@ namespace Microsoft.Win32 {
             int      cchMultiByte,
             char*  lpWideCharStr,
             int      cchWideChar);
-#endif  // FEATURE_CORECLR
 
         [DllImport(KERNEL32, SetLastError = true)]
         [return: MarshalAs(UnmanagedType.Bool)]
         internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime);
 
-#if FEATURE_CORECLR
 #if FEATURE_PAL
         [DllImport(KERNEL32, EntryPoint = "PAL_Random")]
         internal extern static bool Random(bool bStrong,
@@ -2407,6 +2340,5 @@ namespace Microsoft.Win32 {
             }
         }
 #endif
-#endif
     }
 }
index bad4a0d..cf17dae 100644 (file)
@@ -49,10 +49,6 @@ ArgumentOutOfRange_ActualValue = Actual value was {0}.
 NoDebugResources = [{0}]\r\nArguments: {1}\r\nDebugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version={2}&File={3}&Key={4}
 #endif // INCLUDE_RUNTIME
 
-#if !FEATURE_CORECLR
-UnknownError = Unknown error.
-#endif // !FEATURE_CORECLR
-
 #if INCLUDE_DEBUG
 
 ; For code contracts
@@ -70,25 +66,6 @@ InvariantFailed = Invariant failed.
 InvariantFailed_Cnd = Invariant failed: {0}
 MustUseCCRewrite = An assembly (probably "{1}") must be rewritten using the code contracts binary rewriter (CCRewrite) because it is calling Contract.{0} and the CONTRACTS_FULL symbol is defined.  Remove any explicit definitions of the CONTRACTS_FULL symbol from your project and rebuild.  CCRewrite can be downloaded from http://go.microsoft.com/fwlink/?LinkID=169180. \r\nAfter the rewriter is installed, it can be enabled in Visual Studio from the project's Properties page on the Code Contracts pane.  Ensure that "Perform Runtime Contract Checking" is enabled, which will define CONTRACTS_FULL.
 
-; Access Control
-#if FEATURE_MACL
-AccessControl_MustSpecifyContainerAcl = The named parameter must be a container ACL.
-AccessControl_MustSpecifyLeafObjectAcl = The named parameter must be a non-container ACL.
-AccessControl_AclTooLong = Length of the access control list exceed the allowed maximum.
-AccessControl_MustSpecifyDirectoryObjectAcl = The named parameter must be a directory-object ACL.
-AccessControl_MustSpecifyNonDirectoryObjectAcl = The named parameter must be a non-directory-object ACL.
-AccessControl_InvalidSecurityDescriptorRevision = Security descriptor with revision other than '1' are not legal.
-AccessControl_InvalidSecurityDescriptorSelfRelativeForm = Security descriptor must be in the self-relative form.
-AccessControl_NoAssociatedSecurity = Unable to perform a security operation on an object that has no associated security. This can happen when trying to get an ACL of an anonymous kernel object.
-AccessControl_InvalidHandle = The supplied handle is invalid. This can happen when trying to set an ACL on an anonymous kernel object.
-AccessControl_UnexpectedError = Method failed with unexpected error code {0}.
-AccessControl_InvalidSidInSDDLString = The SDDL string contains an invalid sid or a sid that cannot be translated.
-AccessControl_InvalidOwner = The security identifier is not allowed to be the owner of this object.
-AccessControl_InvalidGroup = The security identifier is not allowed to be the primary group of this object.
-AccessControl_InvalidAccessRuleType = The access rule is not the correct type.
-AccessControl_InvalidAuditRuleType = The audit rule is not the correct type.
-#endif  // FEATURE_MACL
-
 ; Identity Reference Library
 #if FEATURE_IDENTITY_REFERENCE
 IdentityReference_IdentityNotMapped = Some or all identity references could not be translated.
@@ -121,9 +98,7 @@ Access_Void = Cannot create an instance of void.
 Arg_TypedReference_Null = The TypedReference must be initialized.
 Argument_AddingDuplicate__ = Item has already been added. Key in dictionary: '{0}'  Key being added: '{1}'
 Argument_AddingDuplicate = An item with the same key has already been added.
-#if FEATURE_CORECLR
 Argument_AddingDuplicateWithKey = An item with the same key has already been added. Key: {0}
-#endif // FEATURE_CORECLR
 Argument_MethodDeclaringTypeGenericLcg = Method '{0}' has a generic declaring type '{1}'. Explicitly provide the declaring type to GetTokenFor. 
 Argument_MethodDeclaringTypeGeneric = Cannot resolve method {0} because the declaring type of the method handle {1} is generic. Explicitly provide the declaring type to GetMethodFromHandle. 
 Argument_FieldDeclaringTypeGeneric = Cannot resolve field {0} because the declaring type of the field handle {1} is generic. Explicitly provide the declaring type to GetFieldFromHandle.
@@ -617,6 +592,7 @@ Argument_NativeOverlappedAlreadyFree = 'overlapped' has already been freed.
 Argument_AlreadyBoundOrSyncHandle = 'handle' has already been bound to the thread pool, or was not opened for asynchronous I/O.
 #if FEATURE_SPAN_OF_T
 Argument_InvalidTypeWithPointersNotSupported = Cannot use type '{0}'. Only value types without pointers or references are supported.
+Argument_DestinationTooShort = Destination is too short.
 #endif // FEATURE_SPAN_OF_T
 
 ;
@@ -1128,9 +1104,6 @@ InvalidOperation_EnumFailedVersion = Collection was modified; enumeration operat
 InvalidOperation_EnumNotStarted = Enumeration has not started. Call MoveNext.
 InvalidOperation_EnumOpCantHappen = Enumeration has either not started or has already finished.
 InvalidOperation_ModifyRONumFmtInfo = Unable to modify a read-only NumberFormatInfo object.
-#if FEATURE_CAS_POLICY
-InvalidOperation_ModifyROPermSet = ReadOnlyPermissionSet objects may not be modified.
-#endif // FEATURE_CAS_POLICY
 InvalidOperation_MustBeSameThread = This operation must take place on the same thread on which the object was created.
 InvalidOperation_MustRevertPrivilege = Must revert the privilege prior to attempting this operation.
 InvalidOperation_ReadOnly = Instance is read-only.
@@ -1441,12 +1414,6 @@ NotSupported_NonBlittableTypes = Non-blittable parameter types are not supported
 NotSupported_UserDllImport = DllImport cannot be used on user-defined methods.
 NotSupported_UserCOM = COM Interop is not supported for user-defined types.
 #endif //FEATURE_WINDOWSPHONE
-#if FEATURE_CAS_POLICY
-NotSupported_RequiresCasPolicyExplicit = This method explicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570 for more information.
-NotSupported_RequiresCasPolicyImplicit = This method implicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570 for more information.
-NotSupported_CasDeny = The Deny stack modifier has been obsoleted by the .NET Framework.  Please see http://go.microsoft.com/fwlink/?LinkId=155571 for more information.
-NotSupported_SecurityContextSourceAppDomainInHeterogenous = SecurityContextSource.CurrentAppDomain is not supported in heterogenous AppDomains.
-#endif // FEATURE_CAS_POLICY
 #if FEATURE_APPX
 NotSupported_AppX = {0} is not supported in AppX.
 LoadOfFxAssemblyNotSupported_AppX = {0} of .NET Framework assemblies is not supported in AppX.
@@ -1456,9 +1423,6 @@ NotSupported_WinRT_PartialTrust = Windows Runtime is not supported in partial tr
 #endif // FEATURE_COMINTEROP
 ; ReflectionTypeLoadException
 ReflectionTypeLoad_LoadFailed = Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
-#if !FEATURE_CORECLR
-NotSupported_NoTypeInfo = Cannot resolve {0} to a TypeInfo object.
-#endif
 #if FEATURE_COMINTEROP
 NotSupported_PIAInAppxProcess = A Primary Interop Assembly is not supported in AppX.
 #endif
@@ -1468,6 +1432,10 @@ NotSupported_WindowsPhone = {0} is not supported.
 NotSupported_AssemblyLoadCodeBase = Assembly.Load with a Codebase is not supported.
 NotSupported_AssemblyLoadFromHash = Assembly.LoadFrom with hashValue is not supported.
 #endif
+#if FEATURE_SPAN_OF_T
+NotSupported_CannotCallEqualsOnSpan = Equals() on Span and ReadOnlySpan is not supported. Use operator== instead.
+NotSupported_CannotCallGetHashCodeOnSpan = GetHashCode() on Span and ReadOnlySpan is not supported.
+#endif // FEATURE_SPAN_OF_T
 
 ; TypeLoadException
 TypeLoad_ResolveType = Could not resolve type '{0}'.
@@ -1580,125 +1548,6 @@ Remoting_Message_BadRetValOrOutArg = Bad return value or out-argument inside the
 Remoting_NonPublicOrStaticCantBeCalledRemotely = Permission denied: cannot call non-public or static methods remotely.
 Remoting_Proxy_ProxyTypeIsNotMBR = classToProxy argument must derive from MarshalByRef type.
 Remoting_TP_NonNull = The transparent proxy field of a real proxy must be null.
-#if FEATURE_REMOTING
-Remoting_Activation_BadAttribute = Activation attribute does not implement the IContextAttribute interface.
-Remoting_Activation_BadObject = Proxy Attribute returned an incompatible object when constructing an instance of type {0}.
-Remoting_Activation_MBR_ProxyAttribute = Proxy Attributes are supported on ContextBound types only.
-Remoting_Activation_ConnectFailed = An attempt to connect to the remote activator failed with exception '{0}'.
-Remoting_Activation_Failed = Activation failed due to an unknown reason.
-Remoting_Activation_InconsistentState = Inconsistent state during activation; there may be two proxies for the same object.
-Remoting_Activation_MissingRemoteAppEntry = Cannot find an entry for remote application '{0}'.
-Remoting_Activation_NullReturnValue = Return value of construction call was null.
-Remoting_Activation_NullFromInternalUnmarshal = InternalUnmarshal of returned ObjRef from activation call returned null.
-Remoting_Activation_WellKnownCTOR = Cannot run a non-default constructor when connecting to well-known objects.
-Remoting_Activation_PermissionDenied = Type '{0}' is not registered for activation.
-Remoting_Activation_PropertyUnhappy = A context property did not approve the candidate context for activating the object.
-Remoting_Activation_AsyncUnsupported = Async Activation not supported.
-Remoting_AmbiguousCTOR = Cannot resolve the invocation to the correct constructor.
-Remoting_AmbiguousMethod = Cannot resolve the invocation to the correct method.
-Remoting_AppDomains_NYI = This feature is not yet supported for cross-application domain.
-Remoting_AppDomainsCantBeCalledRemotely = Permission denied: cannot call methods on the AppDomain class remotely.
-Remoting_AssemblyLoadFailed = Cannot load assembly '{0}'.
-Remoting_Attribute_UseAttributeNotsettable = UseAttribute not allowed in SoapTypeAttribute.
-Remoting_BadType = Cannot load type '{0}'.
-Remoting_BadField = Remoting cannot find field '{0}' on type '{1}'.
-Remoting_BadInternalState_ActivationFailure = Invalid internal state: Activation service failed to initialize.
-Remoting_BadInternalState_ProxySameAppDomain = Invalid internal state: A marshal by ref object should not have a proxy in its own AppDomain.
-Remoting_BadInternalState_FailEnvoySink = Invalid internal state: Failed to create an envoy sink for the object.
-Remoting_CantDisconnectClientProxy = Cannot call disconnect on a proxy.
-Remoting_CantInvokeIRemoteDispatch = Cannot invoke methods on IRemoteDispatch.
-Remoting_ChannelNameAlreadyRegistered = The channel '{0}' is already registered.
-Remoting_ChannelNotRegistered = The channel '{0}' is not registered with remoting services.
-Remoting_Channel_PopOnEmptySinkStack = Tried to pop data from an empty channel sink stack.
-Remoting_Channel_PopFromSinkStackWithoutPush = A channel sink tried to pop data from the stack without first pushing data onto the stack.
-Remoting_Channel_StoreOnEmptySinkStack = A channel sink called the Store method when the sink stack was empty.
-Remoting_Channel_StoreOnSinkStackWithoutPush = A channel sink called the Store method on the sink stack without first pushing data onto the stack.
-Remoting_Channel_CantCallAPRWhenStackEmpty = Cannot call the AsyncProcessResponse method on the previous channel sink because the stack is empty.
-Remoting_Channel_CantCallFRSWhenStackEmtpy = Called FlipRememberedStack() when stack was not null.
-Remoting_Channel_CantCallGetResponseStreamWhenStackEmpty = Cannot call the GetResponseStream method on the previous channel sink because the stack is empty.
-Remoting_Channel_DispatchSinkMessageMissing = No message was deserialized prior to calling the DispatchChannelSink.
-Remoting_Channel_DispatchSinkWantsNullRequestStream = The request stream should be null when the DispatchChannelSink is called. 
-Remoting_Channel_CannotBeSecured = Channel {0} cannot be secured. Please consider using a channel that implements ISecurableChannel
-Remoting_Config_ChannelMissingCtor = To be used from a .config file, the channel type '{0}' must have a constructor of the form '{1}'
-Remoting_Config_SinkProviderMissingCtor = To be used from a .config file, the sink provider type '{0}' must have a constructor of the form '{1}'
-Remoting_Config_SinkProviderNotFormatter = A sink provider of type '{0}' is incorrectly labeled as a 'formatter'.
-Remoting_Config_ConfigurationFailure = Remoting configuration failed with the exception '{0}'.
-Remoting_Config_InvalidTimeFormat = Invalid time format '{0}'. Examples of valid time formats include 7D, 10H, 5M, 30S, or 20MS.
-Remoting_Config_AppNameSet = The remoting application name, '{0}', had already been set.
-Remoting_Config_ErrorsModeSet = The remoting custom errors mode had already been set.
-Remoting_Config_CantRedirectActivationOfWellKnownService = Attempt to redirect activation for type '{0}, {1}'. This is not allowed since either a well-known service type has already been registered with that type or that type has been registered has a activated service type.
-Remoting_Config_CantUseRedirectedTypeForWellKnownService = Attempt to register a well-known or activated service type of type '{0}, {1}'. This is not allowed since the type has already been redirected to activate elsewhere.
-Remoting_Config_InvalidChannelType = '{0}' does not implement IChannelReceiver or IChannelSender. All channels must implement one of these interfaces.
-Remoting_Config_InvalidSinkProviderType = Unable to use '{0}' as a channel sink provider. It does not implement '{1}'.
-Remoting_Config_MissingWellKnownModeAttribute = Well-known service entries must contain a 'mode' attribute with a value of 'Singleton' or 'SingleCall'.
-Remoting_Config_MissingTypeAttribute = '{0}' entries must contain a '{1}' attribute of the form 'typeName, assemblyName'.
-Remoting_Config_MissingXmlTypeAttribute = '{0}' entries must contain a '{1}' attribute of the form 'xmlTypeName, xmlTypeNamespace'.
-Remoting_Config_NoAppName = Improper remoting configuration: missing ApplicationName property.
-Remoting_Config_NonTemplateIdAttribute = Only '{0}' templates can have an 'id' attribute.
-Remoting_Config_PreloadRequiresTypeOrAssembly = Preload entries require a type or assembly attribute.
-Remoting_Config_ProviderNeedsElementName = Sink providers must have an element name of 'formatter' or 'provider'.
-Remoting_Config_RequiredXmlAttribute = '{0}' entries require a '{1}' attribute.
-Remoting_Config_ReadFailure = .Config file '{0}' cannot be read successfully due to exception '{1}'.
-Remoting_Config_NodeMustBeUnique = There can be only one '{0}' node in the '{1}' section of a config file.
-Remoting_Config_TemplateCannotReferenceTemplate = A '{0}' template cannot reference another '{0}' template.
-Remoting_Config_TypeAlreadyRedirected = Attempt to redirect activation of type '{0}, {1}' which is already redirected.
-Remoting_Config_UnknownValue = Unknown value {1} was found on the {0} node.
-Remoting_Config_UnableToResolveTemplate = Cannot resolve '{0}' template reference: '{1}'.
-Remoting_Config_VersionPresent = Version information is present in the assembly name '{0}' which is not allowed for '{1}' entries.
-Remoting_Contexts_BadProperty = A property that contributed a bad sink to the chain was found.
-Remoting_Contexts_NoProperty = A property with the name '{0}' was not found.
-Remoting_Contexts_ContextNotFrozenForCallBack = Context should be frozen before calling the DoCallBack method.
-Remoting_Default = Unknown remoting error.
-Remoting_HandlerNotRegistered = The tracking handler of type '{0}' is not registered with Remoting Services.
-Remoting_InvalidMsg = Invalid Message Object.
-Remoting_InvalidCallingType = Attempted to call a method declared on type '{0}' on an object which exposes '{1}'.
-Remoting_InvalidRequestedType = The server object type cannot be cast to the requested type '{0}'.
-Remoting_InternalError = Server encountered an internal error. For more information, turn off customErrors in the server's .config file.
-Remoting_Lifetime_ILeaseReturn = Expected a return object of type ILease, but received '{0}'.
-Remoting_Lifetime_InitialStateInitialLeaseTime = InitialLeaseTime property can only be set when the lease is in initial state. The state is '{0}'.
-Remoting_Lifetime_InitialStateRenewOnCall = RenewOnCallTime property can only be set when the lease is in initial state. The state is '{0}'.
-Remoting_Lifetime_InitialStateSponsorshipTimeout = SponsorshipTimeout property can only be set when the lease is in initial state. State is '{0}'.
-Remoting_Lifetime_SetOnce = '{0}' can only be set once within an AppDomain.
-Remoting_Message_ArgMismatch = {2} arguments were passed to '{0}::{1}'. {3} arguments were expected by this method.
-Remoting_Message_BadAsyncResult = The async result object is null or of an unexpected type.
-Remoting_Message_BadType = The method was called with a Message of an unexpected type.
-Remoting_Message_CoercionFailed = The argument type '{0}' cannot be converted into parameter type '{1}'.
-Remoting_Message_MissingArgValue = Expecting an instance of type '{0}' at pos {1} in the args array.
-Remoting_Message_BadSerialization = Invalid or malformed serialization information for the message object.
-Remoting_NoIdentityEntry = No remoting information was found for this object.
-Remoting_NotRemotableByReference = Trying to create a proxy to an unbound type.
-Remoting_NullMessage = The method was called with a null message.
-Remoting_Proxy_BadType = The proxy is of an unsupported type.
-Remoting_ResetURI = Attempt to reset the URI for an object from '{0}' to '{1}'.
-Remoting_ServerObjectNotFound = The server object for URI '{0}' is not registered with the remoting infrastructure (it may have been disconnected).
-Remoting_SetObjectUriForMarshal__ObjectNeedsToBeLocal = SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.
-Remoting_SetObjectUriForMarshal__UriExists = SetObjectUriForMarshal method has already been called on this object or the object has already been marshaled.
-Remoting_Proxy_BadReturnType = Return argument has an invalid type.
-Remoting_Proxy_ReturnValueTypeCannotBeNull = ByRef value type parameter cannot be null.
-Remoting_Proxy_BadReturnTypeForActivation = Bad return type for activation call via Invoke: must be of type IConstructionReturnMessage.
-Remoting_Proxy_BadTypeForActivation = Type mismatch between proxy type '{0}' and activation type '{1}'.
-Remoting_Proxy_ExpectedOriginalMessage = The message passed to Invoke should be passed to PropagateOutParameters.
-Remoting_Proxy_InvalidCall = Trying to call proxy while constructor call is in progress.
-Remoting_Proxy_InvalidState = Channel sink does not exist. Failed to dispatch async call.
-Remoting_Proxy_NoChannelSink = This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server.
-Remoting_Proxy_InvalidCallType = Only the synchronous call type is supported for messages that are not of type Message.
-Remoting_Proxy_WrongContext =  ExecuteMessage can be called only from the native context of the object.
-Remoting_SOAPInteropxsdInvalid = Soap Parse error, xsd:type '{0}' invalid {1}
-Remoting_SOAPQNameNamespace = SoapQName missing a Namespace value '{0}'.
-Remoting_ThreadAffinity_InvalidFlag = The specified flag '{0}' does not have one of the valid values.
-Remoting_TrackingHandlerAlreadyRegistered = The handler has already been registered with TrackingServices.
-Remoting_URIClash = Found two different objects associated with the same URI, '{0}'.
-Remoting_URIExists = The remoted object already has an associated URI.
-Remoting_URIToProxy = Trying to associate the URI with a proxy.
-Remoting_WellKnown_MustBeMBR = Attempted to create well-known object of type '{0}'. Well-known objects must derive from the MarshalByRefObject class.
-Remoting_WellKnown_CtorCantMarshal = '{0}': A well-known object cannot marshal itself in its constructor, or perform any action that would cause it to be marshaled (such as passing the 'this' pointer as a parameter to a remote method).
-Remoting_WellKnown_CantDirectlyConnect = Attempt to connect to a server using its object URI: '{0}'. A valid, complete URL must be used.
-Remoting_Connect_CantCreateChannelSink = Cannot create channel sink to connect to URL '{0}'. An appropriate channel has probably not been registered.
-Remoting_UnexpectedNullTP = Failed to create a transparent proxy. If a custom RealProxy is being used ensure it sets the proxy type.
-; The following remoting exception messages appear in native resources too (mscorrc.rc)
-Remoting_Disconnected = Object '{0}' has been disconnected or does not exist at the server.
-Remoting_Message_MethodMissing = The method '{0}' was not found on the interface/type '{1}'.
-#endif  // FEATURE_REMOTING
 
 ; Resources exceptions
 ;
@@ -1727,24 +1576,6 @@ Security_GenericNoType = Request failed.
 Security_NoAPTCA = That assembly does not allow partially trusted callers.
 Security_RegistryPermission = Requested registry access is not allowed.
 Security_MustRevertOverride = Stack walk modifier must be reverted before another modification of the same type can be performed.
-#if FEATURE_CAS_POLICY
-Security_CannotGenerateHash = Hash for the assembly cannot be generated.
-Security_CannotGetRawData = Assembly bytes could not be retrieved.
-Security_PrincipalPermission = Request for principal permission failed.
-Security_Action = The action that failed was:
-Security_TypeFirstPermThatFailed = The type of the first permission that failed was:
-Security_FirstPermThatFailed = The first permission that failed was:
-Security_Demanded = The demand was for:
-Security_GrantedSet = The granted set of the failing assembly was:
-Security_RefusedSet = The refused set of the failing assembly was:
-Security_Denied = The denied permissions were:
-Security_PermitOnly = The only permitted permissions were:
-Security_Assembly = The assembly or AppDomain that failed was:
-Security_Method = The method that caused the failure was:
-Security_Zone = The Zone of the assembly that failed was:
-Security_Url = The Url of the assembly that failed was:
-Security_AnonymouslyHostedDynamicMethodCheckFailed = The demand failed due to the code access security information captured during the creation of an anonymously hosted dynamic method. In order for this operation to succeed, ensure that the demand would have succeeded at the time the method was created. See http://go.microsoft.com/fwlink/?LinkId=288746 for more information.
-#endif  // FEATURE_CAS_POLICY
 
 ;
 ; HostProtection exceptions
@@ -1796,10 +1627,8 @@ IO.PathNotFound_NoPathName = Could not find a part of the path.
 ; PathTooLongException
 IO.PathTooLong = The specified file name or path is too long, or a component of the specified path is too long.
 
-#if FEATURE_CORECLR
 ; SecurityException
 FileSecurityState_OperationNotPermitted = File operation not permitted. Access to path '{0}' is denied.
-#endif
 
 ; PrivilegeNotHeldException
 PrivilegeNotHeld_Default = The process does not possess some privilege required for this operation.
@@ -2197,14 +2026,6 @@ XMLSyntax_InvalidSyntaxSatAssemTag = Invalid XML in file "{0}" near element "{1}
 XMLSyntax_InvalidSyntaxSatAssemTagBadAttr = Invalid XML in file "{0}" near "{1}" and "{2}". In the <satelliteassemblies> section, the <assembly> tag must have exactly 1 attribute called 'name', whose value is a fully-qualified assembly name.
 XMLSyntax_InvalidSyntaxSatAssemTagNoAttr = Invalid XML in file "{0}". In the <satelliteassemblies> section, the <assembly> tag must have exactly 1 attribute called 'name', whose value is a fully-qualified assembly name.
 
-; CodeGroup
-#if FEATURE_CAS_POLICY
-NetCodeGroup_PermissionSet = Same site Web
-MergeLogic_Union = Union
-MergeLogic_FirstMatch = First Match
-FileCodeGroup_PermissionSet = Same directory FileIO - '{0}'
-#endif // FEATURE_CAS_POLICY
-
 ; MembershipConditions
 StrongName_ToString = StrongName - {0}{1}{2}
 StrongName_Name = name = {0}
@@ -2217,12 +2038,6 @@ Zone_ToString = Zone - {0}
 All_ToString = All code
 Url_ToString = Url
 GAC_ToString = GAC
-#if FEATURE_CAS_POLICY
-Site_ToStringArg = Site - {0}
-Publisher_ToStringArg = Publisher - {0}
-Url_ToStringArg = Url - {0}
-#endif // FEATURE_CAS_POLICY
-
 
 ; Interop non exception strings.
 TypeLibConverter_ImportedTypeLibProductName = Assembly imported from type library '{0}'.
@@ -2306,957 +2121,6 @@ InvalidOperation_CannotRemoveLastFromEmptyCollection=Cannot remove the last elem
 ; Buffers
 ArgumentException_BufferNotFromPool=The buffer is not associated with this pool and may not be returned to it.
 
-; Globalization resources
-;------------------
-
-#if !FEATURE_CORECLR
-Globalization.LegacyModifier =  Legacy
-
-;
-;Total items: 809
-;
-Globalization.ci_ = Invariant Language (Invariant Country)
-Globalization.ci_aa = Afar
-Globalization.ci_aa-DJ = Afar (Djibouti)
-Globalization.ci_aa-ER = Afar (Eritrea)
-Globalization.ci_aa-ET = Afar (Ethiopia)
-Globalization.ci_af = Afrikaans
-Globalization.ci_af-NA = Afrikaans (Namibia)
-Globalization.ci_af-ZA = Afrikaans (South Africa)
-Globalization.ci_agq = Aghem
-Globalization.ci_agq-CM = Aghem (Cameroon)
-Globalization.ci_ak = Akan
-Globalization.ci_ak-GH = Akan (Ghana)
-Globalization.ci_am = Amharic
-Globalization.ci_am-ET = Amharic (Ethiopia)
-Globalization.ci_ar = Arabic
-Globalization.ci_ar-001 = Arabic (World)
-Globalization.ci_ar-AE = Arabic (U.A.E.)
-Globalization.ci_ar-BH = Arabic (Bahrain)
-Globalization.ci_ar-DJ = Arabic (Djibouti)
-Globalization.ci_ar-DZ = Arabic (Algeria)
-Globalization.ci_ar-EG = Arabic (Egypt)
-Globalization.ci_ar-ER = Arabic (Eritrea)
-Globalization.ci_ar-IL = Arabic (Israel)
-Globalization.ci_ar-IQ = Arabic (Iraq)
-Globalization.ci_ar-JO = Arabic (Jordan)
-Globalization.ci_ar-KM = Arabic (Comoros)
-Globalization.ci_ar-KW = Arabic (Kuwait)
-Globalization.ci_ar-LB = Arabic (Lebanon)
-Globalization.ci_ar-LY = Arabic (Libya)
-Globalization.ci_ar-MA = Arabic (Morocco)
-Globalization.ci_ar-MR = Arabic (Mauritania)
-Globalization.ci_ar-OM = Arabic (Oman)
-Globalization.ci_ar-PS = Arabic (Palestinian Authority)
-Globalization.ci_ar-QA = Arabic (Qatar)
-Globalization.ci_ar-SA = Arabic (Saudi Arabia)
-Globalization.ci_ar-SD = Arabic (Sudan)
-Globalization.ci_ar-SO = Arabic (Somalia)
-Globalization.ci_ar-SS = Arabic (South Sudan)
-Globalization.ci_ar-SY = Arabic (Syria)
-Globalization.ci_ar-TD = Arabic (Chad)
-Globalization.ci_ar-TN = Arabic (Tunisia)
-Globalization.ci_ar-YE = Arabic (Yemen)
-Globalization.ci_arn = Mapudungun
-Globalization.ci_arn-CL = Mapudungun (Chile)
-Globalization.ci_as = Assamese
-Globalization.ci_as-IN = Assamese (India)
-Globalization.ci_asa = Asu
-Globalization.ci_asa-TZ = Asu (Tanzania)
-Globalization.ci_ast = Asturian
-Globalization.ci_ast-ES = Asturian (Spain)
-Globalization.ci_az = Azerbaijani
-Globalization.ci_az-Cyrl = Azerbaijani (Cyrillic)
-Globalization.ci_az-Cyrl-AZ = Azerbaijani (Cyrillic, Azerbaijan)
-Globalization.ci_az-Latn = Azerbaijani (Latin)
-Globalization.ci_az-Latn-AZ = Azerbaijani (Latin, Azerbaijan)
-Globalization.ci_ba = Bashkir
-Globalization.ci_ba-RU = Bashkir (Russia)
-Globalization.ci_bas = Basaa
-Globalization.ci_bas-CM = Basaa (Cameroon)
-Globalization.ci_be = Belarusian
-Globalization.ci_be-BY = Belarusian (Belarus)
-Globalization.ci_bem = Bemba
-Globalization.ci_bem-ZM = Bemba (Zambia)
-Globalization.ci_bez = Bena
-Globalization.ci_bez-TZ = Bena (Tanzania)
-Globalization.ci_bg = Bulgarian
-Globalization.ci_bg-BG = Bulgarian (Bulgaria)
-Globalization.ci_bm = Bambara
-Globalization.ci_bm-Latn = Bambara (Latin)
-Globalization.ci_bm-Latn-ML = Bambara (Latin, Mali)
-Globalization.ci_bm-ML = Bamanankan (Latin, Mali)
-Globalization.ci_bn = Bangla
-Globalization.ci_bn-BD = Bangla (Bangladesh)
-Globalization.ci_bn-IN = Bangla (India)
-Globalization.ci_bo = Tibetan
-Globalization.ci_bo-CN = Tibetan (PRC)
-Globalization.ci_bo-IN = Tibetan (India)
-Globalization.ci_br = Breton
-Globalization.ci_br-FR = Breton (France)
-Globalization.ci_brx = Bodo
-Globalization.ci_brx-IN = Bodo (India)
-Globalization.ci_bs = Bosnian
-Globalization.ci_bs-Cyrl = Bosnian (Cyrillic)
-Globalization.ci_bs-Cyrl-BA = Bosnian (Cyrillic, Bosnia and Herzegovina)
-Globalization.ci_bs-Latn = Bosnian (Latin)
-Globalization.ci_bs-Latn-BA = Bosnian (Latin, Bosnia and Herzegovina)
-Globalization.ci_byn = Blin
-Globalization.ci_byn-ER = Blin (Eritrea)
-Globalization.ci_ca = Catalan
-Globalization.ci_ca-AD = Catalan (Andorra)
-Globalization.ci_ca-ES = Catalan (Catalan)
-Globalization.ci_ca-ES-valencia = Valencian (Spain)
-Globalization.ci_ca-FR = Catalan (France)
-Globalization.ci_ca-IT = Catalan (Italy)
-Globalization.ci_cgg = Chiga
-Globalization.ci_cgg-UG = Chiga (Uganda)
-Globalization.ci_chr = Cherokee
-Globalization.ci_chr-Cher = Cherokee (Cherokee)
-Globalization.ci_chr-Cher-US = Cherokee (Cherokee)
-Globalization.ci_co = Corsican
-Globalization.ci_co-FR = Corsican (France)
-Globalization.ci_cs = Czech
-Globalization.ci_cs-CZ = Czech (Czech Republic)
-Globalization.ci_cy = Welsh
-Globalization.ci_cy-GB = Welsh (United Kingdom)
-Globalization.ci_da = Danish
-Globalization.ci_da-DK = Danish (Denmark)
-Globalization.ci_da-GL = Danish (Greenland)
-Globalization.ci_dav = Taita
-Globalization.ci_dav-KE = Taita (Kenya)
-Globalization.ci_de = German
-Globalization.ci_de-AT = German (Austria)
-Globalization.ci_de-BE = German (Belgium)
-Globalization.ci_de-CH = German (Switzerland)
-Globalization.ci_de-DE = German (Germany)
-Globalization.ci_de-DE_phoneb = German (Germany)
-Globalization.ci_de-LI = German (Liechtenstein)
-Globalization.ci_de-LU = German (Luxembourg)
-Globalization.ci_dje = Zarma
-Globalization.ci_dje-NE = Zarma (Niger)
-Globalization.ci_dsb = Lower Sorbian
-Globalization.ci_dsb-DE = Lower Sorbian (Germany)
-Globalization.ci_dua = Duala
-Globalization.ci_dua-CM = Duala (Cameroon)
-Globalization.ci_dv = Divehi
-Globalization.ci_dv-MV = Divehi (Maldives)
-Globalization.ci_dyo = Jola-Fonyi
-Globalization.ci_dyo-SN = Jola-Fonyi (Senegal)
-Globalization.ci_dz = Dzongkha
-Globalization.ci_dz-BT = Dzongkha (Bhutan)
-Globalization.ci_ebu = Embu
-Globalization.ci_ebu-KE = Embu (Kenya)
-Globalization.ci_ee = Ewe
-Globalization.ci_ee-GH = Ewe (Ghana)
-Globalization.ci_ee-TG = Ewe (Togo)
-Globalization.ci_el = Greek
-Globalization.ci_el-CY = Greek (Cyprus)
-Globalization.ci_el-GR = Greek (Greece)
-Globalization.ci_en = English
-Globalization.ci_en-001 = English (World)
-Globalization.ci_en-029 = English (Caribbean)
-Globalization.ci_en-150 = English (Europe)
-Globalization.ci_en-AG = English (Antigua and Barbuda)
-Globalization.ci_en-AI = English (Anguilla)
-Globalization.ci_en-AS = English (American Samoa)
-Globalization.ci_en-AU = English (Australia)
-Globalization.ci_en-BB = English (Barbados)
-Globalization.ci_en-BE = English (Belgium)
-Globalization.ci_en-BM = English (Bermuda)
-Globalization.ci_en-BS = English (Bahamas)
-Globalization.ci_en-BW = English (Botswana)
-Globalization.ci_en-BZ = English (Belize)
-Globalization.ci_en-CA = English (Canada)
-Globalization.ci_en-CC = English (Cocos [Keeling] Islands)
-Globalization.ci_en-CK = English (Cook Islands)
-Globalization.ci_en-CM = English (Cameroon)
-Globalization.ci_en-CX = English (Christmas Island)
-Globalization.ci_en-DM = English (Dominica)
-Globalization.ci_en-ER = English (Eritrea)
-Globalization.ci_en-FJ = English (Fiji)
-Globalization.ci_en-FK = English (Falkland Islands)
-Globalization.ci_en-FM = English (Micronesia)
-Globalization.ci_en-GB = English (United Kingdom)
-Globalization.ci_en-GD = English (Grenada)
-Globalization.ci_en-GG = English (Guernsey)
-Globalization.ci_en-GH = English (Ghana)
-Globalization.ci_en-GI = English (Gibraltar)
-Globalization.ci_en-GM = English (Gambia)
-Globalization.ci_en-GU = English (Guam)
-Globalization.ci_en-GY = English (Guyana)
-Globalization.ci_en-HK = English (Hong Kong SAR)
-Globalization.ci_en-IE = English (Ireland)
-Globalization.ci_en-IM = English (Isle of Man)
-Globalization.ci_en-IN = English (India)
-Globalization.ci_en-IO = English (British Indian Ocean Territory)
-Globalization.ci_en-JE = English (Jersey)
-Globalization.ci_en-JM = English (Jamaica)
-Globalization.ci_en-KE = English (Kenya)
-Globalization.ci_en-KI = English (Kiribati)
-Globalization.ci_en-KN = English (Saint Kitts and Nevis)
-Globalization.ci_en-KY = English (Cayman Islands)
-Globalization.ci_en-LC = English (Saint Lucia)
-Globalization.ci_en-LR = English (Liberia)
-Globalization.ci_en-LS = English (Lesotho)
-Globalization.ci_en-MG = English (Madagascar)
-Globalization.ci_en-MH = English (Marshall Islands)
-Globalization.ci_en-MO = English (Macao SAR)
-Globalization.ci_en-MP = English (Northern Mariana Islands)
-Globalization.ci_en-MS = English (Montserrat)
-Globalization.ci_en-MT = English (Malta)
-Globalization.ci_en-MU = English (Mauritius)
-Globalization.ci_en-MW = English (Malawi)
-Globalization.ci_en-MY = English (Malaysia)
-Globalization.ci_en-NA = English (Namibia)
-Globalization.ci_en-NF = English (Norfolk Island)
-Globalization.ci_en-NG = English (Nigeria)
-Globalization.ci_en-NR = English (Nauru)
-Globalization.ci_en-NU = English (Niue)
-Globalization.ci_en-NZ = English (New Zealand)
-Globalization.ci_en-PG = English (Papua New Guinea)
-Globalization.ci_en-PH = English (Republic of the Philippines)
-Globalization.ci_en-PK = English (Pakistan)
-Globalization.ci_en-PN = English (Pitcairn Islands)
-Globalization.ci_en-PR = English (Puerto Rico)
-Globalization.ci_en-PW = English (Palau)
-Globalization.ci_en-RW = English (Rwanda)
-Globalization.ci_en-SB = English (Solomon Islands)
-Globalization.ci_en-SC = English (Seychelles)
-Globalization.ci_en-SD = English (Sudan)
-Globalization.ci_en-SG = English (Singapore)
-Globalization.ci_en-SH = English (St Helena, Ascension, Tristan da Cunha)
-Globalization.ci_en-SL = English (Sierra Leone)
-Globalization.ci_en-SS = English (South Sudan)
-Globalization.ci_en-SX = English (Sint Maarten)
-Globalization.ci_en-SZ = English (Swaziland)
-Globalization.ci_en-TC = English (Turks and Caicos Islands)
-Globalization.ci_en-TK = English (Tokelau)
-Globalization.ci_en-TO = English (Tonga)
-Globalization.ci_en-TT = English (Trinidad and Tobago)
-Globalization.ci_en-TV = English (Tuvalu)
-Globalization.ci_en-TZ = English (Tanzania)
-Globalization.ci_en-UG = English (Uganda)
-Globalization.ci_en-UM = English (US Minor Outlying Islands)
-Globalization.ci_en-US = English (United States)
-Globalization.ci_en-VC = English (Saint Vincent and the Grenadines)
-Globalization.ci_en-VG = English (British Virgin Islands)
-Globalization.ci_en-VI = English (US Virgin Islands)
-Globalization.ci_en-VU = English (Vanuatu)
-Globalization.ci_en-WS = English (Samoa)
-Globalization.ci_en-ZA = English (South Africa)
-Globalization.ci_en-ZM = English (Zambia)
-Globalization.ci_en-ZW = English (Zimbabwe)
-Globalization.ci_eo = Esperanto
-Globalization.ci_eo-001 = Esperanto (World)
-Globalization.ci_es = Spanish
-Globalization.ci_es-419 = Spanish (Latin America)
-Globalization.ci_es-AR = Spanish (Argentina)
-Globalization.ci_es-BO = Spanish (Bolivia)
-Globalization.ci_es-CL = Spanish (Chile)
-Globalization.ci_es-CO = Spanish (Colombia)
-Globalization.ci_es-CR = Spanish (Costa Rica)
-Globalization.ci_es-CU = Spanish (Cuba)
-Globalization.ci_es-DO = Spanish (Dominican Republic)
-Globalization.ci_es-EC = Spanish (Ecuador)
-Globalization.ci_es-ES = Spanish (Spain)
-Globalization.ci_es-ES_tradnl = Spanish (Spain)
-Globalization.ci_es-GQ = Spanish (Equatorial Guinea)
-Globalization.ci_es-GT = Spanish (Guatemala)
-Globalization.ci_es-HN = Spanish (Honduras)
-Globalization.ci_es-MX = Spanish (Mexico)
-Globalization.ci_es-NI = Spanish (Nicaragua)
-Globalization.ci_es-PA = Spanish (Panama)
-Globalization.ci_es-PE = Spanish (Peru)
-Globalization.ci_es-PH = Spanish (Philippines)
-Globalization.ci_es-PR = Spanish (Puerto Rico)
-Globalization.ci_es-PY = Spanish (Paraguay)
-Globalization.ci_es-SV = Spanish (El Salvador)
-Globalization.ci_es-US = Spanish (United States)
-Globalization.ci_es-UY = Spanish (Uruguay)
-Globalization.ci_es-VE = Spanish (Bolivarian Republic of Venezuela)
-Globalization.ci_et = Estonian
-Globalization.ci_et-EE = Estonian (Estonia)
-Globalization.ci_eu = Basque
-Globalization.ci_eu-ES = Basque (Basque)
-Globalization.ci_ewo = Ewondo
-Globalization.ci_ewo-CM = Ewondo (Cameroon)
-Globalization.ci_fa = Persian
-Globalization.ci_fa-AF = Persian (Afghanistan)
-Globalization.ci_fa-IR = Persian (Iran)
-Globalization.ci_ff = Fulah
-Globalization.ci_ff-CM = Fulah (Cameroon)
-Globalization.ci_ff-GN = Fulah (Guinea)
-Globalization.ci_ff-Latn = Fulah (Latin)
-Globalization.ci_ff-Latn-SN = Fulah (Latin, Senegal)
-Globalization.ci_ff-MR = Fulah (Mauritania)
-Globalization.ci_fi = Finnish
-Globalization.ci_fi-FI = Finnish (Finland)
-Globalization.ci_fil = Filipino
-Globalization.ci_fil-PH = Filipino (Philippines)
-Globalization.ci_fo = Faroese
-Globalization.ci_fo-FO = Faroese (Faroe Islands)
-Globalization.ci_fr = French
-Globalization.ci_fr-BE = French (Belgium)
-Globalization.ci_fr-BF = French (Burkina Faso)
-Globalization.ci_fr-BI = French (Burundi)
-Globalization.ci_fr-BJ = French (Benin)
-Globalization.ci_fr-BL = French (Saint Barthélemy)
-Globalization.ci_fr-CA = French (Canada)
-Globalization.ci_fr-CD = French (Congo DRC)
-Globalization.ci_fr-CF = French (Central African Republic)
-Globalization.ci_fr-CG = French (Congo)
-Globalization.ci_fr-CH = French (Switzerland)
-Globalization.ci_fr-CI = French (Côte d’Ivoire)
-Globalization.ci_fr-CM = French (Cameroon)
-Globalization.ci_fr-DJ = French (Djibouti)
-Globalization.ci_fr-DZ = French (Algeria)
-Globalization.ci_fr-FR = French (France)
-Globalization.ci_fr-GA = French (Gabon)
-Globalization.ci_fr-GF = French (French Guiana)
-Globalization.ci_fr-GN = French (Guinea)
-Globalization.ci_fr-GP = French (Guadeloupe)
-Globalization.ci_fr-GQ = French (Equatorial Guinea)
-Globalization.ci_fr-HT = French (Haiti)
-Globalization.ci_fr-KM = French (Comoros)
-Globalization.ci_fr-LU = French (Luxembourg)
-Globalization.ci_fr-MA = French (Morocco)
-Globalization.ci_fr-MC = French (Monaco)
-Globalization.ci_fr-MF = French (Saint Martin)
-Globalization.ci_fr-MG = French (Madagascar)
-Globalization.ci_fr-ML = French (Mali)
-Globalization.ci_fr-MQ = French (Martinique)
-Globalization.ci_fr-MR = French (Mauritania)
-Globalization.ci_fr-MU = French (Mauritius)
-Globalization.ci_fr-NC = French (New Caledonia)
-Globalization.ci_fr-NE = French (Niger)
-Globalization.ci_fr-PF = French (French Polynesia)
-Globalization.ci_fr-PM = French (Saint Pierre and Miquelon)
-Globalization.ci_fr-RE = French (Reunion)
-Globalization.ci_fr-RW = French (Rwanda)
-Globalization.ci_fr-SC = French (Seychelles)
-Globalization.ci_fr-SN = French (Senegal)
-Globalization.ci_fr-SY = French (Syria)
-Globalization.ci_fr-TD = French (Chad)
-Globalization.ci_fr-TG = French (Togo)
-Globalization.ci_fr-TN = French (Tunisia)
-Globalization.ci_fr-VU = French (Vanuatu)
-Globalization.ci_fr-WF = French (Wallis and Futuna)
-Globalization.ci_fr-YT = French (Mayotte)
-Globalization.ci_fur = Friulian
-Globalization.ci_fur-IT = Friulian (Italy)
-Globalization.ci_fy = Frisian
-Globalization.ci_fy-NL = Frisian (Netherlands)
-Globalization.ci_ga = Irish
-Globalization.ci_ga-IE = Irish (Ireland)
-Globalization.ci_gd = Scottish Gaelic
-Globalization.ci_gd-GB = Scottish Gaelic (United Kingdom)
-Globalization.ci_gl = Galician
-Globalization.ci_gl-ES = Galician (Galician)
-Globalization.ci_gn = Guarani
-Globalization.ci_gn-PY = Guarani (Paraguay)
-Globalization.ci_gsw = Alsatian
-Globalization.ci_gsw-CH = Alsatian (Switzerland)
-Globalization.ci_gsw-FR = Alsatian (France)
-Globalization.ci_gsw-LI = Alsatian (Liechtenstein)
-Globalization.ci_gu = Gujarati
-Globalization.ci_gu-IN = Gujarati (India)
-Globalization.ci_guz = Gusii
-Globalization.ci_guz-KE = Gusii (Kenya)
-Globalization.ci_gv = Manx
-Globalization.ci_gv-IM = Manx (Isle of Man)
-Globalization.ci_ha = Hausa
-Globalization.ci_ha-Latn = Hausa (Latin)
-Globalization.ci_ha-Latn-GH = Hausa (Latin, Ghana)
-Globalization.ci_ha-Latn-NE = Hausa (Latin, Niger)
-Globalization.ci_ha-Latn-NG = Hausa (Latin, Nigeria)
-Globalization.ci_haw = Hawaiian
-Globalization.ci_haw-US = Hawaiian (United States)
-Globalization.ci_he = Hebrew
-Globalization.ci_he-IL = Hebrew (Israel)
-Globalization.ci_hi = Hindi
-Globalization.ci_hi-IN = Hindi (India)
-Globalization.ci_hr = Croatian
-Globalization.ci_hr-BA = Croatian (Latin, Bosnia and Herzegovina)
-Globalization.ci_hr-HR = Croatian (Croatia)
-Globalization.ci_hsb = Upper Sorbian
-Globalization.ci_hsb-DE = Upper Sorbian (Germany)
-Globalization.ci_hu = Hungarian
-Globalization.ci_hu-HU = Hungarian (Hungary)
-Globalization.ci_hu-HU_technl = Hungarian (Hungary)
-Globalization.ci_hy = Armenian
-Globalization.ci_hy-AM = Armenian (Armenia)
-Globalization.ci_ia = Interlingua
-Globalization.ci_ia-001 = Interlingua (World)
-Globalization.ci_ia-FR = Interlingua (France)
-Globalization.ci_id = Indonesian
-Globalization.ci_id-ID = Indonesian (Indonesia)
-Globalization.ci_ig = Igbo
-Globalization.ci_ig-NG = Igbo (Nigeria)
-Globalization.ci_ii = Yi
-Globalization.ci_ii-CN = Yi (PRC)
-Globalization.ci_is = Icelandic
-Globalization.ci_is-IS = Icelandic (Iceland)
-Globalization.ci_it = Italian
-Globalization.ci_it-CH = Italian (Switzerland)
-Globalization.ci_it-IT = Italian (Italy)
-Globalization.ci_it-SM = Italian (San Marino)
-Globalization.ci_iu = Inuktitut
-Globalization.ci_iu-Cans = Inuktitut (Syllabics)
-Globalization.ci_iu-Cans-CA = Inuktitut (Syllabics, Canada)
-Globalization.ci_iu-Latn = Inuktitut (Latin)
-Globalization.ci_iu-Latn-CA = Inuktitut (Latin, Canada)
-Globalization.ci_ja = Japanese
-Globalization.ci_ja-JP = Japanese (Japan)
-Globalization.ci_ja-JP_radstr = Japanese (Japan)
-Globalization.ci_jgo = Ngomba
-Globalization.ci_jgo-CM = Ngomba (Cameroon)
-Globalization.ci_jmc = Machame
-Globalization.ci_jmc-TZ = Machame (Tanzania)
-Globalization.ci_jv = Javanese
-Globalization.ci_jv-Latn = Javanese
-Globalization.ci_jv-Latn-ID = Javanese (Indonesia)
-Globalization.ci_ka = Georgian
-Globalization.ci_ka-GE = Georgian (Georgia)
-Globalization.ci_ka-GE_modern = Georgian (Georgia)
-Globalization.ci_kab = Kabyle
-Globalization.ci_kab-DZ = Kabyle (Algeria)
-Globalization.ci_kam = Kamba
-Globalization.ci_kam-KE = Kamba (Kenya)
-Globalization.ci_kde = Makonde
-Globalization.ci_kde-TZ = Makonde (Tanzania)
-Globalization.ci_kea = Kabuverdianu
-Globalization.ci_kea-CV = Kabuverdianu (Cabo Verde)
-Globalization.ci_khq = Koyra Chiini
-Globalization.ci_khq-ML = Koyra Chiini (Mali)
-Globalization.ci_ki = Kikuyu
-Globalization.ci_ki-KE = Kikuyu (Kenya)
-Globalization.ci_kk = Kazakh
-Globalization.ci_kk-KZ = Kazakh (Kazakhstan)
-Globalization.ci_kkj = Kako
-Globalization.ci_kkj-CM = Kako (Cameroon)
-Globalization.ci_kl = Greenlandic
-Globalization.ci_kl-GL = Greenlandic (Greenland)
-Globalization.ci_kln = Kalenjin
-Globalization.ci_kln-KE = Kalenjin (Kenya)
-Globalization.ci_km = Khmer
-Globalization.ci_km-KH = Khmer (Cambodia)
-Globalization.ci_kn = Kannada
-Globalization.ci_kn-IN = Kannada (India)
-Globalization.ci_ko = Korean
-Globalization.ci_ko-KR = Korean (Korea)
-Globalization.ci_kok = Konkani
-Globalization.ci_kok-IN = Konkani (India)
-Globalization.ci_ks = Kashmiri
-Globalization.ci_ks-Arab = Kashmiri (Perso-Arabic)
-Globalization.ci_ks-Arab-IN = Kashmiri (Perso-Arabic)
-Globalization.ci_ksb = Shambala
-Globalization.ci_ksb-TZ = Shambala (Tanzania)
-Globalization.ci_ksf = Bafia
-Globalization.ci_ksf-CM = Bafia (Cameroon)
-Globalization.ci_ksh = Colognian
-Globalization.ci_ksh-DE = Ripuarian (Germany)
-Globalization.ci_ku = Central Kurdish
-Globalization.ci_ku-Arab = Central Kurdish (Arabic)
-Globalization.ci_ku-Arab-IQ = Central Kurdish (Iraq)
-Globalization.ci_kw = Cornish
-Globalization.ci_kw-GB = Cornish (United Kingdom)
-Globalization.ci_ky = Kyrgyz
-Globalization.ci_ky-KG = Kyrgyz (Kyrgyzstan)
-Globalization.ci_lag = Langi
-Globalization.ci_lag-TZ = Langi (Tanzania)
-Globalization.ci_lb = Luxembourgish
-Globalization.ci_lb-LU = Luxembourgish (Luxembourg)
-Globalization.ci_lg = Ganda
-Globalization.ci_lg-UG = Ganda (Uganda)
-Globalization.ci_lkt = Lakota
-Globalization.ci_lkt-US = Lakota (United States)
-Globalization.ci_ln = Lingala
-Globalization.ci_ln-AO = Lingala (Angola)
-Globalization.ci_ln-CD = Lingala (Congo DRC)
-Globalization.ci_ln-CF = Lingala (Central African Republic)
-Globalization.ci_ln-CG = Lingala (Congo)
-Globalization.ci_lo = Lao
-Globalization.ci_lo-LA = Lao (Lao P.D.R.)
-Globalization.ci_lt = Lithuanian
-Globalization.ci_lt-LT = Lithuanian (Lithuania)
-Globalization.ci_lu = Luba-Katanga
-Globalization.ci_lu-CD = Luba-Katanga (Congo DRC)
-Globalization.ci_luo = Luo
-Globalization.ci_luo-KE = Luo (Kenya)
-Globalization.ci_luy = Luyia
-Globalization.ci_luy-KE = Luyia (Kenya)
-Globalization.ci_lv = Latvian
-Globalization.ci_lv-LV = Latvian (Latvia)
-Globalization.ci_mas = Masai
-Globalization.ci_mas-KE = Masai (Kenya)
-Globalization.ci_mas-TZ = Masai (Tanzania)
-Globalization.ci_mer = Meru
-Globalization.ci_mer-KE = Meru (Kenya)
-Globalization.ci_mfe = Morisyen
-Globalization.ci_mfe-MU = Morisyen (Mauritius)
-Globalization.ci_mg = Malagasy
-Globalization.ci_mg-MG = Malagasy (Madagascar)
-Globalization.ci_mgh = Makhuwa-Meetto
-Globalization.ci_mgh-MZ = Makhuwa-Meetto (Mozambique)
-Globalization.ci_mgo = Meta'
-Globalization.ci_mgo-CM = Meta' (Cameroon)
-Globalization.ci_mi = Maori
-Globalization.ci_mi-NZ = Maori (New Zealand)
-Globalization.ci_mk = Macedonian (FYROM)
-Globalization.ci_mk-MK = Macedonian (Former Yugoslav Republic of Macedonia)
-Globalization.ci_ml = Malayalam
-Globalization.ci_ml-IN = Malayalam (India)
-Globalization.ci_mn = Mongolian
-Globalization.ci_mn-Cyrl = Mongolian (Cyrillic)
-Globalization.ci_mn-MN = Mongolian (Cyrillic, Mongolia)
-Globalization.ci_mn-Mong = Mongolian (Traditional Mongolian)
-Globalization.ci_mn-Mong-CN = Mongolian (Traditional Mongolian, PRC)
-Globalization.ci_mn-Mong-MN = Mongolian (Traditional Mongolian, Mongolia)
-Globalization.ci_moh = Mohawk
-Globalization.ci_moh-CA = Mohawk (Mohawk)
-Globalization.ci_mr = Marathi
-Globalization.ci_mr-IN = Marathi (India)
-Globalization.ci_ms = Malay
-Globalization.ci_ms-BN = Malay (Brunei Darussalam)
-Globalization.ci_ms-MY = Malay (Malaysia)
-Globalization.ci_ms-SG = Malay (Latin, Singapore)
-Globalization.ci_mt = Maltese
-Globalization.ci_mt-MT = Maltese (Malta)
-Globalization.ci_mua = Mundang
-Globalization.ci_mua-CM = Mundang (Cameroon)
-Globalization.ci_my = Burmese
-Globalization.ci_my-MM = Burmese (Myanmar)
-Globalization.ci_naq = Nama
-Globalization.ci_naq-NA = Nama (Namibia)
-Globalization.ci_nb = Norwegian (BokmÃ¥l)
-Globalization.ci_nb-NO = Norwegian, BokmÃ¥l (Norway)
-Globalization.ci_nb-SJ = Norwegian, BokmÃ¥l (Svalbard and Jan Mayen)
-Globalization.ci_nd = North Ndebele
-Globalization.ci_nd-ZW = North Ndebele (Zimbabwe)
-Globalization.ci_ne = Nepali
-Globalization.ci_ne-IN = Nepali (India)
-Globalization.ci_ne-NP = Nepali (Nepal)
-Globalization.ci_nl = Dutch
-Globalization.ci_nl-AW = Dutch (Aruba)
-Globalization.ci_nl-BE = Dutch (Belgium)
-Globalization.ci_nl-BQ = Dutch (Bonaire, Sint Eustatius and Saba)
-Globalization.ci_nl-CW = Dutch (Curaçao)
-Globalization.ci_nl-NL = Dutch (Netherlands)
-Globalization.ci_nl-SR = Dutch (Suriname)
-Globalization.ci_nl-SX = Dutch (Sint Maarten)
-Globalization.ci_nmg = Kwasio
-Globalization.ci_nmg-CM = Kwasio (Cameroon)
-Globalization.ci_nn = Norwegian (Nynorsk)
-Globalization.ci_nn-NO = Norwegian, Nynorsk (Norway)
-Globalization.ci_nnh = Ngiemboon
-Globalization.ci_nnh-CM = Ngiemboon (Cameroon)
-Globalization.ci_no = Norwegian
-Globalization.ci_nqo = N'ko
-Globalization.ci_nqo-GN = N'ko (Guinea)
-Globalization.ci_nr = South Ndebele
-Globalization.ci_nr-ZA = South Ndebele (South Africa)
-Globalization.ci_nso = Sesotho sa Leboa
-Globalization.ci_nso-ZA = Sesotho sa Leboa (South Africa)
-Globalization.ci_nus = Nuer
-Globalization.ci_nus-SD = Nuer (Sudan)
-Globalization.ci_nyn = Nyankole
-Globalization.ci_nyn-UG = Nyankole (Uganda)
-Globalization.ci_oc = Occitan
-Globalization.ci_oc-FR = Occitan (France)
-Globalization.ci_om = Oromo
-Globalization.ci_om-ET = Oromo (Ethiopia)
-Globalization.ci_om-KE = Oromo (Kenya)
-Globalization.ci_or = Odia
-Globalization.ci_or-IN = Odia (India)
-Globalization.ci_os = Ossetic
-Globalization.ci_os-GE = Ossetian (Cyrillic, Georgia)
-Globalization.ci_os-RU = Ossetian (Cyrillic, Russia)
-Globalization.ci_pa = Punjabi
-Globalization.ci_pa-Arab = Punjabi (Arabic)
-Globalization.ci_pa-Arab-PK = Punjabi (Islamic Republic of Pakistan)
-Globalization.ci_pa-IN = Punjabi (India)
-Globalization.ci_pl = Polish
-Globalization.ci_pl-PL = Polish (Poland)
-Globalization.ci_prs = Dari
-Globalization.ci_prs-AF = Dari (Afghanistan)
-Globalization.ci_ps = Pashto
-Globalization.ci_ps-AF = Pashto (Afghanistan)
-Globalization.ci_pt = Portuguese
-Globalization.ci_pt-AO = Portuguese (Angola)
-Globalization.ci_pt-BR = Portuguese (Brazil)
-Globalization.ci_pt-CV = Portuguese (Cabo Verde)
-Globalization.ci_pt-GW = Portuguese (Guinea-Bissau)
-Globalization.ci_pt-MO = Portuguese (Macao SAR)
-Globalization.ci_pt-MZ = Portuguese (Mozambique)
-Globalization.ci_pt-PT = Portuguese (Portugal)
-Globalization.ci_pt-ST = Portuguese (São Tomé and Príncipe)
-Globalization.ci_pt-TL = Portuguese (Timor-Leste)
-Globalization.ci_qps-ploc = Pseudo Language (Pseudo)
-Globalization.ci_qps-ploca = Pseudo Language (Pseudo Asia)
-Globalization.ci_qps-plocm = Pseudo Language (Pseudo Mirrored)
-Globalization.ci_qu = Quechua
-Globalization.ci_qu-BO = Quechua (Bolivia)
-Globalization.ci_qu-EC = Quechua (Ecuador)
-Globalization.ci_qu-PE = Quechua (Peru)
-Globalization.ci_quc = K'iche'
-Globalization.ci_quc-Latn = K'iche'
-Globalization.ci_quc-Latn-GT = K'iche' (Guatemala)
-Globalization.ci_qut = K'iche
-Globalization.ci_qut-GT = K'iche (Guatemala)
-Globalization.ci_quz = Quechua
-Globalization.ci_quz-BO = Quechua (Bolivia)
-Globalization.ci_quz-EC = Quechua (Ecuador)
-Globalization.ci_quz-PE = Quechua (Peru)
-Globalization.ci_rm = Romansh
-Globalization.ci_rm-CH = Romansh (Switzerland)
-Globalization.ci_rn = Rundi
-Globalization.ci_rn-BI = Rundi (Burundi)
-Globalization.ci_ro = Romanian
-Globalization.ci_ro-MD = Romanian (Moldova)
-Globalization.ci_ro-RO = Romanian (Romania)
-Globalization.ci_rof = Rombo
-Globalization.ci_rof-TZ = Rombo (Tanzania)
-Globalization.ci_ru = Russian
-Globalization.ci_ru-BY = Russian (Belarus)
-Globalization.ci_ru-KG = Russian (Kyrgyzstan)
-Globalization.ci_ru-KZ = Russian (Kazakhstan)
-Globalization.ci_ru-MD = Russian (Moldova)
-Globalization.ci_ru-RU = Russian (Russia)
-Globalization.ci_ru-UA = Russian (Ukraine)
-Globalization.ci_rw = Kinyarwanda
-Globalization.ci_rw-RW = Kinyarwanda (Rwanda)
-Globalization.ci_rwk = Rwa
-Globalization.ci_rwk-TZ = Rwa (Tanzania)
-Globalization.ci_sa = Sanskrit
-Globalization.ci_sa-IN = Sanskrit (India)
-Globalization.ci_sah = Sakha
-Globalization.ci_sah-RU = Sakha (Russia)
-Globalization.ci_saq = Samburu
-Globalization.ci_saq-KE = Samburu (Kenya)
-Globalization.ci_sbp = Sangu
-Globalization.ci_sbp-TZ = Sangu (Tanzania)
-Globalization.ci_sd = Sindhi
-Globalization.ci_sd-Arab = Sindhi (Arabic)
-Globalization.ci_sd-Arab-PK = Sindhi (Islamic Republic of Pakistan)
-Globalization.ci_se = Sami (Northern)
-Globalization.ci_se-FI = Sami, Northern (Finland)
-Globalization.ci_se-NO = Sami, Northern (Norway)
-Globalization.ci_se-SE = Sami, Northern (Sweden)
-Globalization.ci_seh = Sena
-Globalization.ci_seh-MZ = Sena (Mozambique)
-Globalization.ci_ses = Koyraboro Senni
-Globalization.ci_ses-ML = Koyraboro Senni (Mali)
-Globalization.ci_sg = Sango
-Globalization.ci_sg-CF = Sango (Central African Republic)
-Globalization.ci_shi = Tachelhit
-Globalization.ci_shi-Latn = Tachelhit (Latin)
-Globalization.ci_shi-Latn-MA = Tachelhit (Latin, Morocco)
-Globalization.ci_shi-Tfng = Tachelhit (Tifinagh)
-Globalization.ci_shi-Tfng-MA = Tachelhit (Tifinagh, Morocco)
-Globalization.ci_si = Sinhala
-Globalization.ci_si-LK = Sinhala (Sri Lanka)
-Globalization.ci_sk = Slovak
-Globalization.ci_sk-SK = Slovak (Slovakia)
-Globalization.ci_sl = Slovenian
-Globalization.ci_sl-SI = Slovenian (Slovenia)
-Globalization.ci_sma = Sami (Southern)
-Globalization.ci_sma-NO = Sami, Southern (Norway)
-Globalization.ci_sma-SE = Sami, Southern (Sweden)
-Globalization.ci_smj = Sami (Lule)
-Globalization.ci_smj-NO = Sami, Lule (Norway)
-Globalization.ci_smj-SE = Sami, Lule (Sweden)
-Globalization.ci_smn = Sami (Inari)
-Globalization.ci_smn-FI = Sami, Inari (Finland)
-Globalization.ci_sms = Sami (Skolt)
-Globalization.ci_sms-FI = Sami, Skolt (Finland)
-Globalization.ci_sn = Shona
-Globalization.ci_sn-Latn = Shona (Latin)
-Globalization.ci_sn-Latn-ZW = Shona (Latin, Zimbabwe)
-Globalization.ci_so = Somali
-Globalization.ci_so-DJ = Somali (Djibouti)
-Globalization.ci_so-ET = Somali (Ethiopia)
-Globalization.ci_so-KE = Somali (Kenya)
-Globalization.ci_so-SO = Somali (Somalia)
-Globalization.ci_sq = Albanian
-Globalization.ci_sq-AL = Albanian (Albania)
-Globalization.ci_sq-MK = Albanian (Macedonia, FYRO)
-Globalization.ci_sr = Serbian
-Globalization.ci_sr-Cyrl = Serbian (Cyrillic)
-Globalization.ci_sr-Cyrl-BA = Serbian (Cyrillic, Bosnia and Herzegovina)
-Globalization.ci_sr-Cyrl-CS = Serbian (Cyrillic, Serbia and Montenegro (Former))
-Globalization.ci_sr-Cyrl-ME = Serbian (Cyrillic, Montenegro)
-Globalization.ci_sr-Cyrl-RS = Serbian (Cyrillic, Serbia)
-Globalization.ci_sr-Latn = Serbian (Latin)
-Globalization.ci_sr-Latn-BA = Serbian (Latin, Bosnia and Herzegovina)
-Globalization.ci_sr-Latn-CS = Serbian (Latin, Serbia and Montenegro (Former))
-Globalization.ci_sr-Latn-ME = Serbian (Latin, Montenegro)
-Globalization.ci_sr-Latn-RS = Serbian (Latin, Serbia)
-Globalization.ci_ss = Swati
-Globalization.ci_ss-SZ = Swati (Swaziland)
-Globalization.ci_ss-ZA = Swati (South Africa)
-Globalization.ci_ssy = Saho
-Globalization.ci_ssy-ER = Saho (Eritrea)
-Globalization.ci_st = Southern Sotho
-Globalization.ci_st-LS = Sesotho (Lesotho)
-Globalization.ci_st-ZA = Southern Sotho (South Africa)
-Globalization.ci_sv = Swedish
-Globalization.ci_sv-AX = Swedish (Ã…land Islands)
-Globalization.ci_sv-FI = Swedish (Finland)
-Globalization.ci_sv-SE = Swedish (Sweden)
-Globalization.ci_sw = Kiswahili
-Globalization.ci_sw-KE = Kiswahili (Kenya)
-Globalization.ci_sw-TZ = Kiswahili (Tanzania)
-Globalization.ci_sw-UG = Kiswahili (Uganda)
-Globalization.ci_swc = Congo Swahili
-Globalization.ci_swc-CD = Congo Swahili (Congo DRC)
-Globalization.ci_syr = Syriac
-Globalization.ci_syr-SY = Syriac (Syria)
-Globalization.ci_ta = Tamil
-Globalization.ci_ta-IN = Tamil (India)
-Globalization.ci_ta-LK = Tamil (Sri Lanka)
-Globalization.ci_ta-MY = Tamil (Malaysia)
-Globalization.ci_ta-SG = Tamil (Singapore)
-Globalization.ci_te = Telugu
-Globalization.ci_te-IN = Telugu (India)
-Globalization.ci_teo = Teso
-Globalization.ci_teo-KE = Teso (Kenya)
-Globalization.ci_teo-UG = Teso (Uganda)
-Globalization.ci_tg = Tajik
-Globalization.ci_tg-Cyrl = Tajik (Cyrillic)
-Globalization.ci_tg-Cyrl-TJ = Tajik (Cyrillic, Tajikistan)
-Globalization.ci_th = Thai
-Globalization.ci_th-TH = Thai (Thailand)
-Globalization.ci_ti = Tigrinya
-Globalization.ci_ti-ER = Tigrinya (Eritrea)
-Globalization.ci_ti-ET = Tigrinya (Ethiopia)
-Globalization.ci_tig = Tigre
-Globalization.ci_tig-ER = Tigre (Eritrea)
-Globalization.ci_tk = Turkmen
-Globalization.ci_tk-TM = Turkmen (Turkmenistan)
-Globalization.ci_tn = Setswana
-Globalization.ci_tn-BW = Setswana (Botswana)
-Globalization.ci_tn-ZA = Setswana (South Africa)
-Globalization.ci_to = Tongan
-Globalization.ci_to-TO = Tongan (Tonga)
-Globalization.ci_tr = Turkish
-Globalization.ci_tr-CY = Turkish (Cyprus)
-Globalization.ci_tr-TR = Turkish (Turkey)
-Globalization.ci_ts = Tsonga
-Globalization.ci_ts-ZA = Tsonga (South Africa)
-Globalization.ci_tt = Tatar
-Globalization.ci_tt-RU = Tatar (Russia)
-Globalization.ci_twq = Tasawaq
-Globalization.ci_twq-NE = Tasawaq (Niger)
-Globalization.ci_tzm = Tamazight
-Globalization.ci_tzm-Latn = Tamazight (Latin)
-Globalization.ci_tzm-Latn-DZ = Tamazight (Latin, Algeria)
-Globalization.ci_tzm-Latn-MA = Central Atlas Tamazight (Latin, Morocco)
-Globalization.ci_tzm-Tfng = Tamazight (Tifinagh)
-Globalization.ci_tzm-Tfng-MA = Central Atlas Tamazight (Tifinagh, Morocco)
-Globalization.ci_ug = Uyghur
-Globalization.ci_ug-CN = Uyghur (PRC)
-Globalization.ci_uk = Ukrainian
-Globalization.ci_uk-UA = Ukrainian (Ukraine)
-Globalization.ci_ur = Urdu
-Globalization.ci_ur-IN = Urdu (India)
-Globalization.ci_ur-PK = Urdu (Islamic Republic of Pakistan)
-Globalization.ci_uz = Uzbek
-Globalization.ci_uz-Arab = Uzbek (Perso-Arabic)
-Globalization.ci_uz-Arab-AF = Uzbek (Perso-Arabic, Afghanistan)
-Globalization.ci_uz-Cyrl = Uzbek (Cyrillic)
-Globalization.ci_uz-Cyrl-UZ = Uzbek (Cyrillic, Uzbekistan)
-Globalization.ci_uz-Latn = Uzbek (Latin)
-Globalization.ci_uz-Latn-UZ = Uzbek (Latin, Uzbekistan)
-Globalization.ci_vai = Vai
-Globalization.ci_vai-Latn = Vai (Latin)
-Globalization.ci_vai-Latn-LR = Vai (Latin, Liberia)
-Globalization.ci_vai-Vaii = Vai (Vai)
-Globalization.ci_vai-Vaii-LR = Vai (Vai, Liberia)
-Globalization.ci_ve = Venda
-Globalization.ci_ve-ZA = Venda (South Africa)
-Globalization.ci_vi = Vietnamese
-Globalization.ci_vi-VN = Vietnamese (Vietnam)
-Globalization.ci_vo = Volapük
-Globalization.ci_vo-001 = Volapük (World)
-Globalization.ci_vun = Vunjo
-Globalization.ci_vun-TZ = Vunjo (Tanzania)
-Globalization.ci_wae = Walser
-Globalization.ci_wae-CH = Walser (Switzerland)
-Globalization.ci_wal = Wolaytta
-Globalization.ci_wal-ET = Wolaytta (Ethiopia)
-Globalization.ci_wo = Wolof
-Globalization.ci_wo-SN = Wolof (Senegal)
-Globalization.ci_x-IV = Invariant Language (Invariant Country)
-Globalization.ci_x-IV_mathan = Invariant Language (Invariant Country)
-Globalization.ci_xh = isiXhosa
-Globalization.ci_xh-ZA = isiXhosa (South Africa)
-Globalization.ci_xog = Soga
-Globalization.ci_xog-UG = Soga (Uganda)
-Globalization.ci_yav = Yangben
-Globalization.ci_yav-CM = Yangben (Cameroon)
-Globalization.ci_yi = Yiddish
-Globalization.ci_yi-001 = Yiddish (World)
-Globalization.ci_yo = Yoruba
-Globalization.ci_yo-BJ = Yoruba (Benin)
-Globalization.ci_yo-NG = Yoruba (Nigeria)
-Globalization.ci_zgh = Standard Moroccan Tamazight
-Globalization.ci_zgh-Tfng = Standard Moroccan Tamazight (Tifinagh)
-Globalization.ci_zgh-Tfng-MA = Standard Moroccan Tamazight (Tifinagh, Morocco)
-Globalization.ci_zh = Chinese
-Globalization.ci_zh-CHS = Chinese (Simplified) Legacy
-Globalization.ci_zh-CHT = Chinese (Traditional) Legacy
-Globalization.ci_zh-CN = Chinese (Simplified, PRC)
-Globalization.ci_zh-CN_stroke = Chinese (Simplified, PRC)
-Globalization.ci_zh-Hans = Chinese (Simplified)
-Globalization.ci_zh-Hant = Chinese (Traditional)
-Globalization.ci_zh-HK = Chinese (Traditional, Hong Kong S.A.R.)
-Globalization.ci_zh-HK_radstr = Chinese (Traditional, Hong Kong S.A.R.)
-Globalization.ci_zh-MO = Chinese (Traditional, Macao S.A.R.)
-Globalization.ci_zh-MO_radstr = Chinese (Traditional, Macao S.A.R.)
-Globalization.ci_zh-MO_stroke = Chinese (Traditional, Macao S.A.R.)
-Globalization.ci_zh-SG = Chinese (Simplified, Singapore)
-Globalization.ci_zh-SG_stroke = Chinese (Simplified, Singapore)
-Globalization.ci_zh-TW = Chinese (Traditional, Taiwan)
-Globalization.ci_zh-TW_pronun = Chinese (Traditional, Taiwan)
-Globalization.ci_zh-TW_radstr = Chinese (Traditional, Taiwan)
-Globalization.ci_zu = isiZulu
-Globalization.ci_zu-ZA = isiZulu (South Africa)
-;------------------
-;
-;Total items: 129
-;
-Globalization.ri_029 = Caribbean
-Globalization.ri_AE = U.A.E.
-Globalization.ri_AF = Afghanistan
-Globalization.ri_AL = Albania
-Globalization.ri_AM = Armenia
-Globalization.ri_AR = Argentina
-Globalization.ri_AT = Austria
-Globalization.ri_AU = Australia
-Globalization.ri_AZ = Azerbaijan
-Globalization.ri_BA = Bosnia and Herzegovina
-Globalization.ri_BD = Bangladesh
-Globalization.ri_BE = Belgium
-Globalization.ri_BG = Bulgaria
-Globalization.ri_BH = Bahrain
-Globalization.ri_BN = Brunei Darussalam
-Globalization.ri_BO = Bolivia
-Globalization.ri_BR = Brazil
-Globalization.ri_BY = Belarus
-Globalization.ri_BZ = Belize
-Globalization.ri_CA = Canada
-Globalization.ri_CH = Switzerland
-Globalization.ri_CL = Chile
-Globalization.ri_CN = People's Republic of China
-Globalization.ri_CO = Colombia
-Globalization.ri_CR = Costa Rica
-Globalization.ri_CS = Serbia and Montenegro (Former)
-Globalization.ri_CZ = Czech Republic
-Globalization.ri_DE = Germany
-Globalization.ri_DK = Denmark
-Globalization.ri_DO = Dominican Republic
-Globalization.ri_DZ = Algeria
-Globalization.ri_EC = Ecuador
-Globalization.ri_EE = Estonia
-Globalization.ri_EG = Egypt
-Globalization.ri_ER = Eritrea
-Globalization.ri_ES = Spain
-Globalization.ri_ET = Ethiopia
-Globalization.ri_FI = Finland
-Globalization.ri_FO = Faroe Islands
-Globalization.ri_FR = France
-Globalization.ri_GB = United Kingdom
-Globalization.ri_GE = Georgia
-Globalization.ri_GL = Greenland
-Globalization.ri_GR = Greece
-Globalization.ri_GT = Guatemala
-Globalization.ri_HK = Hong Kong S.A.R.
-Globalization.ri_HN = Honduras
-Globalization.ri_HR = Croatia
-Globalization.ri_HU = Hungary
-Globalization.ri_ID = Indonesia
-Globalization.ri_IE = Ireland
-Globalization.ri_IL = Israel
-Globalization.ri_IN = India
-Globalization.ri_IQ = Iraq
-Globalization.ri_IR = Iran
-Globalization.ri_IS = Iceland
-Globalization.ri_IT = Italy
-Globalization.ri_IV = Invariant Country
-Globalization.ri_JM = Jamaica
-Globalization.ri_JO = Jordan
-Globalization.ri_JP = Japan
-Globalization.ri_KE = Kenya
-Globalization.ri_KG = Kyrgyzstan
-Globalization.ri_KH = Cambodia
-Globalization.ri_KR = Korea
-Globalization.ri_KW = Kuwait
-Globalization.ri_KZ = Kazakhstan
-Globalization.ri_LA = Lao P.D.R.
-Globalization.ri_LB = Lebanon
-Globalization.ri_LI = Liechtenstein
-Globalization.ri_LK = Sri Lanka
-Globalization.ri_LT = Lithuania
-Globalization.ri_LU = Luxembourg
-Globalization.ri_LV = Latvia
-Globalization.ri_LY = Libya
-Globalization.ri_MA = Morocco
-Globalization.ri_MC = Principality of Monaco
-Globalization.ri_ME = Montenegro
-Globalization.ri_MK = Macedonia (FYROM)
-Globalization.ri_MN = Mongolia
-Globalization.ri_MO = Macao S.A.R.
-Globalization.ri_MT = Malta
-Globalization.ri_MV = Maldives
-Globalization.ri_MX = Mexico
-Globalization.ri_MY = Malaysia
-Globalization.ri_NG = Nigeria
-Globalization.ri_NI = Nicaragua
-Globalization.ri_NL = Netherlands
-Globalization.ri_NO = Norway
-Globalization.ri_NP = Nepal
-Globalization.ri_NZ = New Zealand
-Globalization.ri_OM = Oman
-Globalization.ri_PA = Panama
-Globalization.ri_PE = Peru
-Globalization.ri_PH = Philippines
-Globalization.ri_PK = Islamic Republic of Pakistan
-Globalization.ri_PL = Poland
-Globalization.ri_PR = Puerto Rico
-Globalization.ri_PT = Portugal
-Globalization.ri_PY = Paraguay
-Globalization.ri_QA = Qatar
-Globalization.ri_RO = Romania
-Globalization.ri_RS = Serbia
-Globalization.ri_RU = Russia
-Globalization.ri_RW = Rwanda
-Globalization.ri_SA = Saudi Arabia
-Globalization.ri_SE = Sweden
-Globalization.ri_SG = Singapore
-Globalization.ri_SI = Slovenia
-Globalization.ri_SK = Slovakia
-Globalization.ri_SN = Senegal
-Globalization.ri_SV = El Salvador
-Globalization.ri_SY = Syria
-Globalization.ri_TH = Thailand
-Globalization.ri_TJ = Tajikistan
-Globalization.ri_TM = Turkmenistan
-Globalization.ri_TN = Tunisia
-Globalization.ri_TR = Turkey
-Globalization.ri_TT = Trinidad and Tobago
-Globalization.ri_TW = Taiwan
-Globalization.ri_UA = Ukraine
-Globalization.ri_US = United States
-Globalization.ri_UY = Uruguay
-Globalization.ri_UZ = Uzbekistan
-Globalization.ri_VE = Bolivarian Republic of Venezuela
-Globalization.ri_VN = Vietnam
-Globalization.ri_YE = Yemen
-Globalization.ri_ZA = South Africa
-Globalization.ri_ZW = Zimbabwe
-#endif //!FEATURE_CORECLR
-
 ;------------------
 ; Encoding names:
 ;
index d6653c7..27f7faf 100644 (file)
@@ -2,62 +2,23 @@
 // 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 {
-    using System.Runtime.CompilerServices;
-
+namespace System
+{
     public delegate void Action<in T>(T obj); 
 
     // Action/Func delegates first shipped with .NET Framework 3.5 in System.Core.dll as part of LINQ
     // These were type forwarded to mscorlib.dll in .NET Framework 4.0 and in Silverlight 5.0
-
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public delegate void Action();
-
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public delegate void Action<in T1,in T2>(T1 arg1, T2 arg2);
-
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public delegate void Action<in T1,in T2,in T3>(T1 arg1, T2 arg2, T3 arg3);
-
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public delegate void Action<in T1,in T2,in T3,in T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
 
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public delegate TResult Func<out TResult>();
-
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public delegate TResult Func<in T, out TResult>(T arg);
-
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
-
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
-
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
 
-
     public delegate void Action<in T1,in T2,in T3,in T4,in T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
     public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
     public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
index afd46e7..6fad8f3 100644 (file)
@@ -16,10 +16,6 @@ namespace System {
     using System;
     using System.Reflection;
     using System.Runtime.Remoting;
-#if FEATURE_REMOTING    
-    using System.Runtime.Remoting.Activation;
-    using Message = System.Runtime.Remoting.Messaging.Message;
-#endif
     using System.Security;
     using CultureInfo = System.Globalization.CultureInfo;
     using Evidence = System.Security.Policy.Evidence;
@@ -34,7 +30,7 @@ namespace System {
     // Only statics, does not need to be marked with the serializable attribute
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_Activator))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class Activator : _Activator
     {
         internal const int LookupMask                 = 0x000000FF;
@@ -60,7 +56,6 @@ namespace System {
             return CreateInstance(type, bindingAttr, binder, args, culture, null);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         static public Object CreateInstance(Type type,
                                             BindingFlags bindingAttr,
@@ -81,22 +76,7 @@ namespace System {
                 bindingAttr |= Activator.ConstructorDefault;
 
             if (activationAttributes != null && activationAttributes.Length > 0){
-                // If type does not derive from MBR
-                // throw notsupportedexception
-#if FEATURE_REMOTING                
-                if(type.IsMarshalByRef){
-                    // The fix below is preventative.
-                    //
-                    if(!(type.IsContextful)){
-                        if(activationAttributes.Length > 1 || !(activationAttributes[0] is UrlAttribute))
-                           throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonUrlAttrOnMBR"));
-                    }
-                }
-                else
-                    throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR" ));
-#else
-                    throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr" ));
-#endif
+                throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr" ));
             }
 
             RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
@@ -140,7 +120,6 @@ namespace System {
          * types to be created remotely without having to load the type locally.
          */
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         static public ObjectHandle CreateInstance(String assemblyName,
                                                   String typeName)
@@ -158,7 +137,6 @@ namespace System {
                                   ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable                                                  
         static public ObjectHandle CreateInstance(String assemblyName,
                                                   String typeName,
@@ -232,7 +210,6 @@ namespace System {
                                       activationAttributes);
         }
                                   
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         static public ObjectHandle CreateInstance(String assemblyName, 
@@ -258,7 +235,6 @@ namespace System {
                                   ref stackMark);
         }
 
-        [SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static ObjectHandle CreateInstance(string assemblyName,
                                                   string typeName,
@@ -282,7 +258,6 @@ namespace System {
                                   ref stackMark);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal ObjectHandle CreateInstance(String assemblyString, 
                                                     String typeName, 
                                                     bool ignoreCase,
@@ -294,13 +269,6 @@ namespace System {
                                                     Evidence securityInfo,
                                                     ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
-            {
-                throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
-            }
-#endif // FEATURE_CAS_POLICY
-
             Type type = null;
             Assembly assembly = null;
             if (assemblyString == null) {
@@ -358,13 +326,6 @@ namespace System {
                                                       Evidence securityInfo)
                                                
         {
-#if FEATURE_CAS_POLICY
-            if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
-            {
-                throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
-            }
-#endif // FEATURE_CAS_POLICY
-
             return CreateInstanceFromInternal(assemblyFile,
                                               typeName,
                                               ignoreCase,
@@ -406,10 +367,6 @@ namespace System {
                                                                Object[] activationAttributes,
                                                                Evidence securityInfo)
         {
-#if FEATURE_CAS_POLICY
-            Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled || securityInfo == null);
-#endif // FEATURE_CAS_POLICY
-
 #pragma warning disable 618
             Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo);
 #pragma warning restore 618
@@ -438,7 +395,6 @@ namespace System {
         // to pass the security checks when activating the type.
         //
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName) {
             if (domain == null)
                 throw new ArgumentNullException(nameof(domain));
@@ -446,7 +402,6 @@ namespace System {
             return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public static ObjectHandle CreateInstance (AppDomain domain,
                                                    string assemblyName,
@@ -462,17 +417,9 @@ namespace System {
                 throw new ArgumentNullException(nameof(domain));
             Contract.EndContractBlock();
 
-#if FEATURE_CAS_POLICY
-            if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
-            {
-                throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
-            }
-#endif // FEATURE_CAS_POLICY
-
             return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
         }
 
-        [SecurityCritical]
         public static ObjectHandle CreateInstance(AppDomain domain,
                                                   string assemblyName,
                                                   string typeName,
@@ -505,7 +452,6 @@ namespace System {
         // to pass the security checks when activating the type.
         //
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName) {
             if (domain == null)
                 throw new ArgumentNullException(nameof(domain));
@@ -513,7 +459,6 @@ namespace System {
             return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [Obsolete("Methods which use Evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public static ObjectHandle CreateInstanceFrom (AppDomain domain,
                                                        string assemblyFile,
@@ -529,17 +474,9 @@ namespace System {
                 throw new ArgumentNullException(nameof(domain));
             Contract.EndContractBlock();
 
-#if FEATURE_CAS_POLICY
-            if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
-            {
-                throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
-            }
-#endif // FEATURE_CAS_POLICY
-
             return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
         }
 
-        [SecurityCritical]
         public static ObjectHandle CreateInstanceFrom(AppDomain domain,
                                                       string assemblyFile,
                                                       string typeName,
@@ -612,38 +549,11 @@ namespace System {
             }
         }
 
-#if FEATURE_REMOTING
-        //  This method is a helper method and delegates to the remoting 
-        //  services to do the actual work. 
-        [System.Security.SecurityCritical]  // auto-generated_required
-        static public Object GetObject(Type type, String url)
-        {
-            return GetObject(type, url, null);
-        }
-        
-        //  This method is a helper method and delegates to the remoting 
-        //  services to do the actual work. 
-        [System.Security.SecurityCritical]  // auto-generated_required
-        static public Object GetObject(Type type, String url, Object state)
-        {
-            if (type == null)
-                throw new ArgumentNullException(nameof(type));
-            Contract.EndContractBlock();
-            return RemotingServices.Connect(type, url, state);
-        }
-#endif
-
         [System.Diagnostics.Conditional("_DEBUG")]
         private static void Log(bool test, string title, string success, string failure)
         {
-#if FEATURE_REMOTING
-            if(test)
-                BCLDebug.Trace("REMOTE", "{0}{1}", title, success);
-            else
-                BCLDebug.Trace("REMOTE", "{0}{1}", title, failure);
-#endif            
         }
-        
+
         void _Activator.GetTypeInfoCount(out uint pcTInfo)
         {
             throw new NotImplementedException();
index 4dedf19..c0f2122 100644 (file)
@@ -258,7 +258,6 @@ namespace System
         /// contains contextual information about the source or destination. </param>
         /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
         /// <exception cref="T:System.Runtime.Serialization.SerializationException">The exception could not be deserialized correctly.</exception>
-        [SecurityCritical]
         protected AggregateException(SerializationInfo info, StreamingContext context) :
             base(info, context)
         {
@@ -285,7 +284,6 @@ namespace System
         /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that
         /// contains contextual information about the source or destination. </param>
         /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
-        [SecurityCritical]
         public override void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
index de6405a..41e4450 100644 (file)
@@ -21,9 +21,6 @@ namespace System
 
         public static string BaseDirectory
         {
-#if FEATURE_CORECLR
-            [System.Security.SecuritySafeCritical]
-#endif
             get
             {
                 // The value of APP_CONTEXT_BASE_DIRECTORY key has to be a string and it is not allowed to be any other type. 
@@ -41,15 +38,11 @@ namespace System
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-#endif
         public static object GetData(string name)
         {
             return AppDomain.CurrentDomain.GetData(name);
         }
 
-        [System.Security.SecuritySafeCritical]
         public static void SetData(string name, object data)
         {
             AppDomain.CurrentDomain.SetData(name, data);
@@ -57,13 +50,11 @@ namespace System
 
         public static event UnhandledExceptionEventHandler UnhandledException
         {
-            [System.Security.SecurityCritical]
             add
             {
                 AppDomain.CurrentDomain.UnhandledException += value;
             }
 
-            [System.Security.SecurityCritical]
             remove
             {
                 AppDomain.CurrentDomain.UnhandledException -= value;
@@ -72,12 +63,10 @@ namespace System
 
         public static event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException
         {  
-            [System.Security.SecurityCritical]
             add  
             {  
                 AppDomain.CurrentDomain.FirstChanceException += value;  
             }  
-            [System.Security.SecurityCritical]
             remove  
             {  
                 AppDomain.CurrentDomain.FirstChanceException -= value;  
@@ -86,12 +75,10 @@ namespace System
 
         public static event System.EventHandler ProcessExit
         {  
-            [System.Security.SecurityCritical]
             add  
             {  
                 AppDomain.CurrentDomain.ProcessExit += value;  
             }  
-            [System.Security.SecurityCritical]  
             remove  
             {  
                 AppDomain.CurrentDomain.ProcessExit -= value;  
index 7ab7ffb..9f00e81 100644 (file)
@@ -30,7 +30,6 @@ namespace System
 
             if (!TryParseFrameworkName(targetFrameworkMoniker, out identifier, out version, out profile))
             {
-#if FEATURE_CORECLR
                 // If we can't parse the TFM or we don't have a TFM, default to latest behavior for all 
                 // switches (ie. all of them false).
                 // If we want to use the latest behavior it is enough to set the value of the switch to string.Empty.
@@ -39,11 +38,6 @@ namespace System
                 // identifier we are simply saying -- don't turn on any switches, and we are going to get the latest
                 // behavior for all the switches
                 identifier = string.Empty;
-#else
-                identifier = ".NETFramework";          
-                version = 40000;               
-                profile = string.Empty;
-#endif
             }
         }
 
index b6c54b5..fe524c4 100644 (file)
@@ -35,6 +35,7 @@ namespace System
     using System.Text;
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 #if FEATURE_EXCEPTION_NOTIFICATIONS
     using System.Runtime.ExceptionServices;
@@ -89,7 +90,6 @@ namespace System
         }
     }
 
-    [System.Security.SecurityCritical] // auto-generated
     [Serializable]
     [ComVisible(true)]
     public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args);
@@ -156,7 +156,6 @@ namespace System
             Info = itemInfo.ToArray();            
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal AppDomainInitializer Unwrap()
         {
             if (Info==null)
@@ -188,9 +187,8 @@ namespace System
         // Domain security information
         // These fields initialized from the other side only. (NOTE: order 
         // of these fields cannot be changed without changing the layout in 
-        // the EE)
+        // the EE- AppDomainBaseObject in this case)
 
-        [System.Security.SecurityCritical] // auto-generated
         private AppDomainManager _domainManager;
         private Dictionary<String, Object[]> _LocalStore;
         private AppDomainSetup   _FusionStore;
@@ -201,12 +199,10 @@ namespace System
         [method: System.Security.SecurityCritical]
         public event AssemblyLoadEventHandler AssemblyLoad;
 
-        [System.Security.SecurityCritical]
         private ResolveEventHandler _TypeResolve;
 
         public event ResolveEventHandler TypeResolve
         {
-            [System.Security.SecurityCritical]
             add
             {
                 lock (this)
@@ -215,7 +211,6 @@ namespace System
                 }
             }
 
-            [System.Security.SecurityCritical]
             remove
             {
                 lock (this)
@@ -225,12 +220,10 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]
         private ResolveEventHandler _ResourceResolve;
 
         public event ResolveEventHandler ResourceResolve
         {
-            [System.Security.SecurityCritical]
             add
             {
                 lock (this)
@@ -239,7 +232,6 @@ namespace System
                 }
             }
 
-            [System.Security.SecurityCritical]
             remove
             {
                 lock (this)
@@ -249,12 +241,10 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]
         private ResolveEventHandler _AssemblyResolve;
 
         public event ResolveEventHandler AssemblyResolve
         {
-            [System.Security.SecurityCritical]
             add
             {
                 lock (this)
@@ -263,7 +253,6 @@ namespace System
                 }
             }
 
-            [System.Security.SecurityCritical]
             remove
             {
                 lock (this)
@@ -281,10 +270,8 @@ namespace System
         private ApplicationTrust _applicationTrust;
         private EventHandler     _processExit;
 
-        [System.Security.SecurityCritical] 
         private EventHandler     _domainUnload;
 
-        [System.Security.SecurityCritical] // auto-generated
         private UnhandledExceptionEventHandler _unhandledException;
 
         // The compat flags are set at domain creation time to indicate that the given breaking
@@ -328,20 +315,18 @@ namespace System
 
         private static APPX_FLAGS Flags
         {
-            [SecuritySafeCritical]
             get
             {
                 if (s_flags == 0)
                     s_flags = nGetAppXFlags();
 
-                Contract.Assert(s_flags != 0);
+                Debug.Assert(s_flags != 0);
                 return s_flags;
             }
         }
 
         internal static bool ProfileAPICheck
         {
-            [SecuritySafeCritical]
             get
             {
                 return (Flags & APPX_FLAGS.APPX_FLAGS_API_CHECK) != 0;
@@ -350,7 +335,6 @@ namespace System
 
         internal static bool IsAppXNGen
         {
-            [SecuritySafeCritical]
             get
             {
                 return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_NGEN) != 0;
@@ -359,38 +343,32 @@ namespace System
 #endif // FEATURE_APPX
 
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool DisableFusionUpdatesFromADManager(AppDomainHandle domain);
 
 #if FEATURE_APPX
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.I4)]
         private static extern APPX_FLAGS nGetAppXFlags();
 #endif
 
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetAppDomainManagerType(AppDomainHandle domain,
                                                            StringHandleOnStack retAssembly,
                                                            StringHandleOnStack retType);
 
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         private static extern void SetAppDomainManagerType(AppDomainHandle domain,
                                                            string assembly,
                                                            string type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void nSetHostSecurityManagerFlags (HostSecurityManagerOptions flags);
 
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         private static extern void SetSecurityHomogeneousFlag(AppDomainHandle domain,
@@ -415,10 +393,9 @@ namespace System
         ///     If this AppDomain is configured to have an AppDomain manager then create the instance of it.
         ///     This method is also called from the VM to create the domain manager in the default domain.
         /// </summary>
-        [SecuritySafeCritical]
         private void CreateAppDomainManager()
         {
-            Contract.Assert(_domainManager == null, "_domainManager == null");
+            Debug.Assert(_domainManager == null, "_domainManager == null");
 
             AppDomainSetup adSetup = FusionStore;
 #if FEATURE_VERSIONING
@@ -522,7 +499,7 @@ namespace System
             // for perf, we don't intialize the _compatFlags dictionary when we don't need to.  However, we do need to make a 
             // note that we've run this method, because IsCompatibilityFlagsSet needs to return different values for the
             // case where the compat flags have been setup.
-            Contract.Assert(!_compatFlagsInitialized);
+            Debug.Assert(!_compatFlagsInitialized);
             _compatFlagsInitialized = true;
 
             CompatibilitySwitches.InitializeSwitches();
@@ -532,7 +509,6 @@ namespace System
         // either by a host in native, a host in managed using an AppDomainSetup, or by the 
         // TargetFrameworkAttribute on the executable (VS emits its target framework moniker using this
         // attribute starting in version 4).
-        [SecuritySafeCritical]
         internal String GetTargetFrameworkName()
         {
             String targetFrameworkName = _FusionStore.TargetFrameworkName;
@@ -547,7 +523,7 @@ namespace System
                     TargetFrameworkAttribute[] attrs = (TargetFrameworkAttribute[])assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute));
                     if (attrs != null && attrs.Length > 0)
                     {
-                        Contract.Assert(attrs.Length == 1);
+                        Debug.Assert(attrs.Length == 1);
                         targetFrameworkName = attrs[0].FrameworkName;
                         _FusionStore.TargetFrameworkName = targetFrameworkName;
                     }
@@ -561,7 +537,6 @@ namespace System
         /// <summary>
         ///     Returns the setting of the corresponding compatibility config switch (see CreateAppDomainManager for the impact).
         /// </summary>
-        [SecuritySafeCritical]
         internal bool DisableFusionUpdatesFromADManager()
         {
             return DisableFusionUpdatesFromADManager(GetNativeHandle());
@@ -570,7 +545,6 @@ namespace System
         /// <summary>
         ///     Returns whether the current AppDomain follows the AppX rules.
         /// </summary>
-        [SecuritySafeCritical]
         [Pure]
         internal static bool IsAppXModel()
         {
@@ -584,7 +558,6 @@ namespace System
         /// <summary>
         ///     Returns the setting of the AppXDevMode config switch.
         /// </summary>
-        [SecuritySafeCritical]
         [Pure]
         internal static bool IsAppXDesignMode()
         {
@@ -598,7 +571,6 @@ namespace System
         /// <summary>
         ///     Checks (and throws on failure) if the domain supports Assembly.LoadFrom.
         /// </summary>
-        [SecuritySafeCritical]
         [Pure]
         internal static void CheckLoadFromSupported()
         {
@@ -611,7 +583,6 @@ namespace System
         /// <summary>
         ///     Checks (and throws on failure) if the domain supports Assembly.LoadFile.
         /// </summary>
-        [SecuritySafeCritical]
         [Pure]
         internal static void CheckLoadFileSupported()
         {
@@ -624,7 +595,6 @@ namespace System
         /// <summary>
         ///     Checks (and throws on failure) if the domain supports Assembly.ReflectionOnlyLoad.
         /// </summary>
-        [SecuritySafeCritical]
         [Pure]
         internal static void CheckReflectionOnlyLoadSupported()
         {
@@ -637,7 +607,6 @@ namespace System
         /// <summary>
         ///     Checks (and throws on failure) if the domain supports Assembly.LoadWithPartialName.
         /// </summary>
-        [SecuritySafeCritical]
         [Pure]
         internal static void CheckLoadWithPartialNameSupported(StackCrawlMark stackMark)
         {
@@ -657,7 +626,6 @@ namespace System
         /// <summary>
         ///     Checks (and throws on failure) if the domain supports DefinePInvokeMethod.
         /// </summary>
-        [SecuritySafeCritical]
         [Pure]
         internal static void CheckDefinePInvokeSupported()
         {
@@ -671,7 +639,6 @@ namespace System
         /// <summary>
         ///     Checks (and throws on failure) if the domain supports Assembly.Load(byte[] ...).
         /// </summary>
-        [SecuritySafeCritical]
         [Pure]
         internal static void CheckLoadByteArraySupported()
         {
@@ -684,7 +651,6 @@ namespace System
         /// <summary>
         ///     Checks (and throws on failure) if the domain supports AppDomain.CreateDomain.
         /// </summary>
-        [SecuritySafeCritical]
         [Pure]
         internal static void CheckCreateDomainSupported()
         {
@@ -705,7 +671,6 @@ namespace System
         /// <summary>
         ///     Get the name of the assembly and type that act as the AppDomainManager for this domain
         /// </summary>
-        [SecuritySafeCritical]
         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
@@ -724,18 +689,16 @@ namespace System
         /// <summary>
         ///     Set the assembly and type which act as the AppDomainManager for this domain
         /// </summary>
-        [SecuritySafeCritical]
         private void SetAppDomainManagerType(string assembly, string type)
         {
-            Contract.Assert(assembly != null, "assembly != null");
-            Contract.Assert(type != null, "type != null");
+            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>
-        [SecurityCritical]
         private void InitializeDomainSecurity(Evidence providedSecurityInfo,
                                               Evidence creatorsSecurityInfo,
                                               bool generateDefaultEvidence,
@@ -772,7 +735,6 @@ namespace System
                                 publishAppDomain);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetupDomainSecurityForHomogeneousDomain(ApplicationTrust appTrust,
                                                              bool runtimeSuppliedHomogenousGrantSet)
         {
@@ -796,7 +758,6 @@ namespace System
         }
 
         public AppDomainManager DomainManager {
-            [System.Security.SecurityCritical]  // auto-generated_required
             get {
                 return _domainManager;
             }
@@ -818,7 +779,6 @@ namespace System
                 _packageGraphFilePaths = packageGraphFilePaths;
             }
             
-            [System.Security.SecurityCritical]
             public void ResolveNamespace(
                 object sender, 
                 System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs args)
@@ -837,7 +797,6 @@ namespace System
         }
         
         // Called only by native function code:ValidateWorker
-        [System.Security.SecuritySafeCritical]
         private void EnableResolveAssembliesForIntrospection(string verifiedFileDirectory)
         {
             CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(ResolveAssemblyForIntrospection);
@@ -858,7 +817,6 @@ namespace System
         * to have a strong name and a hash will be computed when the assembly
         * is saved.
         **********************************************/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public AssemblyBuilder DefineDynamicAssembly(
             AssemblyName            name,
@@ -871,7 +829,6 @@ namespace System
                                                  null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public AssemblyBuilder DefineDynamicAssembly(
             AssemblyName            name,
@@ -889,7 +846,6 @@ namespace System
         }
 
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Due to the stack crawl mark
-        [SecuritySafeCritical]
         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
                                                      AssemblyBuilderAccess access,
                                                      IEnumerable<CustomAttributeBuilder> assemblyAttributes,
@@ -906,7 +862,6 @@ namespace System
                                                  securityContextSource);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public AssemblyBuilder DefineDynamicAssembly(
             AssemblyName            name,
@@ -923,7 +878,6 @@ namespace System
                                                  SecurityContextSource.CurrentAssembly);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default.  See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public AssemblyBuilder DefineDynamicAssembly(
@@ -941,7 +895,6 @@ namespace System
                                                  SecurityContextSource.CurrentAssembly);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default.  See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public AssemblyBuilder DefineDynamicAssembly(
@@ -963,7 +916,6 @@ namespace System
                                                  SecurityContextSource.CurrentAssembly);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of DefineDynamicAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
         public AssemblyBuilder DefineDynamicAssembly(
@@ -979,7 +931,6 @@ namespace System
                                                  null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public AssemblyBuilder DefineDynamicAssembly(
@@ -1002,7 +953,6 @@ namespace System
                                                  SecurityContextSource.CurrentAssembly);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public AssemblyBuilder DefineDynamicAssembly(
@@ -1026,7 +976,6 @@ namespace System
                                                  SecurityContextSource.CurrentAssembly);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default.  Please see http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
         public AssemblyBuilder DefineDynamicAssembly(
@@ -1051,7 +1000,6 @@ namespace System
                                                  SecurityContextSource.CurrentAssembly);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public AssemblyBuilder DefineDynamicAssembly(
@@ -1079,7 +1027,6 @@ namespace System
                                                  SecurityContextSource.CurrentAssembly);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public AssemblyBuilder DefineDynamicAssembly(
@@ -1108,7 +1055,6 @@ namespace System
                                                  SecurityContextSource.CurrentAssembly);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public AssemblyBuilder DefineDynamicAssembly(
                     AssemblyName name,
@@ -1132,7 +1078,6 @@ namespace System
                                                  SecurityContextSource.CurrentAssembly);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         private AssemblyBuilder InternalDefineDynamicAssembly(
             AssemblyName name,
@@ -1158,7 +1103,6 @@ namespace System
                                                                  securityContextSource);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern String nApplyPolicy(AssemblyName an);
        
@@ -1196,7 +1140,6 @@ namespace System
                                             typeName);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, string typeName) {
             PermissionSet.s_fullTrust.Assert();
             return CreateInstance(assemblyName, typeName);
@@ -1215,7 +1158,6 @@ namespace System
                                                 typeName);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName, string typeName) {
             PermissionSet.s_fullTrust.Assert();
             return CreateInstanceFrom(assemblyName, typeName);
@@ -1346,7 +1288,6 @@ namespace System
                                             activationAttributes);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, 
                                                                     string typeName,
                                                                     bool ignoreCase,
@@ -1415,7 +1356,6 @@ namespace System
                                                 activationAttributes);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName, 
                                                                         string typeName,
                                                                         bool ignoreCase,
@@ -1432,7 +1372,6 @@ namespace System
 #pragma warning restore 618
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public Assembly Load(AssemblyName assemblyRef)
         {
@@ -1440,7 +1379,6 @@ namespace System
             return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public Assembly Load(String assemblyString)
         {
@@ -1448,7 +1386,6 @@ namespace System
             return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public Assembly Load(byte[] rawAssembly)
         {
@@ -1462,7 +1399,6 @@ namespace System
 
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public Assembly Load(byte[] rawAssembly,
                              byte[] rawSymbolStore)
@@ -1476,10 +1412,6 @@ namespace System
                                        SecurityContextSource.CurrentAssembly);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
-#pragma warning restore 618
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
         public Assembly Load(byte[] rawAssembly,
@@ -1495,7 +1427,6 @@ namespace System
                                        SecurityContextSource.CurrentAssembly);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public Assembly Load(AssemblyName assemblyRef,
@@ -1505,7 +1436,6 @@ namespace System
             return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public Assembly Load(String assemblyString,
@@ -1581,7 +1511,6 @@ namespace System
             return nExecuteAssembly(assembly, args);
         }
 
-        [System.Security.SecurityCritical] // auto-generated
         public int ExecuteAssemblyByName(String assemblyName)
         {
             return ExecuteAssemblyByName(assemblyName, (string[])null);
@@ -1652,19 +1581,16 @@ namespace System
 
         public String FriendlyName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return nGetFriendlyName(); }
         } 
 
         public String BaseDirectory
         {
-            [System.Security.SecurityCritical]
             get {
                 return FusionStore.ApplicationBase;
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString()
         {
             StringBuilder sb = StringBuilderCache.Acquire();
@@ -1700,31 +1626,25 @@ namespace System
             return nGetAssemblies(true /* forIntrospection */);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern Assembly[] nGetAssemblies(bool forIntrospection);
 
         // this is true when we've removed the handles etc so really can't do anything
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern bool IsUnloadingForcedFinalize();
 
         // this is true when we've just started going through the finalizers and are forcing objects to finalize
         // so must be aware that certain infrastructure may have gone away
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern bool IsFinalizingForUnload();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void SetData (string name, object data) {
             SetDataHelper(name, data, null);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void SetData (string name, object data, IPermission permission)
         {
             if (!name.Equals("LOCATION_URI"))
@@ -1736,7 +1656,6 @@ namespace System
             SetDataHelper(name, data, permission);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetDataHelper (string name, object data, IPermission permission)
         {
             if (name == null)
@@ -1759,7 +1678,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecurityCritical] // auto-generated
         public Object GetData(string name)
         {
             if(name == null)
@@ -1797,7 +1715,7 @@ namespace System
                 case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue:
                     return FusionStore.ApplicationName;
                 default:
-                    Contract.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
+                    Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
                     return null;
                 }
             }
@@ -1842,7 +1760,6 @@ namespace System
 
         public String DynamicDirectory
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 String dyndir = GetDynamicDir();
                 if (dyndir != null)
@@ -1852,7 +1769,6 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         extern private String GetDynamicDir();
 
@@ -1860,7 +1776,6 @@ namespace System
             throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern int _nExecuteAssembly(RuntimeAssembly assembly, String[] args);
         internal int nExecuteAssembly(RuntimeAssembly assembly, String[] args)
@@ -1872,24 +1787,18 @@ namespace System
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void nCreateContext();
 
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void nSetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD);
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         internal void SetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD)
         {
             nSetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPath, appNiPaths, appLocalWinMD);
         }
 #endif // FEATURE_VERSIONING
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern String nGetFriendlyName();
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern bool nIsDefaultAppDomainForEvidence();
 
@@ -1901,7 +1810,6 @@ namespace System
 
         public event EventHandler ProcessExit
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated_required
             add
             {
                 if (value != null)
@@ -1921,7 +1829,6 @@ namespace System
 
         public event EventHandler DomainUnload
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated_required
             add
             {
                 if (value != null)
@@ -1931,7 +1838,6 @@ namespace System
                         _domainUnload += value;
                 }
             }
-            [System.Security.SecuritySafeCritical] 
             remove
             {
                 lock(this)
@@ -1942,7 +1848,6 @@ namespace System
 
         public event UnhandledExceptionEventHandler UnhandledException
         {
-            [System.Security.SecurityCritical]  // auto-generated_required
             add
             {
                 if (value != null)
@@ -1952,7 +1857,6 @@ namespace System
                         _unhandledException += value;
                 }
             }
-            [System.Security.SecurityCritical]  // auto-generated_required
             remove
             {
                 lock(this)
@@ -1967,7 +1871,6 @@ namespace System
         // To register/unregister the callback, the code must be SecurityCritical.
         public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException
         {
-            [System.Security.SecurityCritical]  // auto-generated_required
             add
             {
                 if (value != null)
@@ -1977,7 +1880,6 @@ namespace System
                         _firstChanceException += value;
                 }
             }
-            [System.Security.SecurityCritical]  // auto-generated_required
             remove
             {
                 lock(this)
@@ -1996,7 +1898,6 @@ namespace System
         }
     
         // This method is called by the VM.
-        [System.Security.SecurityCritical]
         private RuntimeAssembly OnResourceResolveEvent(RuntimeAssembly assembly, String resourceName)
         {
             ResolveEventHandler eventHandler = _ResourceResolve;
@@ -2016,7 +1917,6 @@ namespace System
         }
         
         // This method is called by the VM
-        [System.Security.SecurityCritical]
         private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName)
         {
             ResolveEventHandler eventHandler = _TypeResolve;
@@ -2036,7 +1936,6 @@ namespace System
         }
 
         // This method is called by the VM.
-        [System.Security.SecurityCritical]
         private RuntimeAssembly OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
         {
             ResolveEventHandler eventHandler = _AssemblyResolve;
@@ -2069,7 +1968,7 @@ namespace System
         internal AppDomainSetup FusionStore
         {
             get {
-                Contract.Assert(_FusionStore != null, 
+                Debug.Assert(_FusionStore != null, 
                                 "Fusion store has not been correctly setup in this domain");
                 return _FusionStore;
             }
@@ -2105,17 +2004,14 @@ namespace System
 
         // Used to determine if server object context is valid in
         // x-domain remoting scenarios.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal static extern bool IsDomainIdValid(Int32 id);
 
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void nSetNativeDllSearchDirectories(string paths);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
         {
             Contract.Requires(info != null);
@@ -2162,7 +2058,6 @@ namespace System
         //   are any remoting sinks registered, they can add non-mscorlib
         //   objects to the message (causing an assembly load exception when
         //   we try to deserialize it on the other side)
-        [System.Security.SecurityCritical]  // auto-generated
         private static object PrepareDataForSetup(String friendlyName,
                                                         AppDomainSetup setup,
                                                         Evidence providedSecurityInfo,
@@ -2223,7 +2118,6 @@ namespace System
             };  
         } // PrepareDataForSetup
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)]
         private static Object Setup(Object arg)
         {
@@ -2244,13 +2138,27 @@ namespace System
             Evidence providedSecurityInfo = null;
             Evidence creatorsSecurityInfo = null;
 
-
             AppDomain ad = AppDomain.CurrentDomain;
             AppDomainSetup newSetup=new AppDomainSetup(setup,false);
 
             if(propertyNames!=null && propertyValues != null)
             {
-                StringBuilder normalisedAppPathList = null;
+                for (int i = 0; i < propertyNames.Length; i++)
+                {
+                    // We want to set native dll probing directories before any P/Invokes have a
+                    // chance to fire. The Path class, for one, has P/Invokes.
+                    if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES")
+                    {
+                        if (propertyValues[i] == null)
+                            throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
+
+                        string paths = propertyValues[i];
+                        if (paths.Length == 0)
+                            break;
+
+                        nSetNativeDllSearchDirectories(paths);
+                    }
+                }
 
                 for (int i=0; i<propertyNames.Length; i++)
                 {
@@ -2263,11 +2171,9 @@ namespace System
                             throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
 
                         newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
-
                     }
 #if FEATURE_LOADER_OPTIMIZATION
-                    else
-                    if(propertyNames[i]=="LOADER_OPTIMIZATION")
+                    else if(propertyNames[i]=="LOADER_OPTIMIZATION")
                     {
                         if(propertyValues[i]==null)
                             throw new ArgumentNullException("LOADER_OPTIMIZATION");
@@ -2282,72 +2188,18 @@ namespace System
                         }
                     }
 #endif // FEATURE_LOADER_OPTIMIZATION
-                    else
-                    if(propertyNames[i]=="NATIVE_DLL_SEARCH_DIRECTORIES")
-                    {
-                        if(propertyValues[i]==null)
-                            throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
-                        ad.SetDataHelper(propertyNames[i],propertyValues[i],null);
-                        string paths = (string)propertyValues[i];
-                        if( paths.Length==0 )
-                            continue;
-                        nSetNativeDllSearchDirectories(paths);
-                    }
-                    else
-                    if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES" ||
+                    else if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES" ||
                        propertyNames[i]=="PLATFORM_RESOURCE_ROOTS" ||
                        propertyNames[i]=="APP_PATHS" ||
                        propertyNames[i]=="APP_NI_PATHS")
                     {
                         string values = propertyValues[i];
-                        if(values==null)
+                        if(values == null)
                             throw new ArgumentNullException(propertyNames[i]);
 
-                        int estimatedLength = values.Length + 1; // +1 for extra separator temporarily added at end
-                        if (normalisedAppPathList == null) {
-                            normalisedAppPathList = new StringBuilder(estimatedLength);
-                        }
-                        else {
-                            normalisedAppPathList.Clear();
-                            if (normalisedAppPathList.Capacity < estimatedLength)
-                                normalisedAppPathList.Capacity = estimatedLength;
-                        }
-
-                        for (int pos = 0; pos < values.Length; pos++)
-                        {
-                            string path;
-
-                            int nextPos = values.IndexOf(Path.PathSeparator, pos);
-                            if (nextPos == -1)
-                            {
-                                path = values.Substring(pos);
-                                pos = values.Length - 1;
-                            }
-                            else
-                            {
-                                path = values.Substring(pos, nextPos - pos);
-                                pos = nextPos;
-                            }
-
-                            if( path.Length==0 )                  // skip empty dirs
-                                continue;
-
-                            if (PathInternal.IsPartiallyQualified(path))
-                                throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
-
-                            string appPath = NormalizePath(path, fullCheck: true);
-                            normalisedAppPathList.Append(appPath);
-                            normalisedAppPathList.Append(Path.PathSeparator);
-                        }
-                        // Strip the last separator
-                        if (normalisedAppPathList.Length > 0)
-                        {
-                            normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
-                        }
-                        ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null);        // not supported by fusion, so set explicitly
+                        ad.SetDataHelper(propertyNames[i], NormalizeAppPaths(values), null);
                     }
-                    else
-                    if(propertyNames[i]!= null)
+                    else if(propertyNames[i]!= null)
                     {
                         ad.SetDataHelper(propertyNames[i],propertyValues[i],null);     // just propagate
                     }
@@ -2393,7 +2245,48 @@ namespace System
             return null;
         }
 
-        [SecuritySafeCritical]
+        private static string NormalizeAppPaths(string values)
+        {
+            int estimatedLength = values.Length + 1; // +1 for extra separator temporarily added at end
+            StringBuilder sb = StringBuilderCache.Acquire(estimatedLength);
+
+            for (int pos = 0; pos < values.Length; pos++)
+            {
+                string path;
+
+                int nextPos = values.IndexOf(Path.PathSeparator, pos);
+                if (nextPos == -1)
+                {
+                    path = values.Substring(pos);
+                    pos = values.Length - 1;
+                }
+                else
+                {
+                    path = values.Substring(pos, nextPos - pos);
+                    pos = nextPos;
+                }
+
+                // Skip empty directories
+                if (path.Length == 0)
+                    continue;
+
+                if (PathInternal.IsPartiallyQualified(path))
+                    throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"));
+
+                string appPath = NormalizePath(path, fullCheck: true);
+                sb.Append(appPath);
+                sb.Append(Path.PathSeparator);
+            }
+
+            // Strip the last separator
+            if (sb.Length > 0)
+            {
+                sb.Remove(sb.Length - 1, 1);
+            }
+
+            return StringBuilderCache.GetStringAndRelease(sb);
+        }
+
         internal static string NormalizePath(string path, bool fullCheck)
         {
             return Path.GetFullPath(path);
@@ -2401,7 +2294,6 @@ namespace System
 
         // This routine is called from unmanaged code to
         // set the default fusion context.
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetupDomain(bool allowRedirects, String path, String configFile, String[] propertyNames, String[] propertyValues)
         {
             // It is possible that we could have multiple threads initializing
@@ -2421,11 +2313,10 @@ namespace System
         }
 
 #if FEATURE_LOADER_OPTIMIZATION
-       [System.Security.SecurityCritical]  // auto-generated
        private void SetupLoaderOptimization(LoaderOptimization policy)
         {
             if(policy != LoaderOptimization.NotSpecified) {
-                Contract.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
+                Debug.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
                                 "It is illegal to change the Loader optimization on a domain");
 
                 FusionStore.LoaderOptimization = policy;
@@ -2434,11 +2325,9 @@ namespace System
         }
 #endif
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern IntPtr GetSecurityDescriptor();
 
-        [SecurityCritical]
         private void SetupDomainSecurity(Evidence appDomainEvidence,
                                          IntPtr creatorsSecurityDescriptor,
                                          bool publishAppDomain)
@@ -2451,7 +2340,6 @@ namespace System
 
         }
 
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         private static extern void SetupDomainSecurity(AppDomainHandle appDomain,
@@ -2459,7 +2347,6 @@ namespace System
                                                        IntPtr creatorsSecurityDescriptor,
                                                        [MarshalAs(UnmanagedType.Bool)] bool publishAppDomain);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void nSetupFriendlyName(string friendlyName);
 
@@ -2469,7 +2356,6 @@ namespace System
 #endif // FEATURE_COMINTEROP
 
 #if FEATURE_LOADER_OPTIMIZATION
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void UpdateLoaderOptimization(LoaderOptimization optimization);
 #endif
@@ -2481,15 +2367,12 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern String IsStringInterned(String str);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern String GetOrInternString(String str);
         
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet);
@@ -2497,7 +2380,6 @@ namespace System
         public PermissionSet PermissionSet
         {
             // SecurityCritical because permissions can contain sensitive information such as paths
-            [SecurityCritical]
             get
             {
                 PermissionSet grantSet = null;
@@ -2516,7 +2398,6 @@ namespace System
 
         public bool IsFullyTrusted
         {
-            [SecuritySafeCritical]
             get
             {
                 PermissionSet grantSet = null;
@@ -2535,11 +2416,9 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void nChangeSecurityPolicy();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail)]
         internal static extern void nUnload(Int32 domainInternal);
@@ -2698,7 +2577,6 @@ namespace System
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]              
         internal extern Int32 GetId();
@@ -2713,42 +2591,34 @@ namespace System
         }
 
 #if FEATURE_APPDOMAIN_RESOURCE_MONITORING
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void nEnableMonitoring();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool nMonitoringIsEnabled();
 
         // return -1 if ARM is not supported.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern Int64 nGetTotalProcessorTime();
 
         // return -1 if ARM is not supported.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern Int64 nGetTotalAllocatedMemorySize();
 
         // return -1 if ARM is not supported.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern Int64 nGetLastSurvivedMemorySize();
 
         // return -1 if ARM is not supported.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern Int64 nGetLastSurvivedProcessMemorySize();
 
         public static bool MonitoringIsEnabled
         {
-            [System.Security.SecurityCritical]
             get {
                 return nMonitoringIsEnabled();
             }
             
-            [System.Security.SecurityCritical]
             set {
                 if (value == false)
                 {
@@ -2765,7 +2635,6 @@ namespace System
         // Throws NotSupportedException if ARM is not enabled.
         public TimeSpan MonitoringTotalProcessorTime 
         {
-            [System.Security.SecurityCritical]
             get {
                 Int64 i64ProcessorTime = nGetTotalProcessorTime();
                 if (i64ProcessorTime == -1)
@@ -2781,7 +2650,6 @@ namespace System
         // Throws NotSupportedException if ARM is not enabled.
         public Int64 MonitoringTotalAllocatedMemorySize 
         {
-            [System.Security.SecurityCritical]
             get {
                 Int64 i64AllocatedMemory = nGetTotalAllocatedMemorySize();
                 if (i64AllocatedMemory == -1)
@@ -2799,7 +2667,6 @@ namespace System
         // Throws NotSupportedException if ARM is not enabled.
         public Int64 MonitoringSurvivedMemorySize
         {
-            [System.Security.SecurityCritical]
             get {
                 Int64 i64LastSurvivedMemory = nGetLastSurvivedMemorySize();
                 if (i64LastSurvivedMemory == -1)
@@ -2819,7 +2686,6 @@ namespace System
         // Throws NotSupportedException if ARM is not enabled.
         public static Int64 MonitoringSurvivedProcessMemorySize
         {
-            [System.Security.SecurityCritical]
             get {
                 Int64 i64LastSurvivedProcessMemory = nGetLastSurvivedProcessMemorySize();
                 if (i64LastSurvivedProcessMemory == -1)
index 696688e..71bc088 100644 (file)
@@ -15,13 +15,11 @@ namespace System
     using System.Security;
     using System.Runtime.InteropServices;
 
-    [System.Security.SecurityCritical]  // auto-generated_required
     [System.Runtime.InteropServices.ComVisible(true)]
     public class AppDomainManager : MarshalByRefObject
     {
         public AppDomainManager () {}
 
-        [System.Security.SecurityCritical]
         public virtual void InitializeNewDomain (AppDomainSetup appDomainInfo)
         {
             // By default, InitializeNewDomain does nothing. AppDomain.CreateAppDomainManager relies on this fact.
@@ -32,7 +30,6 @@ namespace System
 
         private Assembly m_entryAssembly = null;
         public virtual Assembly EntryAssembly {
-            [System.Security.SecurityCritical]  // auto-generated
             get {
                 // The default AppDomainManager sets the EntryAssembly depending on whether the
                 // AppDomain is a manifest application domain or not. In the first case, we parse
@@ -51,7 +48,6 @@ namespace System
         }
 
         internal static AppDomainManager CurrentAppDomainManager {
-            [System.Security.SecurityCritical]  // auto-generated
             get {
                 return AppDomain.CurrentDomain.DomainManager;
             }
index b7fe732..fc8a64c 100644 (file)
@@ -21,6 +21,7 @@ namespace System
     using System.Security;
     using System.Security.Policy;
     using Path = System.IO.Path;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Collections.Generic;
 
@@ -124,7 +125,6 @@ namespace System
         private bool _UseRandomizedStringHashing;
 #endif
 
-        [SecuritySafeCritical]
         internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData)
         {
             string[] mine = Value;
@@ -183,7 +183,6 @@ namespace System
             _LoaderOptimization = LoaderOptimization.NotSpecified;
         }
 
-        [System.Security.SecurityCritical] // auto-generated
         internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false) {
             char[] sep = {'\\', '/'};
             int i = imageLocation.LastIndexOfAny(sep);
@@ -231,19 +230,11 @@ namespace System
 
         public String ApplicationBase
         {
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #else
-            [System.Security.SecuritySafeCritical]
-            #endif
             [Pure]
             get {
                 return VerifyDir(GetUnsecureApplicationBase(), false);
             }
 
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             set {
                 Value[(int) LoaderInformation.ApplicationBaseValue] = NormalizePath(value, false);
             }
@@ -466,7 +457,6 @@ namespace System
 
         public String ConfigurationFile
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return VerifyDir(Value[(int) LoaderInformation.ConfigurationFileValue], true);
             }
@@ -561,12 +551,10 @@ namespace System
 
         public String DynamicBase
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return VerifyDir(Value[(int) LoaderInformation.DynamicBaseValue], true);
             }
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
             set {
                 if (value == null)
                     Value[(int) LoaderInformation.DynamicBaseValue] = null;
@@ -654,7 +642,6 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private String VerifyDir(String dir, bool normalize)
         {
             if (dir != null) {
@@ -669,7 +656,6 @@ namespace System
             return dir;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void VerifyDirList(String dirs)
         {
             if (dirs != null) {
@@ -683,7 +669,6 @@ namespace System
 
         internal String DeveloperPath
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get {
                 String dirs = Value[(int) LoaderInformation.DevPathValue];
                 VerifyDirList(dirs);
@@ -821,7 +806,6 @@ namespace System
 
         public String PrivateBinPath
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 String dirs = Value[(int) LoaderInformation.PrivateBinPathValue];
                 VerifyDirList(dirs);
@@ -860,7 +844,6 @@ namespace System
 
         public String ShadowCopyDirectories
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 String dirs = Value[(int) LoaderInformation.ShadowCopyDirectoriesValue];
                 VerifyDirList(dirs);
@@ -903,7 +886,6 @@ namespace System
 
         public String CachePath
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return VerifyDir(Value[(int) LoaderInformation.CachePathValue], false);
             }
@@ -922,7 +904,6 @@ namespace System
 
         public String LicenseFile
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return VerifyDir(Value[(int) LoaderInformation.LicenseFileValue], true);
             }
@@ -990,7 +971,7 @@ namespace System
             if(String.IsNullOrEmpty(s))
                 return -1;
 
-            Contract.Assert('A' == ACTAG_APP_BASE_URL[0]        , "Assumption violated");
+            Debug.Assert('A' == ACTAG_APP_BASE_URL[0]        , "Assumption violated");
             if (s[0]=='A' && s == ACTAG_APP_BASE_URL)        
                 return (int)LoaderInformation.ApplicationBaseValue;
 
index 0ce27ed..c5bc379 100644 (file)
@@ -16,19 +16,16 @@ namespace System {
     [StructLayout(LayoutKind.Sequential)]
     public struct ArgIterator
     {
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern ArgIterator(IntPtr arglist);
 
         // create an arg iterator that points at the first argument that
         // is not statically declared (that is the first ... arg)
         // 'arglist' is the value returned by the ARGLIST instruction
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public ArgIterator(RuntimeArgumentHandle arglist) : this(arglist.Value)
         {
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private unsafe extern ArgIterator(IntPtr arglist, void *ptr);
         
@@ -36,7 +33,6 @@ namespace System {
         // 'arglist' is the value returned by the ARGLIST instruction
         // This is much like the C va_start macro
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
 
         public unsafe ArgIterator(RuntimeArgumentHandle arglist, void* ptr) : this(arglist.Value, ptr)
@@ -45,7 +41,6 @@ namespace System {
 
         // Fetch an argument as a typed referece, advance the iterator.
         // Throws an exception if past end of argument list
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public TypedReference GetNextArg()
         {
@@ -58,14 +53,12 @@ namespace System {
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         // reference to TypedReference is banned, so have to pass result as void pointer
         private unsafe extern void FCallGetNextArg(void * result);
 
         // Alternate version of GetNextArg() intended primarily for IJW code
         // generated by VC's "va_arg()" construct. 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public TypedReference GetNextArg(RuntimeTypeHandle rth)
         {
@@ -96,7 +89,6 @@ namespace System {
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         // reference to TypedReference is banned, so have to pass result as void pointer
         private unsafe extern void InternalGetNextArg(void * result, RuntimeType rt);
@@ -107,16 +99,13 @@ namespace System {
         }
     
         // How many arguments are left in the list 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern int GetRemainingCount();
     
         // Gets the type of the current arg, does NOT advance the iterator
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern unsafe void* _GetNextArgType();
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe RuntimeTypeHandle GetNextArgType() 
         {
             return new RuntimeTypeHandle(Type.GetTypeFromHandleUnsafe((IntPtr)_GetNextArgType()));
index 0afa56f..f37b769 100644 (file)
@@ -82,7 +82,6 @@ namespace System {
             get { return m_paramName; }
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
index 4bcb537..661ebd2 100644 (file)
@@ -48,7 +48,6 @@ namespace System {
             SetErrorCode(__HResults.E_POINTER);   
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context) {
         }
     }
index 0b1ed4d..78a90db 100644 (file)
@@ -89,7 +89,6 @@ namespace System {
             get { return m_actualValue; }
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
index 1e89976..7bb6ebb 100644 (file)
@@ -19,6 +19,7 @@ namespace System {
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
     using System.Security;
+    using System.Diagnostics;
     using System.Security.Permissions;
     using System.Diagnostics.Contracts;
 
@@ -64,7 +65,6 @@ namespace System {
         }
 
         // Create instance will create an array
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static Array CreateInstance(Type elementType, int length)
         {
             if ((object)elementType == null)
@@ -82,7 +82,6 @@ namespace System {
             return InternalCreate((void*)t.TypeHandle.Value,1,&length,null);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static Array CreateInstance(Type elementType, int length1, int length2)
         {
             if ((object)elementType == null)
@@ -105,7 +104,6 @@ namespace System {
             return InternalCreate((void*)t.TypeHandle.Value,2,pLengths,null);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static Array CreateInstance(Type elementType, int length1, int length2, int length3)
         {
             if ((object)elementType == null)
@@ -132,7 +130,6 @@ namespace System {
             return InternalCreate((void*)t.TypeHandle.Value,3,pLengths,null);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static Array CreateInstance(Type elementType, params int[] lengths)
         {
             if ((object)elementType == null)
@@ -186,7 +183,6 @@ namespace System {
         }
 
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static Array CreateInstance(Type elementType, int[] lengths,int[] lowerBounds)
         {
             if (elementType == null)
@@ -219,41 +215,25 @@ namespace System {
                 fixed(int* pLowerBounds = lowerBounds)
                     return InternalCreate((void*)t.TypeHandle.Value,lengths.Length,pLengths,pLowerBounds);
         }
-        [System.Security.SecurityCritical]  // auto-generated
+
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private unsafe static extern Array InternalCreate(void* elementType,int rank,int *pLengths,int *pLowerBounds);
 
-        [SecurityCritical]
-#if !FEATURE_CORECLR
-        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
-#endif
         internal static Array UnsafeCreateInstance(Type elementType, int length)
         {
             return CreateInstance(elementType, length);
         }
 
-        [SecurityCritical]
-#if !FEATURE_CORECLR
-        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
-#endif
         internal static Array UnsafeCreateInstance(Type elementType, int length1, int length2)
         {
             return CreateInstance(elementType, length1, length2);
         }
 
-        [SecurityCritical]
-#if !FEATURE_CORECLR
-        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
-#endif
         internal static Array UnsafeCreateInstance(Type elementType, params int[] lengths)
         {
             return CreateInstance(elementType, lengths);
         }
 
-        [SecurityCritical]
-#if !FEATURE_CORECLR
-        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
-#endif
         internal static Array UnsafeCreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
         {
             return CreateInstance(elementType, lengths, lowerBounds);
@@ -262,7 +242,6 @@ namespace System {
         // Copies length elements from sourceArray, starting at index 0, to
         // destinationArray, starting at index 0.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         public static void Copy(Array sourceArray, Array destinationArray, int length)
         {
@@ -284,7 +263,6 @@ namespace System {
         // Copies length elements from sourceArray, starting at sourceIndex, to
         // destinationArray, starting at destinationIndex.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) 
         {
@@ -295,7 +273,6 @@ namespace System {
         // instance & might fail when called from within a CER, or if the
         // reliable flag is true, it will either always succeed or always
         // throw an exception with no side effects.
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable);
@@ -305,7 +282,6 @@ namespace System {
         // compatible array types based on the array element type - this 
         // method does not support casting, boxing, or primitive widening.
         // It will up-cast, assuming the array types are correct.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
         {
@@ -338,13 +314,11 @@ namespace System {
         // Sets length elements in array to 0 (or null for Object arrays), starting
         // at index.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static extern void Clear(Array array, int index, int length);
         
         // The various Get values...
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe Object GetValue(params int[] indices)
         {
             if (indices == null)
@@ -359,7 +333,6 @@ namespace System {
             return TypedReference.InternalToObject(&elemref);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe Object GetValue(int index)
         {
             if (Rank != 1)
@@ -371,7 +344,6 @@ namespace System {
             return TypedReference.InternalToObject(&elemref);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe Object GetValue(int index1, int index2)
         {
             if (Rank != 2)
@@ -387,7 +359,6 @@ namespace System {
             return TypedReference.InternalToObject(&elemref);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe Object GetValue(int index1, int index2, int index3)
         {
             if (Rank != 3)
@@ -463,7 +434,6 @@ namespace System {
         }
 
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe void SetValue(Object value,int index)
         {
             if (Rank != 1)
@@ -475,7 +445,6 @@ namespace System {
             InternalSetValue(&elemref,value);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe void SetValue(Object value,int index1, int index2)
         {
             if (Rank != 2)
@@ -491,7 +460,6 @@ namespace System {
             InternalSetValue(&elemref,value);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe void SetValue(Object value,int index1, int index2, int index3)
         {
             if (Rank != 3)
@@ -508,7 +476,6 @@ namespace System {
             InternalSetValue(&elemref,value);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe void SetValue(Object value,params int[] indices)
         {
             if (indices == null)
@@ -581,20 +548,17 @@ namespace System {
             this.SetValue(value, intIndices);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         // reference to TypedReference is banned, so have to pass result as pointer
         private unsafe extern void InternalGetReference(void * elemRef, int rank, int * pIndices);
 
         // Ideally, we would like to use TypedReference.SetValue instead. Unfortunately, TypedReference.SetValue
         // always throws not-supported exception
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private unsafe extern static void InternalSetValue(void * target, Object value);
 
         public extern int Length {
             [Pure]
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             [MethodImpl(MethodImplOptions.InternalCall)]
             get;
@@ -604,7 +568,7 @@ namespace System {
         private static int GetMedian(int low, int hi) {
             // Note both may be negative, if we are dealing with arrays w/ negative lower bounds.
             Contract.Requires(low <= hi);
-            Contract.Assert( hi - low >= 0, "Length overflow!");
+            Debug.Assert( hi - low >= 0, "Length overflow!");
             return low + ((hi - low) >> 1);
         }
 
@@ -619,14 +583,12 @@ namespace System {
         [ComVisible(false)]
         public extern long LongLength {
             [Pure]
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             [MethodImpl(MethodImplOptions.InternalCall)]
             get;
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern int GetLength(int dimension);
 
@@ -639,25 +601,21 @@ namespace System {
 
         public extern int Rank {
             [Pure]
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
             get;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Pure]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public extern int GetUpperBound(int dimension);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Pure]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern int GetLowerBound(int dimension);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern int GetDataPtrOffsetInternal();
@@ -894,7 +852,6 @@ namespace System {
         // is larger than the given search value.
         // 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) {
             if (array==null) 
@@ -965,7 +922,6 @@ namespace System {
             return ~lo;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
@@ -1329,7 +1285,6 @@ namespace System {
         // elements of the array are compared to the given value using the
         // Object.Equals method.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public static int IndexOf(Array array, Object value, int startIndex, int count) {
             if (array==null)
@@ -1424,7 +1379,6 @@ namespace System {
             return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
@@ -1465,7 +1419,6 @@ namespace System {
         // the array are compared to the given value using the Object.Equals
         // method.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public static int LastIndexOf(Array array, Object value, int startIndex, int count) {
             if (array==null)
@@ -1577,7 +1530,6 @@ namespace System {
             return EqualityComparer<T>.Default.LastIndexOf(array, value, startIndex, count);            
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private static extern bool TrySZLastIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
@@ -1602,7 +1554,6 @@ namespace System {
         // index index + (index + count - i - 1).
         // Reliability note: This may fail because it may have to box objects.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         public static void Reverse(Array array, int index, int length) {
             if (array==null) 
@@ -1646,7 +1597,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         private static extern bool TrySZReverse(Array array, int index, int count);
@@ -1780,7 +1730,6 @@ namespace System {
         // the IComparable interface, which in that case must be implemented
         // by all elements of the given section of the keys array.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) {
             if (keys==null)
@@ -1822,7 +1771,6 @@ namespace System {
             }
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         private static extern bool TrySZSort(Array keys, Array items, int left, int right);
@@ -1869,7 +1817,6 @@ namespace System {
             Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer) {
             if (array==null)
@@ -1893,7 +1840,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer) {
             if (keys==null)
@@ -2375,7 +2321,7 @@ namespace System {
             private int _endIndex; // cache array length, since it's a little slow.
 
             internal SZArrayEnumerator(Array array) {
-                Contract.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
+                Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
                 _array = array;
                 _index = -1;
                 _endIndex = array.Length;
@@ -2497,7 +2443,6 @@ namespace System {
         // if this is an array of value classes and that value class has a default constructor 
         // then this calls this default constructor on every element in the value class array.
         // otherwise this is a no-op.  Generally this method is called automatically by the compiler
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern void Initialize();
     }
@@ -2534,13 +2479,12 @@ namespace System {
     sealed class SZArrayHelper {
         // It is never legal to instantiate this class.
         private SZArrayHelper() {
-            Contract.Assert(false, "Hey! How'd I get here?");
+            Debug.Assert(false, "Hey! How'd I get here?");
         }
 
         // -----------------------------------------------------------
         // ------- Implement IEnumerable<T> interface methods --------
         // -----------------------------------------------------------
-        [SecuritySafeCritical]
         internal IEnumerator<T> GetEnumerator<T>() {
             //! Warning: "this" is an array, not an SZArrayHelper. See comments above
             //! or you may introduce a security hole!
@@ -2552,7 +2496,6 @@ namespace System {
         // -----------------------------------------------------------
         // ------- Implement ICollection<T> interface methods --------
         // -----------------------------------------------------------
-        [SecuritySafeCritical]
         void CopyTo<T>(T[] array, int index) {
             //! Warning: "this" is an array, not an SZArrayHelper. See comments above
             //! or you may introduce a security hole!
@@ -2561,7 +2504,6 @@ namespace System {
             Array.Copy(_this, 0, array, index, _this.Length);
         }
 
-        [SecuritySafeCritical]
         internal int get_Count<T>() {
             //! Warning: "this" is an array, not an SZArrayHelper. See comments above
             //! or you may introduce a security hole!
@@ -2572,7 +2514,6 @@ namespace System {
         // -----------------------------------------------------------
         // ---------- Implement IList<T> interface methods -----------
         // -----------------------------------------------------------
-        [SecuritySafeCritical]
         internal T get_Item<T>(int index) {
             //! Warning: "this" is an array, not an SZArrayHelper. See comments above
             //! or you may introduce a security hole!
@@ -2584,7 +2525,6 @@ namespace System {
             return _this[index];
         }
 
-        [SecuritySafeCritical]
         internal void set_Item<T>(int index, T value) {
             //! Warning: "this" is an array, not an SZArrayHelper. See comments above
             //! or you may introduce a security hole!
@@ -2601,7 +2541,6 @@ namespace System {
             ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
         }
 
-        [SecuritySafeCritical]
         bool Contains<T>(T value) {
             //! Warning: "this" is an array, not an SZArrayHelper. See comments above
             //! or you may introduce a security hole!
@@ -2620,7 +2559,6 @@ namespace System {
             ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);                     
         }
 
-        [SecuritySafeCritical]
         int IndexOf<T>(T value) {
             //! Warning: "this" is an array, not an SZArrayHelper. See comments above
             //! or you may introduce a security hole!
@@ -2657,7 +2595,7 @@ namespace System {
 
             internal SZGenericArrayEnumerator(T[] array, int endIndex) {
                 // We allow passing null array in case of empty enumerator. 
-                Contract.Assert(array != null || endIndex == -1, "endIndex should be -1 in the case of a null array (for the empty enumerator).");
+                Debug.Assert(array != null || endIndex == -1, "endIndex should be -1 in the case of a null array (for the empty enumerator).");
                 _array = array;
                 _index = -1;
                 _endIndex = endIndex;
index 1e76d17..b767e7b 100644 (file)
@@ -16,6 +16,7 @@
 using System.Collections;
 using System.Collections.Generic;
 using System.Runtime.InteropServices;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System
@@ -28,10 +29,10 @@ namespace System
     [Serializable]
     public struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
     {
-        private T[] _array;
-        private int _offset;
-        private int _count;
-        
+        private readonly T[] _array;
+        private readonly int _offset;
+        private readonly int _count;
+
         public ArraySegment(T[] array)
         {
             if (array == null)
@@ -64,10 +65,10 @@ namespace System
         {
             get
             {
-                Contract.Assert(    (null == _array && 0 == _offset && 0 == _count)
+                Debug.Assert(    (null == _array && 0 == _offset && 0 == _count)
                                  || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
                                 "ArraySegment is invalid");
-                
+
                 return _array;
             }
         }
@@ -83,7 +84,7 @@ namespace System
                 // after reading each field out of an ArraySegment into their stack.
                 Contract.Ensures(Contract.Result<int>() >= 0);
 
-                Contract.Assert(    (null == _array && 0 == _offset && 0 == _count)
+                Debug.Assert(    (null == _array && 0 == _offset && 0 == _count)
                                  || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
                                 "ArraySegment is invalid");
 
@@ -102,14 +103,23 @@ namespace System
                 // after reading each field out of an ArraySegment into their stack.
                 Contract.Ensures(Contract.Result<int>() >= 0);
 
-                Contract.Assert(     (null == _array && 0 == _offset && 0 == _count)
+                Debug.Assert(     (null == _array && 0 == _offset && 0 == _count)
                                   || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
                                 "ArraySegment is invalid");
 
                 return _count;
             }
         }
-        
+
+        public Enumerator GetEnumerator()
+        {
+            if (_array == null)
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
+            Contract.EndContractBlock();
+
+            return new Enumerator(this);
+        }
+
         public override int GetHashCode()
         {
             if (_array == null)
@@ -184,7 +194,7 @@ namespace System
 
             int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
 
-            Contract.Assert(index == -1 || 
+            Debug.Assert(index == -1 ||
                             (index >= _offset && index < _offset + _count));
 
             return index >= 0 ? index - _offset : -1;
@@ -246,7 +256,7 @@ namespace System
 
             int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
 
-            Contract.Assert(index == -1 ||
+            Debug.Assert(index == -1 ||
                             (index >= _offset && index < _offset + _count));
 
             return index >= 0;
@@ -269,46 +279,34 @@ namespace System
         #endregion
 
         #region IEnumerable<T>
-        IEnumerator<T> IEnumerable<T>.GetEnumerator()
-        {
-            if (_array == null)
-                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
-            Contract.EndContractBlock();
 
-            return new ArraySegmentEnumerator(this);
-        }
+        IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
         #endregion
 
         #region IEnumerable
-        IEnumerator IEnumerable.GetEnumerator()
-        {
-            if (_array == null)
-                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
-            Contract.EndContractBlock();
 
-            return new ArraySegmentEnumerator(this);
-        }
+        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
         #endregion
 
         [Serializable]
-        private sealed class ArraySegmentEnumerator : IEnumerator<T>
+        public struct Enumerator : IEnumerator<T>
         {
-            private T[] _array;
-            private int _start;
-            private int _end;
+            private readonly T[] _array;
+            private readonly int _start;
+            private readonly int _end; // cache Offset + Count, since it's a little slow
             private int _current;
 
-            internal ArraySegmentEnumerator(ArraySegment<T> arraySegment)
+            internal Enumerator(ArraySegment<T> arraySegment)
             {
                 Contract.Requires(arraySegment.Array != null);
                 Contract.Requires(arraySegment.Offset >= 0);
                 Contract.Requires(arraySegment.Count >= 0);
                 Contract.Requires(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
 
-                _array = arraySegment._array;
-                _start = arraySegment._offset;
-                _end = _start + arraySegment._count;
-                _current = _start - 1;
+                _array = arraySegment.Array;
+                _start = arraySegment.Offset;
+                _end = arraySegment.Offset + arraySegment.Count;
+                _current = arraySegment.Offset - 1;
             }
 
             public bool MoveNext()
@@ -325,19 +323,15 @@ namespace System
             {
                 get
                 {
-                    if (_current < _start) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
-                    if (_current >= _end) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
+                    if (_current < _start)
+                        ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
+                    if (_current >= _end)
+                        ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
                     return _array[_current];
                 }
             }
 
-            object IEnumerator.Current
-            {
-                get
-                {
-                    return Current;
-                }
-            }
+            object IEnumerator.Current => Current;
 
             void IEnumerator.Reset()
             {
index 66aa48c..e77450e 100644 (file)
@@ -10,6 +10,7 @@ namespace System {
     using System.Collections.Generic;
     using System.Runtime.InteropServices;
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Security;
     using System.Security.Permissions;
@@ -436,7 +437,6 @@ namespace System {
                 Environment.GetResourceString("Format_AttributeUsage", type));
         }
 
-        [System.Security.SecuritySafeCritical]
         private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount)
         {
             return (Attribute[])Array.UnsafeCreateInstance(elementType, elementCount);
@@ -637,7 +637,7 @@ namespace System {
                     return element.IsDefined(attributeType, false);
 
                 default: 
-                    Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
+                    Debug.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
             }
         }
@@ -830,7 +830,6 @@ namespace System {
         #endregion
 
         #region Object Overrides
-        [SecuritySafeCritical]
         public override bool Equals(Object obj)
         {
             if (obj == null)
@@ -891,7 +890,7 @@ namespace System {
 
                 // Attributes can only contain single-dimension arrays, so we don't need to worry about 
                 // multidimensional arrays.
-                Contract.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
+                Debug.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
                 for (int j = 0; j < thisValueArray.Length; j++)
                 {
                     if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j)))
@@ -905,7 +904,7 @@ namespace System {
                 // An object of type Attribute will cause a stack overflow. 
                 // However, this should never happen because custom attributes cannot contain values other than
                 // constants, single-dimensional arrays and typeof expressions.
-                Contract.Assert(!(thisValue is Attribute));
+                Debug.Assert(!(thisValue is Attribute));
                 if (!thisValue.Equals(thatValue))
                     return false;
             }
@@ -913,7 +912,6 @@ namespace System {
             return true;
         }
 
-        [SecuritySafeCritical]
         public override int GetHashCode()
         {
             Type type = GetType();
@@ -958,27 +956,5 @@ namespace System {
         #region Public Members
         public virtual bool IsDefaultAttribute() { return false; }
         #endregion
-
-#if !FEATURE_CORECLR
-        void _Attribute.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Attribute.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Attribute.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Attribute.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 }
index f5ad6aa..0ca6e61 100644 (file)
@@ -119,7 +119,6 @@ namespace System {
         
         [Pure]
         [Conditional("_LOGGING")]
-        [SecuritySafeCritical]
         static public void Log(String message) {
             if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
                 return;
@@ -132,7 +131,6 @@ namespace System {
 
         [Pure]
         [Conditional("_LOGGING")]
-        [SecuritySafeCritical]
         static public void Log(String switchName, String message) {
             if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
                 return;
@@ -160,7 +158,6 @@ namespace System {
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static int GetRegistryLoggingValues(out bool loggingEnabled, out bool logToConsole, out int logLevel, out bool perfWarnings, out bool correctnessWarnings, out bool safeHandleStackTraces);
 
-        [SecuritySafeCritical]
         private static void CheckRegistry() {
             if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
                 return;
@@ -207,7 +204,6 @@ namespace System {
             }
         }
 
-        [SecuritySafeCritical]
         internal static bool CheckEnabled(String switchName) {
             if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
                 return false;
@@ -220,7 +216,6 @@ namespace System {
             return ((int)logSwitch.MinimumLevel<=(int)LogLevel.Trace);
         }
 
-        [SecuritySafeCritical]
         private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch) {
             if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
             {
@@ -236,7 +231,6 @@ namespace System {
 
         [Pure]
         [Conditional("_LOGGING")]
-        [SecuritySafeCritical]
         public static void Log(String switchName, LogLevel level, params Object[]messages) {
             if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
                 return;
@@ -338,35 +332,9 @@ namespace System {
             System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, trace.ToString());
         }
 
-#if !FEATURE_CORECLR
-        // For logging errors related to the console - we often can't expect to
-        // write to stdout if it doesn't exist.
-        [SecuritySafeCritical]
-        [Conditional("_DEBUG")]
-        internal static void ConsoleError(String msg)
-        {
-            if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
-                return;
-
-            if (m_MakeConsoleErrorLoggingWork == null) {
-                PermissionSet perms = new PermissionSet();
-                perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
-                perms.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, Path.GetFullPath(".")));
-                m_MakeConsoleErrorLoggingWork = perms;
-            }
-            m_MakeConsoleErrorLoggingWork.Assert();
-                   
-            using (TextWriter err = File.AppendText("ConsoleErrors.log"))
-            {
-                err.WriteLine(msg);
-            }
-        }
-#endif // !FEATURE_CORECLR
-
         // For perf-related asserts.  On a debug build, set the registry key
         // BCLPerfWarnings to non-zero.
         [Conditional("_DEBUG")]
-        [SecuritySafeCritical]
         internal static void Perf(bool expr, String msg)
         {
             if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
@@ -386,7 +354,6 @@ namespace System {
         // BCLCorrectnessWarnings to non-zero.
         [Conditional("_DEBUG")]
 #if _DEBUG
-        [SecuritySafeCritical]
 #endif
         internal static void Correctness(bool expr, String msg)
         {
@@ -411,7 +378,6 @@ namespace System {
         }
 
 #if !BIT64 // 32
-        [SecuritySafeCritical]
 #endif
         internal static bool CorrectnessEnabled()
         {
index b71fcc3..3f3f4a5 100644 (file)
@@ -132,14 +132,11 @@ namespace System {
         }
 
         public String FusionLog {
-            [System.Security.SecuritySafeCritical]  // auto-generated
 #pragma warning disable CS0618 // Type or member is obsolete
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
 #pragma warning restore CS0618 // Type or member is obsolete
             get { return _fusionLog; }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             // Serialize data for our base classes.  base will verify info != null.
             base.GetObjectData(info, context);
index 5adbd8f..3a6d1c0 100644 (file)
@@ -15,6 +15,7 @@ namespace System {
     
     using System;
     using System.Runtime.CompilerServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Security;
 
@@ -56,7 +57,6 @@ namespace System {
       
         // Converts a short into an array of bytes with length
         // two.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static byte[] GetBytes(short value)
         {
             Contract.Ensures(Contract.Result<byte[]>() != null);
@@ -70,7 +70,6 @@ namespace System {
 
         // Converts an int into an array of bytes with length 
         // four.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static byte[] GetBytes(int value)
         {
             Contract.Ensures(Contract.Result<byte[]>() != null);
@@ -84,7 +83,6 @@ namespace System {
       
         // Converts a long into an array of bytes with length 
         // eight.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static byte[] GetBytes(long value)
         {
             Contract.Ensures(Contract.Result<byte[]>() != null);
@@ -128,7 +126,6 @@ namespace System {
       
         // Converts a float into an array of bytes with length 
         // four.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static byte[] GetBytes(float value)
         {
             Contract.Ensures(Contract.Result<byte[]>() != null);
@@ -139,7 +136,6 @@ namespace System {
       
         // Converts a double into an array of bytes with length 
         // eight.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static byte[] GetBytes(double value)
         {
             Contract.Ensures(Contract.Result<byte[]>() != null);
@@ -168,7 +164,6 @@ namespace System {
         }
       
         // Converts an array of bytes into a short.  
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static unsafe short ToInt16(byte[] value, int startIndex) {
             if( value == null)  {
                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
@@ -200,7 +195,6 @@ namespace System {
         }
       
         // Converts an array of bytes into an int.  
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static unsafe int ToInt32 (byte[] value, int startIndex) {
             if( value == null)  {
                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
@@ -231,7 +225,6 @@ namespace System {
         }
       
         // Converts an array of bytes into a long.  
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static unsafe long ToInt64 (byte[] value, int startIndex) {
             if (value == null)  {
                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
@@ -315,7 +308,6 @@ namespace System {
         }
     
         // Converts an array of bytes into a float.  
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe public static float ToSingle (byte[] value, int startIndex)
         {
             if (value == null)
@@ -331,7 +323,6 @@ namespace System {
         }
       
         // Converts an array of bytes into a double.  
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe public static double ToDouble (byte[] value, int startIndex)
         {
             if (value == null)
@@ -347,7 +338,7 @@ namespace System {
         }
       
         private static char GetHexValue(int i) {
-            Contract.Assert( i >=0 && i <16, "i is out of range.");
+            Debug.Assert( i >=0 && i <16, "i is out of range.");
             if (i<10) {
                 return (char)(i + '0');
             }
@@ -438,22 +429,18 @@ namespace System {
             return (value[startIndex]==0)?false:true;
         }
 
-        [SecuritySafeCritical]
         public static unsafe long DoubleToInt64Bits(double value) {
             return *((long *)&value);
         }
 
-        [SecuritySafeCritical]
         public static unsafe double Int64BitsToDouble(long value) {
             return *((double*)&value);
         }
 
-        [SecuritySafeCritical]
         public static unsafe int SingleToInt32Bits(float value) {
             return *((int*)&value);
         }
 
-        [SecuritySafeCritical]
         public static unsafe float Int32BitsToSingle(int value) {
             return *((float*)&value);
         }
index 72cbe01..eee2a81 100644 (file)
@@ -11,6 +11,7 @@ namespace System {
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.InteropServices;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Security;
     using System.Runtime;
@@ -28,7 +29,6 @@ namespace System {
         // respecting types.  This calls memmove internally.  The count and 
         // offset parameters here are in bytes.  If you want to use traditional
         // array element indices and counts, use Array.Copy.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void BlockCopy(Array src, int srcOffset,
             Array dst, int dstOffset, int count);
@@ -37,7 +37,6 @@ namespace System {
         // parameter validation has already been done.  The count and offset
         // parameters here are in bytes.  If you want to use traditional
         // array element indices and counts, use Array.Copy.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void InternalBlockCopy(Array src, int srcOffsetBytes,
             Array dst, int dstOffsetBytes, int byteCount);
@@ -47,10 +46,9 @@ namespace System {
         // It is however cross platform as the CRT hasn't ported their fast version to 64-bit
         // platforms.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count)
         {
-            Contract.Assert(src != null, "src should not be null");
+            Debug.Assert(src != null, "src should not be null");
 
             byte* pByte = src + index;
 
@@ -122,7 +120,6 @@ namespace System {
         
         // Returns a bool to indicate if the array is of primitive data types
         // or not.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool IsPrimitiveTypeArray(Array array);
 
@@ -132,11 +129,9 @@ namespace System {
         // This essentially does the following: 
         // return ((byte*)array) + index.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern byte _GetByte(Array array, int index);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static byte GetByte(Array array, int index)
         {
             // Is the array present?
@@ -160,11 +155,9 @@ namespace System {
         // This essentially does the following: 
         // *(((byte*)array) + index) = value.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _SetByte(Array array, int index, byte value);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void SetByte(Array array, int index, byte value)
         {
             // Is the array present?
@@ -190,11 +183,9 @@ namespace System {
         // This essentially does the following: 
         // return array.length * sizeof(array.UnderlyingElementType).
         //
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int _ByteLength(Array array);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static int ByteLength(Array array)
         {
             // Is the array present?
@@ -208,18 +199,16 @@ namespace System {
             return _ByteLength(array);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static void ZeroMemory(byte* src, long len)
         {
             while(len-- > 0)
                 *(src + len) = 0;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) {
-            Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
-            Contract.Assert(dest.Length - destIndex >= len, "not enough bytes in dest");
+            Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
+            Debug.Assert(dest.Length - destIndex >= len, "not enough bytes in dest");
             // If dest has 0 elements, the fixed statement will throw an 
             // IndexOutOfRangeException.  Special-case 0-byte copies.
             if (len==0)
@@ -229,12 +218,11 @@ namespace System {
             }
         }
 
-        [SecurityCritical]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len)
         {
-            Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");        
-            Contract.Assert(src.Length - srcIndex >= len, "not enough bytes in src");
+            Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");        
+            Debug.Assert(src.Length - srcIndex >= len, "not enough bytes in src");
             // If dest has 0 elements, the fixed statement will throw an 
             // IndexOutOfRangeException.  Special-case 0-byte copies.
             if (len==0)
@@ -254,7 +242,6 @@ namespace System {
         // 1. This method is given access to other internal dlls and this close to release we do not want to change it.
         // 2. It is difficult to get this right for arm and again due to release dates we would like to visit it later.
         [FriendAccessAllowed]
-        [System.Security.SecurityCritical]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
 #if ARM
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -262,13 +249,12 @@ namespace System {
 #else // ARM
         [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
         internal unsafe static void Memcpy(byte* dest, byte* src, int len) {
-            Contract.Assert(len >= 0, "Negative length in memcopy!");
+            Debug.Assert(len >= 0, "Negative length in memcopy!");
             Memmove(dest, src, (uint)len);
         }
 #endif // ARM
 
         // This method has different signature for x64 and other platforms and is done for performance reasons.
-        [System.Security.SecurityCritical]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal unsafe static void Memmove(byte* dest, byte* src, nuint len)
         {
@@ -524,7 +510,7 @@ namespace System {
             // We know due to the above switch-case that this loop will always run 1 iteration; max
             // bytes we copy before checking is 23 (7 to align the pointers, 16 for 1 iteration) so
             // the switch handles lengths 0-22.
-            Contract.Assert(end >= 7 && i <= end);
+            Debug.Assert(end >= 7 && i <= end);
 
             // This is separated out into a different variable, so the i + 16 addition can be
             // performed at the start of the pipeline and the loop condition does not have
@@ -595,7 +581,6 @@ namespace System {
 
         // Non-inlinable wrapper around the QCall that avoids poluting the fast path
         // with P/Invoke prolog/epilog.
-        [SecurityCritical]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [MethodImplAttribute(MethodImplOptions.NoInlining)]
         private unsafe static void _Memmove(byte* dest, byte* src, nuint len)
@@ -605,13 +590,11 @@ namespace System {
 
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
-        [SecurityCritical]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         extern private unsafe static void __Memmove(byte* dest, byte* src, nuint len);
 
         // The attributes on this method are chosen for best JIT performance. 
         // Please do not edit unless intentional.
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
         [CLSCompliant(false)]
         public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy)
@@ -626,7 +609,6 @@ namespace System {
 
         // The attributes on this method are chosen for best JIT performance. 
         // Please do not edit unless intentional.
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
         [CLSCompliant(false)]
         public static unsafe void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy)
index 2c24bf6..980412b 100644 (file)
@@ -139,28 +139,24 @@ namespace System {
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format, IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
index 0831c4b..01ad7c3 100644 (file)
@@ -19,12 +19,10 @@ namespace System {
 internal class CLRConfig {
     
     [FriendAccessAllowed]
-    [System.Security.SecurityCritical]
     [MethodImplAttribute(MethodImplOptions.InternalCall)]
     [SuppressUnmanagedCodeSecurity]
     internal static extern bool CheckLegacyManagedDeflateStream();
 
-    [System.Security.SecurityCritical]
     [MethodImplAttribute(MethodImplOptions.InternalCall)]
     [SuppressUnmanagedCodeSecurity]
     internal static extern bool CheckThrowUnobservedTaskExceptions();
index aba416c..b21da7f 100644 (file)
@@ -213,7 +213,6 @@ namespace System
                              int textLength,
                              int prefixLength);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void RunParser(String fileName);
     }
@@ -245,7 +244,6 @@ namespace System
             return Parse(fileName, configPath, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal ConfigNode Parse(String fileName, String configPath, bool skipSecurityStuff)
         {
             if (fileName == null)
@@ -291,11 +289,7 @@ namespace System
                 // Neither Exception nor ApplicationException are the "right" exceptions here.
                 // Desktop throws ApplicationException for backwards compatibility.
                 // On Silverlight we don't have ApplicationException, so fall back to Exception.
-#if FEATURE_CORECLR
                 throw new Exception(message, inner);
-#else
-                throw new ApplicationException(message, inner);
-#endif
             }
             return rootNode;
         }
@@ -440,11 +434,7 @@ namespace System
                     // Neither Exception nor ApplicationException are the "right" exceptions here.
                     // Desktop throws ApplicationException for backwards compatibility.
                     // On Silverlight we don't have ApplicationException, so fall back to Exception.
-#if FEATURE_CORECLR
                     throw new Exception(message);
-#else
-                    throw new ApplicationException(message);
-#endif
                 }
             }
         }
index 650b159..b9c9305 100644 (file)
@@ -18,6 +18,7 @@ namespace System {
     using System.Runtime;
     using System.Runtime.InteropServices;
     using System.Runtime.CompilerServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
 [System.Runtime.InteropServices.ComVisible(true)]
@@ -86,7 +87,7 @@ namespace System {
 
         // Return the Unicode category for Unicode character <= 0x00ff.      
         private static UnicodeCategory GetLatin1UnicodeCategory(char ch) {
-            Contract.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
+            Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
             return (UnicodeCategory)(categoryForLatin1[(int)ch]);
         }
      
@@ -911,7 +912,6 @@ namespace System {
         ** Convert an UTF32 value into a surrogate pair.
         ==============================================================================*/
         
-        [System.Security.SecuritySafeCritical]
         public static String ConvertFromUtf32(int utf32)
         {
             // For UTF32 values from U+00D800 ~ U+00DFFF, we should throw.  They
index fa51796..e7f1213 100644 (file)
@@ -31,9 +31,7 @@ namespace System.Collections {
     // of the ArrayList is automatically increased as required by reallocating the
     // internal array.
     // 
-#if FEATURE_CORECLR
     [FriendAccessAllowed]
-#endif
     [DebuggerTypeProxy(typeof(System.Collections.ArrayList.ArrayListDebugView))]   
     [DebuggerDisplay("Count = {Count}")]
     [Serializable]
@@ -554,9 +552,7 @@ namespace System.Collections {
     
         // Returns a read-only IList wrapper for the given IList.
         //
-#if FEATURE_CORECLR
         [FriendAccessAllowed]
-#endif
         public static IList ReadOnly(IList list) {
             if (list==null)
                 throw new ArgumentNullException(nameof(list));
@@ -729,7 +725,6 @@ namespace System.Collections {
     
         // Returns a thread-safe wrapper around an IList.
         //
-        [HostProtection(Synchronization=true)]
         public static IList Synchronized(IList list) {
             if (list==null)
                 throw new ArgumentNullException(nameof(list));
@@ -740,7 +735,6 @@ namespace System.Collections {
     
         // Returns a thread-safe wrapper around a ArrayList.
         //
-        [HostProtection(Synchronization=true)]
         public static ArrayList Synchronized(ArrayList list) {
             if (list==null)
                 throw new ArgumentNullException(nameof(list));
@@ -764,7 +758,6 @@ namespace System.Collections {
         // downcasting all elements.  This copy may fail and is an O(n) operation.
         // Internally, this implementation calls Array.Copy.
         //
-        [SecuritySafeCritical]
         public virtual Array ToArray(Type type) {
             if (type==null)
                 throw new ArgumentNullException(nameof(type));
@@ -1122,7 +1115,6 @@ namespace System.Collections {
                 return array;
             }
 
-            [SecuritySafeCritical]
             public override Array ToArray(Type type)
             {
                 if (type==null)
@@ -2519,7 +2511,6 @@ namespace System.Collections {
                 return array;
             }
 
-            [SecuritySafeCritical]
             public override Array ToArray(Type type) {
                 if (type==null)
                     throw new ArgumentNullException(nameof(type));
index d905a6e..0e3c78b 100644 (file)
@@ -83,7 +83,6 @@ namespace System.Collections {
             throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
index c704ea3..c1a6f75 100644 (file)
@@ -28,7 +28,6 @@ using System.Security.Permissions;
 
 namespace System.Collections.Concurrent
 {
-
     /// <summary>
     /// Represents a thread-safe collection of keys and values.
     /// </summary>
@@ -38,13 +37,9 @@ namespace System.Collections.Concurrent
     /// All public and protected members of <see cref="ConcurrentDictionary{TKey,TValue}"/> are thread-safe and may be used
     /// concurrently from multiple threads.
     /// </remarks>
-#if !FEATURE_CORECLR
-    [Serializable]
-#endif
     [ComVisible(false)]
     [DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
     [DebuggerDisplay("Count = {Count}")]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
     {
         /// <summary>
@@ -68,41 +63,20 @@ namespace System.Collections.Concurrent
                 m_comparer = comparer;
             }
         }
-#if !FEATURE_CORECLR
-        [NonSerialized]
-#endif
+
         private volatile Tables m_tables; // Internal tables of the dictionary       
         // NOTE: this is only used for compat reasons to serialize the comparer.
         // This should not be accessed from anywhere else outside of the serialization methods.
         internal IEqualityComparer<TKey> m_comparer; 
-#if !FEATURE_CORECLR
-        [NonSerialized]
-#endif
         private readonly bool m_growLockArray; // Whether to dynamically increase the size of the striped lock
 
         // How many times we resized becaused of collisions. 
         // This is used to make sure we don't resize the dictionary because of multi-threaded Add() calls
         // that generate collisions. Whenever a GrowTable() should be the only place that changes this
-#if !FEATURE_CORECLR
-        // The field should be have been marked as NonSerialized but because we shipped it without that attribute in 4.5.1.
-        // we can't add it back without breaking compat. To maximize compat we are going to keep the OptionalField attribute 
-        // This will prevent cases where the field was not serialized.
-        [OptionalField]
-#endif
         private int m_keyRehashCount;
 
-#if !FEATURE_CORECLR
-        [NonSerialized]
-#endif
         private int m_budget; // The maximum number of elements per lock before a resize operation is triggered
 
-#if !FEATURE_CORECLR // These fields are not used in CoreCLR
-        private KeyValuePair<TKey, TValue>[] m_serializationArray; // Used for custom serialization
-
-        private int m_serializationConcurrencyLevel; // used to save the concurrency level in serialization
-
-        private int m_serializationCapacity; // used to save the capacity in serialization
-#endif
         // The default concurrency level is DEFAULT_CONCURRENCY_MULTIPLIER * #CPUs. The higher the
         // DEFAULT_CONCURRENCY_MULTIPLIER, the more concurrent writes can take place without interference
         // and blocking, but also the more expensive operations that require all locks become (e.g. table
@@ -803,11 +777,6 @@ namespace System.Collections.Concurrent
 
                 bool resizeDesired = false;
                 bool lockTaken = false;
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR                
-                bool resizeDueToCollisions = false;
-#endif // !FEATURE_CORECLR
-#endif
 
                 try
                 {
@@ -821,12 +790,6 @@ namespace System.Collections.Concurrent
                         continue;
                     }
 
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
-                    int collisionCount = 0;
-#endif // !FEATURE_CORECLR
-#endif
-
                     // Try to find this key in the bucket
                     Node prev = null;
                     for (Node node = tables.m_buckets[bucketNo]; node != null; node = node.m_next)
@@ -864,24 +827,8 @@ namespace System.Collections.Concurrent
                             return false;
                         }
                         prev = node;
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
-                        collisionCount++;
-#endif // !FEATURE_CORECLR
-#endif
                     }
 
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
-                    if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer)) 
-                    {
-                        resizeDesired = true;
-                        resizeDueToCollisions = true;
-                    }
-#endif // !FEATURE_CORECLR
-#endif
-
                     // The key was not found in the bucket. Insert the key-value pair.
                     Volatile.Write<Node>(ref tables.m_buckets[bucketNo], new Node(key, value, hashcode, tables.m_buckets[bucketNo]));
                     checked
@@ -916,16 +863,7 @@ namespace System.Collections.Concurrent
                 if (resizeDesired)
                 {
 #if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
-                    if (resizeDueToCollisions)
-                    {
-                        GrowTable(tables, (IEqualityComparer<TKey>)HashHelpers.GetRandomizedEqualityComparer(comparer), true, m_keyRehashCount);
-                    }
-                    else
-#endif // !FEATURE_CORECLR
-                    {
-                        GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
-                    }
+                    GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
 #else
                     GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
 #endif
@@ -1850,13 +1788,6 @@ namespace System.Collections.Concurrent
         /// </summary>
         private void AcquireAllLocks(ref int locksAcquired)
         {
-#if !FEATURE_CORECLR
-            if (CDSCollectionETWBCLProvider.Log.IsEnabled())
-            {
-                CDSCollectionETWBCLProvider.Log.ConcurrentDictionary_AcquiringAllLocks(m_tables.m_buckets.Length);
-            }
-#endif //!FEATURE_CORECLR
-
             // First, acquire lock 0
             AcquireLocks(0, 1, ref locksAcquired);
 
@@ -1973,7 +1904,7 @@ namespace System.Collections.Concurrent
         [Conditional("DEBUG")]
         private void Assert(bool condition)
         {
-            Contract.Assert(condition);
+            Debug.Assert(condition);
         }
 
         /// <summary>
@@ -2038,46 +1969,5 @@ namespace System.Collections.Concurrent
                 m_enumerator.Reset();
             }
         }
-
-#if !FEATURE_CORECLR
-        /// <summary>
-        /// Get the data array to be serialized
-        /// </summary>
-        [OnSerializing]
-        private void OnSerializing(StreamingContext context)
-        {
-            Tables tables = m_tables;
-
-            // save the data into the serialization array to be saved
-            m_serializationArray = ToArray();
-            m_serializationConcurrencyLevel = tables.m_locks.Length;
-            m_serializationCapacity = tables.m_buckets.Length;
-            m_comparer = (IEqualityComparer<TKey>)HashHelpers.GetEqualityComparerForSerialization(tables.m_comparer);
-        }
-
-        /// <summary>
-        /// Construct the dictionary from a previously serialized one
-        /// </summary>
-        [OnDeserialized]
-        private void OnDeserialized(StreamingContext context)
-        {
-            KeyValuePair<TKey, TValue>[] array = m_serializationArray;
-
-            var buckets = new Node[m_serializationCapacity];
-            var countPerLock = new int[m_serializationConcurrencyLevel];
-
-            var locks = new object[m_serializationConcurrencyLevel];
-            for (int i = 0; i < locks.Length; i++)
-            {
-                locks[i] = new object();
-            }
-
-            m_tables = new Tables(buckets, locks, countPerLock, m_comparer);
-
-            InitializeFromCollection(array);
-            m_serializationArray = null;
-
-        }
-#endif
     }
 }
index d815ae9..7aa5971 100644 (file)
@@ -38,7 +38,6 @@ namespace System.Collections.Concurrent
     [ComVisible(false)]
     [DebuggerDisplay("Count = {Count}")]
     [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     [Serializable]
     public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
     {
@@ -77,7 +76,7 @@ namespace System.Collections.Concurrent
             int index = 0;
             foreach (T element in collection)
             {
-                Contract.Assert(index >= 0 && index < SEGMENT_SIZE);
+                Debug.Assert(index >= 0 && index < SEGMENT_SIZE);
                 localTail.UnsafeAdd(element);
                 index++;
 
@@ -125,7 +124,7 @@ namespace System.Collections.Concurrent
         [OnDeserialized]
         private void OnDeserialized(StreamingContext context)
         {
-            Contract.Assert(m_serializationArray != null);
+            Debug.Assert(m_serializationArray != null);
             InitializeFromCollection(m_serializationArray);
             m_serializationArray = null;
         }
@@ -689,7 +688,7 @@ namespace System.Collections.Concurrent
                 m_array = new T[SEGMENT_SIZE];
                 m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false
                 m_high = -1;
-                Contract.Assert(index >= 0);
+                Debug.Assert(index >= 0);
                 m_index = index;
                 m_source = source;
             }
@@ -721,7 +720,7 @@ namespace System.Collections.Concurrent
             /// <param name="value"></param>
             internal void UnsafeAdd(T value)
             {
-                Contract.Assert(m_high < SEGMENT_SIZE - 1);
+                Debug.Assert(m_high < SEGMENT_SIZE - 1);
                 m_high++;
                 m_array[m_high] = value;
                 m_state[m_high].m_value = true;
@@ -737,7 +736,7 @@ namespace System.Collections.Concurrent
             /// <returns>the reference to the new Segment</returns>
             internal Segment UnsafeGrow()
             {
-                Contract.Assert(m_high >= SEGMENT_SIZE - 1);
+                Debug.Assert(m_high >= SEGMENT_SIZE - 1);
                 Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
                 m_next = newSegment;
                 return newSegment;
@@ -753,7 +752,7 @@ namespace System.Collections.Concurrent
                 //no CAS is needed, since there is no contention (other threads are blocked, busy waiting)
                 Segment newSegment = new Segment(m_index + 1, m_source);  //m_index is Int64, we don't need to worry about overflow
                 m_next = newSegment;
-                Contract.Assert(m_source.m_tail == this);
+                Debug.Assert(m_source.m_tail == this);
                 m_source.m_tail = m_next;
             }
 
@@ -860,7 +859,7 @@ namespace System.Collections.Concurrent
                             {
                                 spinLocal.SpinOnce();
                             }
-                            Contract.Assert(m_source.m_head == this);
+                            Debug.Assert(m_source.m_head == this);
                             m_source.m_head = m_next;
                         }
                         return true;
index c418aa0..c36d96c 100644 (file)
@@ -45,10 +45,6 @@ namespace System.Collections.Concurrent
     /// </remarks>
     [DebuggerDisplay("Count = {Count}")]
     [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
-#if !FEATURE_CORECLR
-    [Serializable]
-#endif //!FEATURE_CORECLR
     public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
     {
         /// <summary>
@@ -70,15 +66,8 @@ namespace System.Collections.Concurrent
             }
         }
 
-#if !FEATURE_CORECLR
-        [NonSerialized]
-#endif //!FEATURE_CORECLR
         private volatile Node m_head; // The stack is a singly linked list, and only remembers the head.
 
-#if !FEATURE_CORECLR
-        private T[] m_serializationArray; // Used for custom serialization.
-#endif //!FEATURE_CORECLR
-
         private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff.
 
         /// <summary>
@@ -124,50 +113,6 @@ namespace System.Collections.Concurrent
             m_head = lastNode;
         }
 
-#if !FEATURE_CORECLR
-        /// <summary>
-        /// Get the data array to be serialized
-        /// </summary>
-        [OnSerializing]
-        private void OnSerializing(StreamingContext context)
-        {
-            // save the data into the serialization array to be saved
-            m_serializationArray = ToArray();
-        }
-
-        /// <summary>
-        /// Construct the stack from a previously seiralized one
-        /// </summary>
-        [OnDeserialized]
-        private void OnDeserialized(StreamingContext context)
-        {
-            Contract.Assert(m_serializationArray != null);
-            // Add the elements to our stack.  We need to add them from head-to-tail, to
-            // preserve the original ordering of the stack before serialization.
-            Node prevNode = null;
-            Node head = null;
-            for (int i = 0; i < m_serializationArray.Length; i++)
-            {
-                Node currNode = new Node(m_serializationArray[i]);
-
-                if (prevNode == null)
-                {
-                    head = currNode;
-                }
-                else
-                {
-                    prevNode.m_next = currNode;
-                }
-
-                prevNode = currNode;
-            }
-
-            m_head = head;
-            m_serializationArray = null;
-        }
-#endif //!FEATURE_CORECLR
-
-
         /// <summary>
         /// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty.
         /// </summary>
@@ -221,7 +166,6 @@ namespace System.Collections.Concurrent
             }
         }
 
-
         /// <summary>
         /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
         /// synchronized with the SyncRoot.
@@ -455,13 +399,6 @@ namespace System.Collections.Concurrent
             }
             while (Interlocked.CompareExchange(
                 ref m_head, head, tail.m_next) != tail.m_next);
-
-#if !FEATURE_CORECLR
-            if (CDSCollectionETWBCLProvider.Log.IsEnabled())
-            {
-                CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count);
-            }
-#endif // !FEATURE_CORECLR
         }
 
         /// <summary>
@@ -683,12 +620,6 @@ namespace System.Collections.Concurrent
                 // Is the stack empty?
                 if (head == null)
                 {
-#if !FEATURE_CORECLR
-                    if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
-                    {
-                        CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
-                    }
-#endif //!FEATURE_CORECLR
                     poppedHead = null;
                     return 0;
                 }
@@ -702,12 +633,6 @@ namespace System.Collections.Concurrent
                 // Try to swap the new head.  If we succeed, break out of the loop.
                 if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head)
                 {
-#if !FEATURE_CORECLR
-                    if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
-                    {
-                        CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
-                    }
-#endif //!FEATURE_CORECLR
                     // Return the popped Node.
                     poppedHead = head;
                     return nodesCount;
index 02263b7..33e3c88 100644 (file)
@@ -61,7 +61,6 @@ namespace System.Collections.Concurrent
     /// </ol>
     /// </para>
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public abstract class OrderablePartitioner<TSource> : Partitioner<TSource>
     {
         /// <summary>
index 3d54c14..0192b19 100644 (file)
@@ -44,7 +44,6 @@ namespace System.Collections.Concurrent
     /// </ol>
     /// </para>
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public abstract class Partitioner<TSource>
     {
         /// <summary>
index 5568f9b..9b36c05 100644 (file)
@@ -14,6 +14,7 @@
 using System.Collections.Generic;
 using System.Security.Permissions;
 using System.Threading;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 
@@ -26,9 +27,6 @@ namespace System.Collections.Concurrent
     /// non-blocking.  These behaviors can be overridden via this enumeration.
     /// </summary>
     [Flags]
-#if !FEATURE_CORECLR
-    [Serializable]
-#endif
     public enum EnumerablePartitionerOptions
     {
         /// <summary>
@@ -71,7 +69,6 @@ namespace System.Collections.Concurrent
     /// thread.
     /// </para>
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public static class Partitioner
     {
         /// <summary>
@@ -431,7 +428,7 @@ namespace System.Collections.Concurrent
                 //perform deferred allocating of the local variables. 
                 if (m_localOffset == null)
                 {
-                    Contract.Assert(m_currentChunkSize == null);
+                    Debug.Assert(m_currentChunkSize == null);
                     m_localOffset = new SharedInt(-1);
                     m_currentChunkSize = new SharedInt(0);
                     m_doublingCountdown = CHUNK_DOUBLING_RATE;
@@ -449,7 +446,7 @@ namespace System.Collections.Concurrent
                 {
                     // The second part of the || condition is necessary to handle the case when MoveNext() is called
                     // after a previous MoveNext call returned false.
-                    Contract.Assert(m_localOffset.Value == m_currentChunkSize.Value - 1 || m_currentChunkSize.Value == 0);
+                    Debug.Assert(m_localOffset.Value == m_currentChunkSize.Value - 1 || m_currentChunkSize.Value == 0);
 
                     //set the requested chunk size to a proper value
                     int requestedChunkSize;
@@ -470,11 +467,11 @@ namespace System.Collections.Concurrent
                     // Decrement your doubling countdown
                     m_doublingCountdown--;
 
-                    Contract.Assert(requestedChunkSize > 0 && requestedChunkSize <= m_maxChunkSize);
+                    Debug.Assert(requestedChunkSize > 0 && requestedChunkSize <= m_maxChunkSize);
                     //GrabNextChunk will update the value of m_currentChunkSize
                     if (GrabNextChunk(requestedChunkSize))
                     {
-                        Contract.Assert(m_currentChunkSize.Value <= requestedChunkSize && m_currentChunkSize.Value > 0);
+                        Debug.Assert(m_currentChunkSize.Value <= requestedChunkSize && m_currentChunkSize.Value > 0);
                         m_localOffset.Value = 0;
                         return true;
                     }
@@ -715,10 +712,10 @@ namespace System.Collections.Concurrent
                 /// </returns>
                 internal bool GrabChunk_Single(KeyValuePair<long,TSource>[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed)
                 {
-                    Contract.Assert(m_useSingleChunking, "Expected m_useSingleChecking to be true");
-                    Contract.Assert(requestedChunkSize == 1, "Got requested chunk size of " + requestedChunkSize + " when single-chunking was on");
-                    Contract.Assert(actualNumElementsGrabbed == 0, "Expected actualNumElementsGrabbed == 0, instead it is " + actualNumElementsGrabbed);
-                    Contract.Assert(destArray.Length == 1, "Expected destArray to be of length 1, instead its length is " + destArray.Length);
+                    Debug.Assert(m_useSingleChunking, "Expected m_useSingleChecking to be true");
+                    Debug.Assert(requestedChunkSize == 1, "Got requested chunk size of " + requestedChunkSize + " when single-chunking was on");
+                    Debug.Assert(actualNumElementsGrabbed == 0, "Expected actualNumElementsGrabbed == 0, instead it is " + actualNumElementsGrabbed);
+                    Debug.Assert(destArray.Length == 1, "Expected destArray to be of length 1, instead its length is " + destArray.Length);
 
                     lock (m_sharedLock)
                     {
@@ -764,8 +761,8 @@ namespace System.Collections.Concurrent
                 /// </returns>
                 internal bool GrabChunk_Buffered(KeyValuePair<long,TSource>[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed)
                 {
-                    Contract.Assert(requestedChunkSize > 0);
-                    Contract.Assert(!m_useSingleChunking, "Did not expect to be in single-chunking mode");
+                    Debug.Assert(requestedChunkSize > 0);
+                    Debug.Assert(!m_useSingleChunking, "Did not expect to be in single-chunking mode");
 
                     TryCopyFromFillBuffer(destArray, requestedChunkSize, ref actualNumElementsGrabbed);
                     
@@ -803,7 +800,7 @@ namespace System.Collections.Concurrent
                                 while( m_activeCopiers > 0) sw.SpinOnce();
                             }
 
-                            Contract.Assert(m_sharedIndex != null); //already been allocated in MoveNext() before calling GrabNextChunk
+                            Debug.Assert(m_sharedIndex != null); //already been allocated in MoveNext() before calling GrabNextChunk
 
                             // Now's the time to actually enumerate the source
 
@@ -940,7 +937,7 @@ namespace System.Collections.Concurrent
                 /// </returns>
                 override protected bool GrabNextChunk(int requestedChunkSize)
                 {
-                    Contract.Assert(requestedChunkSize > 0);
+                    Debug.Assert(requestedChunkSize > 0);
 
                     if (HasNoElementsLeft)
                     {
@@ -973,8 +970,8 @@ namespace System.Collections.Concurrent
                     {
                         //we only set it from false to true once
                         //we should never set it back in any circumstances
-                        Contract.Assert(value);
-                        Contract.Assert(!m_hasNoElementsLeft.Value);
+                        Debug.Assert(value);
+                        Debug.Assert(!m_hasNoElementsLeft.Value);
                         m_hasNoElementsLeft.Value = true;
                     }
                 }
@@ -988,8 +985,8 @@ namespace System.Collections.Concurrent
                         {
                             throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
                         }
-                        Contract.Assert(m_localList != null);
-                        Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
+                        Debug.Assert(m_localList != null);
+                        Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
                         return (m_localList[m_localOffset.Value]);
                     }
                 }
@@ -1127,11 +1124,11 @@ namespace System.Collections.Concurrent
             /// </returns>
             override protected bool GrabNextChunk(int requestedChunkSize)
             {
-                Contract.Assert(requestedChunkSize > 0);
+                Debug.Assert(requestedChunkSize > 0);
 
                 while (!HasNoElementsLeft)
                 {
-                    Contract.Assert(m_sharedIndex != null);
+                    Debug.Assert(m_sharedIndex != null);
                     // use the new Volatile.Read method because it is cheaper than Interlocked.Read on AMD64 architecture
                     long oldSharedIndex = Volatile.Read(ref m_sharedIndex.Value);
 
@@ -1173,13 +1170,13 @@ namespace System.Collections.Concurrent
             {
                 get
                 {
-                    Contract.Assert(m_sharedIndex != null);
+                    Debug.Assert(m_sharedIndex != null);
                     // use the new Volatile.Read method because it is cheaper than Interlocked.Read on AMD64 architecture
                     return Volatile.Read(ref m_sharedIndex.Value) >= SourceCount - 1;
                 }
                 set
                 {
-                    Contract.Assert(false);
+                    Debug.Assert(false);
                 }
             }
 
@@ -1268,7 +1265,7 @@ namespace System.Collections.Concurrent
                             throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
                         }
 
-                        Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
+                        Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
                         return new KeyValuePair<long, TSource>(m_startIndex + m_localOffset.Value,
                             m_sharedReader[m_startIndex + m_localOffset.Value]);
                     }
@@ -1352,7 +1349,7 @@ namespace System.Collections.Concurrent
                             throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
                         }
 
-                        Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
+                        Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
                         return new KeyValuePair<long, TSource>(m_startIndex + m_localOffset.Value,
                             m_sharedReader[m_startIndex + m_localOffset.Value]);
                     }
@@ -1539,7 +1536,7 @@ namespace System.Collections.Concurrent
             internal StaticIndexRangePartitionerForIList(IList<TSource> list)
                 : base()
             {
-                Contract.Assert(list != null);
+                Debug.Assert(list != null);
                 m_list = list;
             }
             override protected int SourceCount
@@ -1565,7 +1562,7 @@ namespace System.Collections.Concurrent
             internal StaticIndexRangePartitionForIList(IList<TSource> list, int startIndex, int endIndex)
                 : base(startIndex, endIndex)
             {
-                Contract.Assert(startIndex >= 0 && endIndex <= list.Count - 1);
+                Debug.Assert(startIndex >= 0 && endIndex <= list.Count - 1);
                 m_list = list;
             }
 
@@ -1579,7 +1576,7 @@ namespace System.Collections.Concurrent
                         throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
                     }
 
-                    Contract.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
+                    Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
                     return (new KeyValuePair<long, TSource>(m_offset, m_list[m_offset]));
                 }
             }
@@ -1597,7 +1594,7 @@ namespace System.Collections.Concurrent
             internal StaticIndexRangePartitionerForArray(TSource[] array)
                 : base()
             {
-                Contract.Assert(array != null);
+                Debug.Assert(array != null);
                 m_array = array;
             }
             override protected int SourceCount
@@ -1622,7 +1619,7 @@ namespace System.Collections.Concurrent
             internal StaticIndexRangePartitionForArray(TSource[] array, int startIndex, int endIndex)
                 : base(startIndex, endIndex)
             {
-                Contract.Assert(startIndex >= 0 && endIndex <= array.Length - 1);
+                Debug.Assert(startIndex >= 0 && endIndex <= array.Length - 1);
                 m_array = array;
             }
 
@@ -1636,7 +1633,7 @@ namespace System.Collections.Concurrent
                         throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
                     }
 
-                    Contract.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
+                    Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
                     return (new KeyValuePair<long, TSource>(m_offset, m_array[m_offset]));
                 }
             }
@@ -1704,30 +1701,15 @@ namespace System.Collections.Concurrent
 
             if (typeof(TSource).IsValueType)
             {
-#if !FEATURE_CORECLR // Marshal.SizeOf is not supported in CoreCLR
-
-                if (typeof(TSource).StructLayoutAttribute.Value == LayoutKind.Explicit)
-                {
-                    chunkSize = Math.Max(1, DEFAULT_BYTES_PER_CHUNK / Marshal.SizeOf(typeof(TSource)));
-                }
-                else
-                {
-                    // We choose '128' because this ensures, no matter the actual size of the value type,
-                    // the total bytes used will be a multiple of 128. This ensures it's cache aligned.
-                    chunkSize = 128;
-                }
-#else
                 chunkSize = 128;
-#endif
             }
             else
             {
-                Contract.Assert((DEFAULT_BYTES_PER_CHUNK % IntPtr.Size) == 0, "bytes per chunk should be a multiple of pointer size");
+                Debug.Assert((DEFAULT_BYTES_PER_CHUNK % IntPtr.Size) == 0, "bytes per chunk should be a multiple of pointer size");
                 chunkSize = (DEFAULT_BYTES_PER_CHUNK / IntPtr.Size);
             }
             return chunkSize;
         }
         #endregion
-
     }
 }
index 65061c7..298ac3e 100644 (file)
@@ -17,6 +17,7 @@ namespace System.Collections.Generic
     using System;
     using System.Globalization;
     using System.Runtime.CompilerServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Runtime.Versioning;
     
@@ -72,7 +73,6 @@ namespace System.Collections.Generic
             }
         }                
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static IArraySortHelper<T> CreateArraySortHelper()
         {
             if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
@@ -90,8 +90,8 @@ namespace System.Collections.Generic
 
         public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
         {
-            Contract.Assert(keys != null, "Check the arguments in the caller!");
-            Contract.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+            Debug.Assert(keys != null, "Check the arguments in the caller!");
+            Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
 
             // Add a try block here to detect IComparers (or their
             // underlying IComparables, etc) that are bogus.
@@ -135,9 +135,9 @@ namespace System.Collections.Generic
 
         internal static void Sort(T[] keys, int index, int length, Comparison<T> comparer)
         {
-            Contract.Assert(keys != null, "Check the arguments in the caller!");
-            Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
-            Contract.Assert(comparer != null, "Check the arguments in the caller!");
+            Debug.Assert(keys != null, "Check the arguments in the caller!");
+            Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+            Debug.Assert(comparer != null, "Check the arguments in the caller!");
 
             // Add a try block here to detect bogus comparisons
             try
@@ -380,8 +380,8 @@ namespace System.Collections.Generic
 
         public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
         {
-            Contract.Assert(keys != null, "Check the arguments in the caller!");
-            Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+            Debug.Assert(keys != null, "Check the arguments in the caller!");
+            Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
 
             try
             {
@@ -406,8 +406,8 @@ namespace System.Collections.Generic
 
         public int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
         {
-            Contract.Assert(array != null, "Check the arguments in the caller!");
-            Contract.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
+            Debug.Assert(array != null, "Check the arguments in the caller!");
+            Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
 
             try
             {
@@ -689,7 +689,6 @@ namespace System.Collections.Generic
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static IArraySortHelper<TKey, TValue> CreateArraySortHelper()
         {
             if (typeof(IComparable<TKey>).IsAssignableFrom(typeof(TKey)))
@@ -705,8 +704,8 @@ namespace System.Collections.Generic
 
         public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
         {
-            Contract.Assert(keys != null, "Check the arguments in the caller!");  // Precondition on interface method
-            Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+            Debug.Assert(keys != null, "Check the arguments in the caller!");  // Precondition on interface method
+            Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
 
             // Add a try block here to detect IComparers (or their
             // underlying IComparables, etc) that are bogus.
@@ -960,8 +959,8 @@ namespace System.Collections.Generic
     {
         public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
         {
-            Contract.Assert(keys != null, "Check the arguments in the caller!");
-            Contract.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+            Debug.Assert(keys != null, "Check the arguments in the caller!");
+            Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
             
             // Add a try block here to detect IComparers (or their
             // underlying IComparables, etc) that are bogus.
index 6e65daf..4f06b0a 100644 (file)
@@ -7,6 +7,7 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 //using System.Globalization;
 using System.Runtime.CompilerServices;
@@ -42,7 +43,6 @@ namespace System.Collections.Generic
         // Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
         // saves the right instantiations
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static Comparer<T> CreateComparer()
         {
             object result = null;
@@ -196,7 +196,7 @@ namespace System.Collections.Generic
     {
         public Int32EnumComparer()
         {
-            Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+            Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
         }
         
         // Used by the serialization engine.
@@ -216,7 +216,6 @@ namespace System.Collections.Generic
         public override int GetHashCode() =>
             GetType().GetHashCode();
 
-        [SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // Previously Comparer<T> was not specialized for enums,
@@ -232,7 +231,7 @@ namespace System.Collections.Generic
     {
         public UInt32EnumComparer()
         {
-            Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+            Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
         }
         
         // Used by the serialization engine.
@@ -252,7 +251,6 @@ namespace System.Collections.Generic
         public override int GetHashCode() =>
             GetType().GetHashCode();
 
-        [SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             info.SetType(typeof(ObjectComparer<T>));
@@ -264,7 +262,7 @@ namespace System.Collections.Generic
     {
         public Int64EnumComparer()
         {
-            Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+            Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
         }
         
         // Used by the serialization engine.
@@ -284,7 +282,6 @@ namespace System.Collections.Generic
         public override int GetHashCode() =>
             GetType().GetHashCode();
 
-        [SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             info.SetType(typeof(ObjectComparer<T>));
@@ -296,7 +293,7 @@ namespace System.Collections.Generic
     {
         public UInt64EnumComparer()
         {
-            Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+            Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
         }
         
         // Used by the serialization engine.
@@ -316,7 +313,6 @@ namespace System.Collections.Generic
         public override int GetHashCode() =>
             GetType().GetHashCode();
 
-        [SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             info.SetType(typeof(ObjectComparer<T>));
index 2bbe7f9..dc50530 100644 (file)
@@ -91,12 +91,12 @@ namespace System.Collections.Generic {
             if (capacity > 0) Initialize(capacity);
             this.comparer = comparer ?? EqualityComparer<TKey>.Default;
 
-#if FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR
+#if FEATURE_RANDOMIZED_STRING_HASHING
             if (HashHelpers.s_UseRandomizedStringHashing && comparer == EqualityComparer<string>.Default)
             {
                 this.comparer = (IEqualityComparer<TKey>) NonRandomizedStringEqualityComparer.Default;
             }
-#endif // FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR
+#endif // FEATURE_RANDOMIZED_STRING_HASHING
         }
 
         public Dictionary(IDictionary<TKey,TValue> dictionary): this(dictionary, null) {}
@@ -302,7 +302,6 @@ namespace System.Collections.Generic {
             return new Enumerator(this, Enumerator.KeyValuePair);
         }        
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
@@ -362,11 +361,7 @@ namespace System.Collections.Generic {
             for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
                 if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
                     if (add) { 
-#if FEATURE_CORECLR
                         ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
-#else
-                        ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
-#endif
                     }
                     entries[i].value = value;
                     version++;
@@ -401,8 +396,6 @@ namespace System.Collections.Generic {
             version++;
 
 #if FEATURE_RANDOMIZED_STRING_HASHING
-
-#if FEATURE_CORECLR
             // In case we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
             // in this case will be EqualityComparer<string>.Default.
             // Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will 
@@ -413,14 +406,6 @@ namespace System.Collections.Generic {
                 comparer = (IEqualityComparer<TKey>) EqualityComparer<string>.Default;
                 Resize(entries.Length, true);
             }
-#else
-            if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer)) 
-            {
-                comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(comparer);
-                Resize(entries.Length, true);
-            }
-#endif // FEATURE_CORECLR
-
 #endif
 
         }
@@ -474,7 +459,7 @@ namespace System.Collections.Generic {
         }
 
         private void Resize(int newSize, bool forceNewHashCodes) {
-            Contract.Assert(newSize >= entries.Length);
+            Debug.Assert(newSize >= entries.Length);
             int[] newBuckets = new int[newSize];
             for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
             Entry[] newEntries = new Entry[newSize];
index 8fd2548..3731114 100644 (file)
@@ -32,7 +32,6 @@ namespace System.Collections.Generic
         // Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
         // saves the right instantiations
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static EqualityComparer<T> CreateComparer()
         {
             Contract.Ensures(Contract.Result<EqualityComparer<T>>() != null);
@@ -294,7 +293,6 @@ namespace System.Collections.Generic
             GetType().GetHashCode();
     }
 
-#if FEATURE_CORECLR
     // NonRandomizedStringEqualityComparer is the comparer used by default with the Dictionary<string,...> 
     // As the randomized string hashing is turned on by default on coreclr, we need to keep the performance not affected 
     // as much as possible in the main stream scenarios like Dictionary<string,>
@@ -320,7 +318,6 @@ namespace System.Collections.Generic
             return obj.GetLegacyNonRandomizedHashCode();
         }
     }
-#endif // FEATURE_CORECLR
 
     // Performance of IndexOf on byte array is very important for some scenarios.
     // We will call the C runtime function memchr, which is optimized.
@@ -337,7 +334,6 @@ namespace System.Collections.Generic
             return b.GetHashCode();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe override int IndexOf(byte[] array, byte value, int startIndex, int count) {
             if (array==null)
                 throw new ArgumentNullException(nameof(array));
@@ -391,7 +387,6 @@ namespace System.Collections.Generic
         // This is used by the serialization engine.
         protected EnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
 
-        [SecurityCritical]
         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) {
@@ -489,7 +484,6 @@ namespace System.Collections.Generic
         // This is used by the serialization engine.
         public LongEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
 
-        [SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // The LongEnumEqualityComparer does not exist on 4.0 so we need to serialize this comparer as ObjectEqualityComparer
@@ -552,14 +546,12 @@ namespace System.Collections.Generic
         }
 
         [Pure]
-        [SecuritySafeCritical]
         public int GetHashCode(String obj) {
             if(obj == null) return 0;
             return String.InternalMarvin32HashString(obj, obj.Length, _entropy);
         }
 
         [Pure]
-        [SecuritySafeCritical]
         public int GetHashCode(Object obj) {
             if(obj == null) return 0;
 
@@ -611,7 +603,6 @@ namespace System.Collections.Generic
         }
 
         [Pure]
-        [SecuritySafeCritical]
         public int GetHashCode(Object obj) {
             if(obj == null) return 0;
 
index 9e77906..3e2947f 100644 (file)
@@ -1029,8 +1029,8 @@ namespace System.Collections.Generic {
 
         private void AddEnumerable(IEnumerable<T> enumerable)
         {
-            Contract.Assert(enumerable != null);
-            Contract.Assert(!(enumerable is ICollection<T>), "We should have optimized for this beforehand.");
+            Debug.Assert(enumerable != null);
+            Debug.Assert(!(enumerable is ICollection<T>), "We should have optimized for this beforehand.");
 
             using (IEnumerator<T> en = enumerable.GetEnumerator())
             {
index 8d74c8f..d4c7d8d 100644 (file)
@@ -23,10 +23,7 @@ namespace System.Collections {
     using System.Runtime.CompilerServices;
     using System.Runtime.ConstrainedExecution;
     using System.Diagnostics.Contracts;
-#if !FEATURE_CORECLR
-    using System.Security.Cryptography;
-#endif
-   
+
     // The Hashtable class represents a dictionary of associated keys and values
     // with constant lookup time.
     // 
@@ -290,7 +287,7 @@ namespace System.Collections {
             loadsize = (int)(this.loadFactor * hashsize);
             isWriterInProgress = false;
             // Based on the current algorithm, loadsize must be less than hashsize.
-            Contract.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
+            Debug.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
         }
     
         // Constructs a new hashtable with the given initial capacity and load
@@ -444,14 +441,11 @@ namespace System.Collections {
         // Removes all entries from this hashtable.
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public virtual void Clear() {
-            Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously!  Don't do that - use Hashtable.Synchronized.");
+            Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously!  Don't do that - use Hashtable.Synchronized.");
 
             if (count == 0 && occupancy == 0)
                 return;
 
-#if !FEATURE_CORECLR
-            Thread.BeginCriticalRegion();
-#endif
             isWriterInProgress = true;
             for (int i = 0; i < buckets.Length; i++){
                 buckets[i].hash_coll = 0;
@@ -463,9 +457,6 @@ namespace System.Collections {
             occupancy = 0;
             UpdateVersion();            
             isWriterInProgress = false;    
-#if !FEATURE_CORECLR
-            Thread.EndCriticalRegion();
-#endif
         }
         
         // Clone returns a virtually identical copy of this hash table.  This does
@@ -526,9 +517,7 @@ namespace System.Collections {
             } while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
             return false;
         }
-    
-    
-        
+
         // Checks if this hashtable contains an entry with the given value. The
         // values of the entries of the hashtable are compared to the given value
         // using the Object.Equals method. This method performs a linear
@@ -750,28 +739,23 @@ namespace System.Collections {
             for (nb = 0; nb < buckets.Length; nb++){
                 bucket oldb = buckets[nb];
                 if ((oldb.key != null) && (oldb.key != buckets)) {
-                    int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF);                              
+                    int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF);
                     putEntry(newBuckets, oldb.key, oldb.val, hashcode);
                 }
             }
-            
+
             // New bucket[] is good to go - replace buckets and other internal state.
-#if !FEATURE_CORECLR
-            Thread.BeginCriticalRegion();            
-#endif
             isWriterInProgress = true;
             buckets = newBuckets;
             loadsize = (int)(loadFactor * newsize);
             UpdateVersion();
             isWriterInProgress = false;
-#if !FEATURE_CORECLR
-            Thread.EndCriticalRegion();   
-#endif
+
             // minimun size of hashtable is 3 now and maximum loadFactor is 0.72 now.
-            Contract.Assert(loadsize < newsize, "Our current implementaion means this is not possible.");
+            Debug.Assert(loadsize < newsize, "Our current implementaion means this is not possible.");
             return;
         }
-    
+
         // Returns an enumerator for this hashtable.
         // If modifications made to the hashtable while an enumeration is
         // in progress, the MoveNext and Current methods of the
@@ -820,7 +804,7 @@ namespace System.Collections {
         // 
         protected virtual bool KeyEquals(Object item, Object key)
         {
-            Contract.Assert(key != null, "key can't be null here!");
+            Debug.Assert(key != null, "key can't be null here!");
             if( Object.ReferenceEquals(buckets, item)) {
                 return false;
             }
@@ -913,36 +897,14 @@ namespace System.Collections {
 
                     // We pretty much have to insert in this order.  Don't set hash
                     // code until the value & key are set appropriately.
-#if !FEATURE_CORECLR
-                    Thread.BeginCriticalRegion(); 
-#endif
-                    isWriterInProgress = true;                    
+                    isWriterInProgress = true;
                     buckets[bucketNumber].val = nvalue;
                     buckets[bucketNumber].key  = key;
                     buckets[bucketNumber].hash_coll |= (int) hashcode;
                     count++;
                     UpdateVersion();
                     isWriterInProgress = false;   
-#if !FEATURE_CORECLR
-                    Thread.EndCriticalRegion();
-#endif
 
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
-                    // coreclr has the randomized string hashing on by default so we don't need to resize at this point
-
-                    if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer)) 
-                    {
-                        // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
-                        // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
-                        if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
-                        {
-                            _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
-                            rehash(buckets.Length, true);
-                        }
-                    }
-#endif // !FEATURE_CORECLR
-#endif // FEATURE_RANDOMIZED_STRING_HASHING
                     return;
                 }
 
@@ -954,31 +916,10 @@ namespace System.Collections {
                     if (add) {
                         throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", buckets[bucketNumber].key, key));
                     }
-#if !FEATURE_CORECLR
-                    Thread.BeginCriticalRegion();
-#endif
-                    isWriterInProgress = true;                    
+                    isWriterInProgress = true;
                     buckets[bucketNumber].val = nvalue;
-                    UpdateVersion();                    
+                    UpdateVersion();
                     isWriterInProgress = false; 
-#if !FEATURE_CORECLR
-                    Thread.EndCriticalRegion();   
-#endif
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
-                    if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer)) 
-                    {
-                        // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
-                        // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
-                        if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
-                        {
-                            _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
-                            rehash(buckets.Length, true);
-                        }
-                    }
-#endif // !FEATURE_CORECLR
-#endif
                     return;
                 }
 
@@ -992,7 +933,7 @@ namespace System.Collections {
                     }
                 }
 
-                bucketNumber = (int) (((long)bucketNumber + incr)% (uint)buckets.Length);               
+                bucketNumber = (int) (((long)bucketNumber + incr)% (uint)buckets.Length);
             } while (++ntry < buckets.Length);
 
             // This code is here if and only if there were no buckets without a collision bit set in the entire table
@@ -1000,47 +941,27 @@ namespace System.Collections {
             {
                 // We pretty much have to insert in this order.  Don't set hash
                 // code until the value & key are set appropriately.
-#if !FEATURE_CORECLR
-                Thread.BeginCriticalRegion();  
-#endif
-                isWriterInProgress = true;                    
+                isWriterInProgress = true;
                 buckets[emptySlotNumber].val = nvalue;
                 buckets[emptySlotNumber].key  = key;
                 buckets[emptySlotNumber].hash_coll |= (int) hashcode;
                 count++;
                 UpdateVersion();                
                 isWriterInProgress = false;     
-#if !FEATURE_CORECLR
-                Thread.EndCriticalRegion(); 
-#endif
 
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
-                if(buckets.Length > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer)) 
-                {
-                    // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
-                    // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
-                    if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
-                    {
-                        _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
-                        rehash(buckets.Length, true);
-                    }
-                }
-#endif // !FEATURE_CORECLR
-#endif
                 return;
             }
-    
+
             // If you see this assert, make sure load factor & count are reasonable.
             // Then verify that our double hash function (h2, described at top of file)
             // meets the requirements described above. You should never see this assert.
-            Contract.Assert(false, "hash table insert failed!  Load factor too high, or our double hashing function is incorrect.");
+            Debug.Assert(false, "hash table insert failed!  Load factor too high, or our double hashing function is incorrect.");
             throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HashInsertFailed"));
         }
     
         private void putEntry (bucket[] newBuckets, Object key, Object nvalue, int hashcode)
         {
-            Contract.Assert(hashcode >= 0, "hashcode >= 0");  // make sure collision bit (sign bit) wasn't set.
+            Debug.Assert(hashcode >= 0, "hashcode >= 0");  // make sure collision bit (sign bit) wasn't set.
 
             uint seed = (uint) hashcode;
             uint incr = (uint)(1 + ((seed * HashPrime) % ((uint)newBuckets.Length - 1)));
@@ -1058,7 +979,7 @@ namespace System.Collections {
                 newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
                     occupancy++;
                 }
-                bucketNumber = (int) (((long)bucketNumber + incr)% (uint)newBuckets.Length);                
+                bucketNumber = (int) (((long)bucketNumber + incr)% (uint)newBuckets.Length);
             } while (true);
         }
     
@@ -1072,7 +993,7 @@ namespace System.Collections {
                 throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
             }
             Contract.EndContractBlock();
-            Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously!  Don't do that - use Hashtable.Synchronized.");
+            Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously!  Don't do that - use Hashtable.Synchronized.");
 
             uint seed;
             uint incr;
@@ -1086,9 +1007,6 @@ namespace System.Collections {
                 b = buckets[bn];
                 if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && 
                     KeyEquals (b.key, key)) {
-#if !FEATURE_CORECLR
-                    Thread.BeginCriticalRegion();    
-#endif
                     isWriterInProgress = true;
                     // Clear hash_coll field, then key, then value
                     buckets[bn].hash_coll &= unchecked((int)0x80000000);
@@ -1102,12 +1020,9 @@ namespace System.Collections {
                     count--;
                     UpdateVersion();
                     isWriterInProgress = false; 
-#if !FEATURE_CORECLR
-                    Thread.EndCriticalRegion();   
-#endif
                     return;
                 }
-                bn = (int) (((long)bn + incr)% (uint)buckets.Length);                               
+                bn = (int) (((long)bn + incr)% (uint)buckets.Length);
             } while (b.hash_coll < 0 && ++ntry < buckets.Length);
 
             //throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound"));
@@ -1131,7 +1046,6 @@ namespace System.Collections {
     
         // Returns a thread-safe wrapper for a Hashtable.
         //
-        [HostProtection(Synchronization=true)]
         public static Hashtable Synchronized(Hashtable table) {
             if (table==null)
                 throw new ArgumentNullException(nameof(table));
@@ -1143,7 +1057,6 @@ namespace System.Collections {
         // The ISerializable Implementation
         //
 
-        [System.Security.SecurityCritical]
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
@@ -1399,7 +1312,6 @@ namespace System.Collections {
             **           context -- the StreamingContext for the current serialization (ignored)
             **Exceptions: ArgumentNullException if info is null.
             ==============================================================================*/
-            [System.Security.SecurityCritical]  // auto-generated
             public override void GetObjectData(SerializationInfo info, StreamingContext context) {
                 if (info==null) {
                     throw new ArgumentNullException(nameof(info));
@@ -1746,7 +1658,7 @@ namespace System.Collections {
             // Note that this check works even when _items.Length overflowed thanks to the (uint) cast
             if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize)
             {
-                Contract.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
+                Debug.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
                 return MaxPrimeArrayLength;
             }
 
@@ -1765,7 +1677,7 @@ namespace System.Collections {
 
         public static IEqualityComparer GetRandomizedEqualityComparer(object comparer)
         {
-            Contract.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer); 
+            Debug.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer); 
 
             if(comparer == null) {
                 return new System.Collections.Generic.RandomizedObjectEqualityComparer();
@@ -1781,7 +1693,7 @@ namespace System.Collections {
                 return cmp.GetRandomizedEqualityComparer();
             }
 
-            Contract.Assert(false, "Missing case in GetRandomizedEqualityComparer!");
+            Debug.Assert(false, "Missing case in GetRandomizedEqualityComparer!");
 
             return null;
         }
@@ -1804,9 +1716,6 @@ namespace System.Collections {
         }
 
         private const int bufferSize = 1024;
-#if !FEATURE_CORECLR
-        private static RandomNumberGenerator rng;
-#endif
         private static byte[] data;
         private static int currentIndex = bufferSize;
         private static readonly object lockObj = new Object();
@@ -1821,18 +1730,10 @@ namespace System.Collections {
                     if(data == null)
                     {
                         data = new byte[bufferSize];
-                        Contract.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
-#if !FEATURE_CORECLR
-                        rng = RandomNumberGenerator.Create();
-#endif
-
+                        Debug.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
                     }
 
-#if FEATURE_CORECLR
                     Microsoft.Win32.Win32Native.Random(true, data, data.Length);
-#else
-                    rng.GetBytes(data);
-#endif
                     currentIndex = 0;
                 }
 
index 7313d71..b6fe6de 100644 (file)
@@ -53,7 +53,7 @@ namespace System.Collections.ObjectModel
         /// </summary>
         new private List<TItem> Items {
             get {
-                Contract.Assert(base.Items is List<TItem>);
+                Debug.Assert(base.Items is List<TItem>);
 
                 return (List<TItem>)base.Items;
             }
@@ -233,7 +233,7 @@ namespace System.Collections.ObjectModel
         }
 
         private void RemoveKey(TKey key) {
-            Contract.Assert(key != null, "key shouldn't be null!");
+            Debug.Assert(key != null, "key shouldn't be null!");
             if (dict != null) {
                 dict.Remove(key);
             }
index 658dc48..4a480a2 100644 (file)
@@ -60,10 +60,8 @@ namespace System.Collections {
     // 
     [DebuggerTypeProxy(typeof(System.Collections.SortedList.SortedListDebugView))]  
     [DebuggerDisplay("Count = {Count}")]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
+    [System.Runtime.InteropServices.ComVisible(true)]
     [Obsolete("Non-generic collections have been deprecated. Please use collections in System.Collections.Generic.")]
-#endif
     [Serializable]
     public class SortedList : IDictionary, ICloneable
     {
@@ -213,7 +211,7 @@ namespace System.Collections {
                     }
                     else {
                         // size can only be zero here.
-                        Contract.Assert( _size == 0, "Size is not zero");
+                        Debug.Assert( _size == 0, "Size is not zero");
                         keys = emptyArray;
                         values = emptyArray;                      
                     }
@@ -530,7 +528,6 @@ namespace System.Collections {
         
         // Returns a thread-safe SortedList.
         //
-        [HostProtection(Synchronization=true)]
         public static SortedList Synchronized(SortedList list) {
             if (list==null)
                 throw new ArgumentNullException(nameof(list));
index d36c8e9..c3ad15a 100644 (file)
@@ -189,7 +189,6 @@ namespace System.Collections {
     
         // Returns a synchronized Stack.
         //
-        [HostProtection(Synchronization=true)]
         public static Stack Synchronized(Stack stack) {
             if (stack==null)
                 throw new ArgumentNullException(nameof(stack));
index 893a47e..bb2f02a 100644 (file)
@@ -2,8 +2,6 @@
 // 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.Runtime.CompilerServices;
 
 namespace System
@@ -12,16 +10,7 @@ namespace System
     internal static class CompatibilitySwitches
     {
         private static bool s_AreSwitchesSet;
-
-#if FEATURE_CORECLR
         private static bool s_useLatestBehaviorWhenTFMNotSpecified; // Which behavior to use when the TFM is not specified.
-#endif //FEATURE_CORECLR
-
-#if !FEATURE_CORECLR
-        private static bool s_isNetFx40TimeSpanLegacyFormatMode;
-        private static bool s_isNetFx40LegacySecurityPolicy;
-        private static bool s_isNetFx45LegacyManagedDeflateStream;
-#endif //!FEATURE_CORECLR
 
         public static bool IsCompatibilityBehaviorDefined
         {
@@ -39,51 +28,14 @@ namespace System
 
         internal static void InitializeSwitches()
         {
-#if !FEATURE_CORECLR
-            s_isNetFx40TimeSpanLegacyFormatMode = IsCompatibilitySwitchSet("NetFx40_TimeSpanLegacyFormatMode");
-            s_isNetFx40LegacySecurityPolicy = IsCompatibilitySwitchSet("NetFx40_LegacySecurityPolicy");
-            s_isNetFx45LegacyManagedDeflateStream = IsCompatibilitySwitchSet("NetFx45_LegacyManagedDeflateStream");
-#endif //FEATURE_CORECLR
-
             s_AreSwitchesSet = true;
         }
 
-#if !FEATURE_CORECLR
-        public static bool IsAppEarlierThanSilverlight4
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public static bool IsAppEarlierThanWindowsPhone8
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public static bool IsAppEarlierThanWindowsPhoneMango
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-#endif //!FEATURE_CORECLR
-
         public static bool IsNetFx40TimeSpanLegacyFormatMode
         {
             get
             {
-#if !FEATURE_CORECLR
-                return s_isNetFx40TimeSpanLegacyFormatMode;
-#else
                 return false;
-#endif //!FEATURE_CORECLR
             }
         }
 
@@ -91,11 +43,7 @@ namespace System
         {
             get
             {
-#if !FEATURE_CORECLR
-                return s_isNetFx40LegacySecurityPolicy;
-#else
                 return false;
-#endif //!FEATURE_CORECLR
             }
         }
 
@@ -103,11 +51,7 @@ namespace System
         {
             get
             {
-#if !FEATURE_CORECLR
-                return s_isNetFx45LegacyManagedDeflateStream;
-#else
                 return false;
-#endif //!FEATURE_CORECLR
             }
         }
     }
index 50ebba0..0e14f93 100644 (file)
@@ -19,6 +19,7 @@ using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Runtime.Versioning;
 using System.Security;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 
@@ -146,13 +147,13 @@ namespace System {
 #if _DEBUG
         private static bool TriggerAsserts = DoAsserts();
         private static bool DoAsserts() {
-            Contract.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null");
-            Contract.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)");
-            Contract.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty),
+            Debug.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null");
+            Debug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)");
+            Debug.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty),
                             "[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)");
-            Contract.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String),
+            Debug.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String),
                             "[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)");
-            Contract.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int),
+            Debug.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int),
                             "[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)");
             return true;
         }
@@ -1129,7 +1130,6 @@ namespace System {
             throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static int ToInt32(decimal value) {
             return Decimal.FCallToInt32(value);
         }
@@ -2114,7 +2114,6 @@ namespace System {
         }
 
         // Convert the byte value to a string in base fromBase
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String ToString (byte value, int toBase) {
             if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
                 throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
@@ -2124,7 +2123,6 @@ namespace System {
         }
 
         // Convert the Int16 value to a string in base fromBase
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String ToString (short value, int toBase) {
             if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
                 throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
@@ -2134,7 +2132,6 @@ namespace System {
         }
 
         // Convert the Int32 value to a string in base toBase
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String ToString (int value, int toBase) {
             if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
                 throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
@@ -2144,7 +2141,6 @@ namespace System {
         }
 
         // Convert the Int64 value to a string in base toBase
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String ToString (long value, int toBase) {
             if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
                 throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
@@ -2176,7 +2172,6 @@ namespace System {
             return ToBase64String(inArray, offset, length, Base64FormattingOptions.None);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(false)]
         public static unsafe String ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) {
             //Do data verfication
@@ -2223,7 +2218,6 @@ namespace System {
             return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(false)]
         public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options) {
             //Do data verfication
@@ -2279,7 +2273,6 @@ namespace System {
             return retVal;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static unsafe int ConvertToBase64Array(char* outChars, byte* inData, int offset, int length, bool insertLineBreaks) {
             int lengthmod3 = length%3;
             int calcLength = offset + (length - lengthmod3);
@@ -2366,7 +2359,6 @@ namespace System {
         /// </summary>
         /// <param name="s">The string to convert</param>
         /// <returns>The array of bytes represented by the specifed Base64 string.</returns>
-        [SecuritySafeCritical] 
         public static Byte[] FromBase64String(String s) {
 
             // "s" is an unfortunate parameter name, but we need to keep it for backward compat.
@@ -2392,7 +2384,6 @@ namespace System {
         /// <param name="offset">A position within the input array.</param>
         /// <param name="length">Number of element to convert.</param>
         /// <returns>The array of bytes represented by the specified Base64 encoding characters.</returns>
-        [SecuritySafeCritical]
         public static Byte[] FromBase64CharArray(Char[] inArray, Int32 offset, Int32 length) {
 
             if (inArray == null)
@@ -2428,12 +2419,11 @@ namespace System {
         /// <param name="inputPtr">Pointer to the first input char</param>
         /// <param name="inputLength">Number of input chars</param>
         /// <returns></returns>
-        [SecurityCritical] 
         private static unsafe Byte[] FromBase64CharPtr(Char* inputPtr, Int32 inputLength) {
 
             // The validity of parameters much be checked by callers, thus we are Critical here.
 
-            Contract.Assert(0 <= inputLength);
+            Debug.Assert(0 <= inputLength);
 
             // We need to get rid of any trailing white spaces.
             // Otherwise we would be rejecting input such as "abc= ":
@@ -2448,7 +2438,7 @@ namespace System {
             // Compute the output length:
             Int32 resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength);
 
-            Contract.Assert(0 <= resultLength);
+            Debug.Assert(0 <= resultLength);
 
             // resultLength can be zero. We will still enter FromBase64_Decode and process the input.
             // It may either simply write no bytes (e.g. input = " ") or throw (e.g. input = "ab").
@@ -2482,7 +2472,6 @@ namespace System {
         /// <param name="destLength">Max length of the preallocated result buffer</param>
         /// <returns>If the result buffer was not large enough to write all result bytes, return -1;
         /// Otherwise return the number of result bytes actually produced.</returns>
-        [SecurityCritical]
         private static unsafe Int32 FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength) {
 
             // You may find this method weird to look at. It\92s written for performance, not aesthetics.
@@ -2583,12 +2572,12 @@ namespace System {
             }}  // unchecked while
 
             // 'd be nice to have an assert that we never get here, but CS0162: Unreachable code detected.
-            // Contract.Assert(false, "We only leave the above loop by jumping; should never get here.");
+            // Debug.Assert(false, "We only leave the above loop by jumping; should never get here.");
 
             // We jump here out of the loop if we hit an '=':
             _EqualityCharEncountered:
 
-            Contract.Assert(currCode == intEq);
+            Debug.Assert(currCode == intEq);
 
             // Recall that inputPtr is now one position past where '=' was read.
             // '=' can only be at the last input pos:
@@ -2662,13 +2651,12 @@ namespace System {
         /// Walk the entire input counting white spaces and padding chars, then compute result length
         /// based on 3 bytes per 4 chars.
         /// </summary>
-        [SecurityCritical]
         private static unsafe Int32 FromBase64_ComputeResultLength(Char* inputPtr, Int32 inputLength) {
 
             const UInt32 intEq =    (UInt32) '=';            
             const UInt32 intSpace = (UInt32) ' ';
 
-            Contract.Assert(0 <= inputLength);
+            Debug.Assert(0 <= inputLength);
 
             Char* inputEndPtr = inputPtr + inputLength;
             Int32 usefulInputLength = inputLength;
@@ -2691,11 +2679,11 @@ namespace System {
                 }
             }
 
-            Contract.Assert(0 <= usefulInputLength);
+            Debug.Assert(0 <= usefulInputLength);
             
             // For legal input, we can assume that 0 <= padding < 3. But it may be more for illegal input.
             // We will notice it at decode when we see a '=' at the wrong place.
-            Contract.Assert(0 <= padding);
+            Debug.Assert(0 <= padding);
 
             // Perf: reuse the variable that stored the number of '=' to store the number of bytes encoded by the
             // last group that contains the '=':
index d29ad24..05a0980 100644 (file)
@@ -46,7 +46,6 @@ namespace System {
     
         // Converts a Currency to a Decimal.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal ToDecimal(Currency c)
         {
             Decimal result = new Decimal ();
@@ -54,7 +53,6 @@ namespace System {
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallToDecimal(ref Decimal result,Currency c);
     }
index f98117b..804bbcc 100644 (file)
@@ -21,21 +21,18 @@ namespace System {
     using System;
     using System.Diagnostics.Contracts;
     using System.Text;
-    using System.Threading;
     using System.Collections;
     using System.Globalization;
     using System.Runtime.CompilerServices;
     using System.Runtime.Versioning;
 
-#if FEATURE_CORECLR
     [Obsolete("System.CurrentSystemTimeZone has been deprecated.  Please investigate the use of System.TimeZoneInfo.Local instead.")]
-#endif
     [Serializable]
     internal class CurrentSystemTimeZone : TimeZone
     {
         // The per-year information is cached in in this instance value. As a result it can
         // be cleaned up by CultureInfo.ClearCachedData, which will clear the instance of this object
-        private Hashtable m_CachedDaylightChanges = new Hashtable();
+        private readonly Hashtable m_CachedDaylightChanges = new Hashtable();
 
         // Standard offset in ticks to the Universal time if
         // no daylight saving is in used.
@@ -148,21 +145,6 @@ namespace System {
             return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
         }
 
-        // Private object for locking instead of locking on a public type for SQL reliability work.
-        private static Object s_InternalSyncObject;
-        private static Object InternalSyncObject
-        {
-            get
-            {
-                if (s_InternalSyncObject == null)
-                {
-                    Object o = new Object();
-                    Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
-                }
-                return s_InternalSyncObject;
-            }
-        }
-
         public override DaylightTime GetDaylightChanges(int year)
         {
             if (year < 1 || year > 9999)
@@ -202,7 +184,7 @@ namespace System {
                     currentDaylightChanges = new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero); 
                 }
 
-                lock (InternalSyncObject)
+                lock (m_CachedDaylightChanges)
                 {
                     if (!m_CachedDaylightChanges.Contains(objYear))
                     {
index 130366d..6f80af7 100644 (file)
@@ -26,7 +26,6 @@ namespace System {
         
         public static readonly DBNull Value = new DBNull();
 
-        [System.Security.SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context) {
             UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.NullUnity, null, null);
         }
index 4b4570f..e93346c 100644 (file)
@@ -556,20 +556,6 @@ namespace System {
             return millis * TicksPerMillisecond;
         }
 
-#if !FEATURE_CORECLR
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
-        [SuppressUnmanagedCodeSecurity]
-        [return: MarshalAs(UnmanagedType.Bool)]
-        internal static extern bool LegacyParseMode();
-
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
-        [SuppressUnmanagedCodeSecurity]
-        [return: MarshalAs(UnmanagedType.Bool)]
-        internal static extern bool EnableAmPmParseAdjustment();
-#endif
-
         // Checks if this DateTime is equal to a given object. Returns
         // true if the given object is a boxed DateTime and its value
         // is equal to the value of this DateTime. Returns false
@@ -912,7 +898,6 @@ namespace System {
         }
 
         public static DateTime UtcNow {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
                 // following code is tuned for speed. Don't change it without running benchmark.
@@ -924,7 +909,6 @@ namespace System {
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern long GetSystemTimeAsFileTime();
 
index 40efcaf..5bdaa18 100644 (file)
@@ -11,6 +11,7 @@ namespace System {
     using System.Runtime.CompilerServices;
     using System.Runtime.Serialization;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // DateTimeOffset is a value type that consists of a DateTime and a time zone offset, 
@@ -513,7 +514,6 @@ namespace System {
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info == null) {
                 throw new ArgumentNullException(nameof(info));
@@ -751,7 +751,7 @@ namespace System {
         private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) {
             // The key validation is that both the UTC and clock times fit. The clock time is validated
             // by the DateTime constructor.
-            Contract.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
+            Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
             // This operation cannot overflow because offset should have already been validated to be within
             // 14 hours and the DateTime instance is more than that distance from the boundaries of Int64.
             Int64 utcTicks = dateTime.Ticks - offset.Ticks;
index 0fb2bd1..fd16697 100644 (file)
@@ -206,13 +206,11 @@ namespace System {
     
         // Constructs a Decimal from a float value.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern Decimal(float value);
     
         // Constructs a Decimal from a double value.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern Decimal(double value);
     
@@ -335,7 +333,6 @@ namespace System {
     
         // Adds two Decimal values.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal Add(Decimal d1, Decimal d2)
         {
             FCallAddSub (ref d1, ref d2, DECIMAL_ADD);
@@ -346,11 +343,9 @@ namespace System {
         // of the operation.  Passing in DECIMAL_ADD or DECIMAL_NEG for bSign indicates
         // addition or subtraction, respectively.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallAddSub(ref Decimal d1, ref Decimal d2, byte bSign);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallAddSubOverflowed(ref Decimal d1, ref Decimal d2, byte bSign, ref bool overflowed);
         
@@ -363,13 +358,11 @@ namespace System {
         // Compares two Decimal values, returning an integer that indicates their
         // relationship.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static int Compare(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private static extern int FCallCompare(ref Decimal d1, ref Decimal d2);
@@ -380,7 +373,6 @@ namespace System {
         // null is considered to be less than any instance.
         // If object is not of type Decimal, this method throws an ArgumentException.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public int CompareTo(Object value)
         {
             if (value == null)
@@ -392,7 +384,6 @@ namespace System {
             return FCallCompare(ref this, ref other);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public int CompareTo(Decimal value)
         {
             return FCallCompare(ref this, ref value);
@@ -400,7 +391,6 @@ namespace System {
         
         // Divides two Decimal values.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal Divide(Decimal d1, Decimal d2)
         {
             FCallDivide (ref d1, ref d2);
@@ -410,11 +400,9 @@ namespace System {
         // FCallDivide divides two decimal values.  On return, d1 contains the result
         // of the operation.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallDivide(ref Decimal d1, ref Decimal d2);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallDivideOverflowed(ref Decimal d1, ref Decimal d2, ref bool overflowed);
 
@@ -423,7 +411,6 @@ namespace System {
         // if the given object is a boxed Decimal and its value is equal to the
         // value of this Decimal. Returns false otherwise.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool Equals(Object value) {
             if (value is Decimal) {
                 Decimal other = (Decimal)value;
@@ -432,7 +419,6 @@ namespace System {
             return false;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public bool Equals(Decimal value)
         {
             return FCallCompare(ref this, ref value) == 0;
@@ -440,14 +426,12 @@ namespace System {
 
         // Returns the hash code for this Decimal.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern override int GetHashCode();
     
         // Compares two Decimal values for equality. Returns true if the two
         // Decimal values are equal, or false if they are not equal.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool Equals(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2) == 0;
         }
@@ -455,14 +439,12 @@ namespace System {
         // Rounds a Decimal to an integer value. The Decimal argument is rounded
         // towards negative infinity.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal Floor(Decimal d)
         {
             FCallFloor (ref d);
             return d;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallFloor(ref Decimal d);    
 
@@ -471,25 +453,21 @@ namespace System {
         // optionally followed by a decimal point (".") and another sequence of
         // digits.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider));
         }    
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format, IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider));
@@ -650,7 +628,6 @@ namespace System {
     
         // Returns the larger of two Decimal values.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal static Decimal Max(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2) >= 0? d1: d2;
@@ -658,7 +635,6 @@ namespace System {
     
         // Returns the smaller of two Decimal values.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal static Decimal Min(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2) < 0? d1: d2;
@@ -709,7 +685,6 @@ namespace System {
         
         // Multiplies two Decimal values.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal Multiply(Decimal d1, Decimal d2)
         {
             FCallMultiply (ref d1, ref d2);
@@ -719,11 +694,9 @@ namespace System {
         // FCallMultiply multiples two decimal values.  On return, d1 contains the result
         // of the operation.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallMultiply(ref Decimal d1, ref Decimal d2);
     
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallMultiplyOverflowed(ref Decimal d1, ref Decimal d2, ref bool overflowed);
     
@@ -746,7 +719,6 @@ namespace System {
             return Round(d, 0);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal Round(Decimal d, int decimals)
         {
             FCallRound (ref d, decimals);
@@ -757,7 +729,6 @@ namespace System {
             return Round(d, 0, mode);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) {
             if ((decimals < 0) || (decimals > 28))
                 throw new ArgumentOutOfRangeException(nameof(decimals), Environment.GetResourceString("ArgumentOutOfRange_DecimalRound"));
@@ -775,13 +746,11 @@ namespace System {
             return d;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallRound(ref Decimal d, int decimals);
     
         // Subtracts two Decimal values.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal Subtract(Decimal d1, Decimal d2)
         {
             FCallAddSub(ref d1, ref d2, DECIMAL_NEG);
@@ -843,7 +812,6 @@ namespace System {
         // has fewer significant digits than a Decimal, this operation may
         // produce round-off errors.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Currency ToCurrency(Decimal d)
         {
             Currency result = new Currency ();
@@ -851,18 +819,15 @@ namespace System {
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallToCurrency(ref Currency result, Decimal d);
     
         // Converts a Decimal to a double. Since a double has fewer significant
         // digits than a Decimal, this operation may produce round-off errors.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern double ToDouble(Decimal d);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int FCallToInt32(Decimal d);
     
@@ -870,7 +835,6 @@ namespace System {
         // zero to the nearest integer value, and the result of this operation is
         // returned as an integer.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static int ToInt32(Decimal d) {
             if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
             if (d.hi == 0 && d.mid == 0) {
@@ -890,7 +854,6 @@ namespace System {
         // to the nearest integer value, and the result of this operation is
         // returned as a long.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static long ToInt64(Decimal d) {
             if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
             if (d.hi == 0) {
@@ -927,7 +890,6 @@ namespace System {
         // value is rounded towards zero to the nearest integer value, and the 
         // result of this operation is returned as an unsigned integer.
         //
-         [System.Security.SecuritySafeCritical]  // auto-generated
          [CLSCompliant(false)]
         public static uint ToUInt32(Decimal d) {
             if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
@@ -943,7 +905,6 @@ namespace System {
         // value is rounded towards zero to the nearest integer value, and the 
         // result of this operation is returned as a long.
         //
-         [System.Security.SecuritySafeCritical]  // auto-generated
          [CLSCompliant(false)]
         public static ulong ToUInt64(Decimal d) {
             if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
@@ -958,7 +919,6 @@ namespace System {
         // Converts a Decimal to a float. Since a float has fewer significant
         // digits than a Decimal, this operation may produce round-off errors.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float ToSingle(Decimal d);
 
@@ -966,7 +926,6 @@ namespace System {
         // towards zero to the nearest integer value, corresponding to removing all
         // digits after the decimal point.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal Truncate(Decimal d)
         {
             FCallTruncate (ref d);
@@ -974,7 +933,6 @@ namespace System {
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void FCallTruncate(ref Decimal d);
     
@@ -1099,25 +1057,21 @@ namespace System {
             return Subtract(d, One);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal operator +(Decimal d1, Decimal d2) {
             FCallAddSub(ref d1, ref d2, DECIMAL_ADD);
             return d1;
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal operator -(Decimal d1, Decimal d2) {
             FCallAddSub(ref d1, ref d2, DECIMAL_NEG);
             return d1;
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal operator *(Decimal d1, Decimal d2) {
             FCallMultiply (ref d1, ref d2);
             return d1;
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Decimal operator /(Decimal d1, Decimal d2) {
             FCallDivide (ref d1, ref d2);
             return d1;
@@ -1127,32 +1081,26 @@ namespace System {
             return Remainder(d1, d2);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool operator ==(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2) == 0;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool operator !=(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2) != 0;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool operator <(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2) < 0;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool operator <=(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2) <= 0;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool operator >(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2) > 0;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool operator >=(Decimal d1, Decimal d2) {
             return FCallCompare(ref d1, ref d2) >= 0;
         }
index de0433d..b4681c4 100644 (file)
@@ -14,6 +14,7 @@ namespace System {
     using System.Reflection;
     using System.Runtime.CompilerServices;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using CultureInfo = System.Globalization.CultureInfo;
     //Marked serializable even though it has no state.
@@ -33,7 +34,6 @@ namespace System {
         // 
         // The most specific match will be selected.  
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override MethodBase BindToMethod(
             BindingFlags bindingAttr, MethodBase[] match, ref Object[] args, 
             ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, out Object state)
@@ -437,7 +437,6 @@ namespace System {
         
         // Given a set of fields that match the base criteria, select a field.
         // if value is null then we have no way to select a field
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override FieldInfo BindToField(BindingFlags bindingAttr,FieldInfo[] match, Object value,CultureInfo cultureInfo)
         {
             if (match == null) {
@@ -514,7 +513,6 @@ namespace System {
         // Given a set of methods that match the base criteria, select a method based
         // upon an array of types.  This method should return null if no method matchs
         // the criteria.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override MethodBase SelectMethod(BindingFlags bindingAttr,MethodBase[] match,Type[] types,ParameterModifier[] modifiers)
         {
             int i;
@@ -589,7 +587,6 @@ namespace System {
         }
         
         // Given a set of properties that match the base criteria, select one.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override PropertyInfo SelectProperty(BindingFlags bindingAttr,PropertyInfo[] match,Type returnType,
                     Type[] indexes,ParameterModifier[] modifiers)
         {
@@ -876,7 +873,6 @@ namespace System {
             }
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static int FindMostSpecificType(Type c1, Type c2, Type t)
         {
             // If the two types are exact move on...
@@ -987,7 +983,7 @@ namespace System {
                 int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
 
                 if (hierarchyDepth1 == hierarchyDepth2) {
-                    Contract.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
+                    Debug.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
                     return 0; 
                 }
                 else if (hierarchyDepth1 < hierarchyDepth2) 
@@ -1084,14 +1080,12 @@ namespace System {
 
         // CanConvertPrimitive
         // This will determine if the source can be converted to the target type
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool CanConvertPrimitive(RuntimeType source,RuntimeType target);
 
         // CanConvertPrimitiveObjectToType
         // This method will determine if the primitive object can be converted
         //  to a type.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern bool CanConvertPrimitiveObjectToType(Object source,RuntimeType type);
         
index 347607f..bca88c1 100644 (file)
@@ -12,6 +12,7 @@ namespace System {
     using System.Runtime.InteropServices;
     using System.Runtime.CompilerServices;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -20,29 +21,24 @@ namespace System {
     public abstract class Delegate : ICloneable, ISerializable 
     {
         // _target is the object we will invoke on
-        [System.Security.SecurityCritical]
         internal Object _target;
 
         // MethodBase, either cached after first request or assigned from a DynamicMethod
         // For open delegates to collectible types, this may be a LoaderAllocator object
-        [System.Security.SecurityCritical]
         internal Object _methodBase;
 
         // _methodPtr is a pointer to the method we will invoke
         // It could be a small thunk if this is a static or UM call
-        [System.Security.SecurityCritical]
         internal IntPtr _methodPtr;
         
         // In the case of a static method passed to a delegate, this field stores
         // whatever _methodPtr would have stored: and _methodPtr points to a
         // small thunk which removes the "this" pointer before going on
         // to _methodPtrAux.
-        [System.Security.SecurityCritical]
         internal IntPtr _methodPtrAux;
 
         // This constructor is called from the class generated by the
         //  compiler generated code
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected Delegate(Object target,String method)
         {
             if (target == null)
@@ -67,7 +63,6 @@ namespace System {
         // This constructor is called from a class to generate a 
         // delegate based upon a static method name and the Type object
         // for the class defining the method.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected unsafe Delegate(Type target,String method)
         {
             if (target == null)
@@ -113,7 +108,6 @@ namespace System {
             return DynamicInvokeImpl(args);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected virtual object DynamicInvokeImpl(object[] args) 
         {
             RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod());
@@ -123,7 +117,6 @@ namespace System {
         }
 
             
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool Equals(Object obj)
         {                
             if (obj == null || !InternalEqualTypes(this, obj))
@@ -227,7 +220,6 @@ namespace System {
             }
         }
             
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected virtual MethodInfo GetMethodImpl()
         {
             if ((_methodBase == null) || !(_methodBase is MethodInfo))
@@ -292,7 +284,6 @@ namespace System {
         }
     
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Delegate Remove(Delegate source, Delegate value)
         {
             if (source == null)
@@ -350,7 +341,6 @@ namespace System {
         }
 
         // V1 API.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure)
         {
             if (type == null)
@@ -402,7 +392,6 @@ namespace System {
         }
 
         // V1 API.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure)
         {
             if (type == null)
@@ -443,7 +432,6 @@ namespace System {
         }
             
         // V1 API.
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
         {
@@ -494,7 +482,6 @@ namespace System {
         }
 
         // V2 API.
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure)
         {
@@ -555,7 +542,6 @@ namespace System {
         // Implementation of ISerializable
         //
 
-        [System.Security.SecurityCritical]
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             throw new NotSupportedException();
@@ -566,7 +552,6 @@ namespace System {
 
         // V2 internal API.
         // This is Critical because it skips the security check when creating the delegate.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method)
         {
             // Validate the parameters.
@@ -600,7 +585,6 @@ namespace System {
         }
 
         // Caution: this method is intended for deserialization only, no security checks are performed.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object firstArgument, MethodInfo method)
         {
             // Validate the parameters.
@@ -642,10 +626,9 @@ namespace System {
             return CreateDelegate(type, method, true);
         }
 
-        [System.Security.SecuritySafeCritical]
         internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark)
         {
-            Contract.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
+            Debug.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
 
 #if FEATURE_APPX
             bool nonW8PMethod = (rtMethod.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0;
@@ -663,7 +646,6 @@ namespace System {
             return UnsafeCreateDelegate(rtType, rtMethod, firstArgument, flags);
         }
 
-        [System.Security.SecurityCritical]
         internal static Delegate UnsafeCreateDelegate(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags)
         {
             Delegate d = InternalAlloc(rtType);
@@ -678,62 +660,49 @@ namespace System {
         // internal implementation details (FCALLS and utilities)
         //
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags);
             
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags);
             
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static MulticastDelegate InternalAlloc(RuntimeType type);
             
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static MulticastDelegate InternalAllocLike(Delegate d);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool InternalEqualTypes(object a, object b);
 
         // Used by the ctor. Do not call directly.
         // The name of this function will appear in managed stacktraces as delegate constructor.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void DelegateConstruct(Object target, IntPtr slot);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern IntPtr GetMulticastInvoke();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern IntPtr GetInvokeMethod();
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern IRuntimeMethodInfo FindMethodHandle();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool InternalEqualMethodHandles(Delegate left, Delegate right);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern IntPtr AdjustTarget(Object target, IntPtr methodPtr);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern IntPtr GetCallStub(IntPtr methodPtr);
 
-        [System.Security.SecuritySafeCritical]
         internal virtual Object GetTarget()
         {
             return (_methodPtrAux.IsNull()) ? _target : null;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool CompareUnmanagedFunctionPtrs (Delegate d1, Delegate d2);
     }
index 9313dfd..83fe35a 100644 (file)
@@ -17,7 +17,6 @@ namespace System
     internal sealed class DelegateSerializationHolder : IObjectReference, ISerializable
     {
         #region Static Members
-        [System.Security.SecurityCritical]  // auto-generated
         internal static DelegateEntry GetDelegateSerializationInfo(
             SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
         {
@@ -116,7 +115,6 @@ namespace System
         #endregion    
     
         #region Constructor
-        [System.Security.SecurityCritical]  // auto-generated
         private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
@@ -195,7 +193,6 @@ namespace System
             return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName);
         }
 
-        [System.Security.SecurityCritical]
         private Delegate GetDelegate(DelegateEntry de, int index)
         {
             Delegate d;
@@ -218,27 +215,19 @@ namespace System
                 // If we received the new style delegate encoding we already have the target MethodInfo in hand.
                 if (m_methods != null)
                 {
-#if FEATURE_REMOTING                
-                    Object target = de.target != null ? RemotingServices.CheckCast(de.target, targetType) : null;
-#else
                     if(de.target != null && !targetType.IsInstanceOfType(de.target))
                         throw new InvalidCastException();
                     Object target=de.target;
-#endif
                     d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
                 }
                 else
                 {
                     if (de.target != null)
-#if FEATURE_REMOTING                
-                        d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName);
-#else
-                {
-                    if(!targetType.IsInstanceOfType(de.target))
-                        throw new InvalidCastException();
-                     d = Delegate.CreateDelegate(type, de.target, de.methodName);
-                }
-#endif
+                    {
+                        if(!targetType.IsInstanceOfType(de.target))
+                            throw new InvalidCastException();
+                         d = Delegate.CreateDelegate(type, de.target, de.methodName);
+                    }
                     else
                         d = Delegate.CreateDelegate(type, targetType, de.methodName);
                 }
@@ -259,7 +248,6 @@ namespace System
         #endregion
 
         #region IObjectReference
-        [System.Security.SecurityCritical]  // auto-generated
         public Object GetRealObject(StreamingContext context)
         {
             int count = 0;
@@ -289,7 +277,6 @@ namespace System
         #endregion
 
         #region ISerializable
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DelegateSerHolderSerial"));
index 40efe75..77cc6d8 100644 (file)
@@ -59,7 +59,6 @@ namespace System.Diagnostics {
             Fail(conditionString, message, null, exitCode, stackTraceFormat, 0);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static void Fail(String conditionString, String message, String windowTitle, int exitCode, StackTrace.TraceFormat stackTraceFormat, int numStackFramesToSkip)
         {
             // get the stacktrace
@@ -82,32 +81,15 @@ namespace System.Diagnostics {
             }
             else if (iResult == AssertFilters.FailTerminate)
             {
-#if FEATURE_CORECLR
                 // We want to exit the Silverlight application, after displaying a message.
                 // Our best known way to emulate this is to exit the process with a known 
                 // error code.  Jolt may not be prepared for an appdomain to be unloaded.
                 Environment._Exit(exitCode);
-#else
-                // This assert dialog will be common for code contract failures.  If a code contract failure
-                // occurs on an end user machine, we believe the right experience is to do a FailFast, which 
-                // will report this error via Watson, so someone could theoretically fix the bug.
-                // However, in CLR v4, Environment.FailFast when a debugger is attached gives you an MDA
-                // saying you've hit a bug in the runtime or unsafe managed code, and this is most likely caused
-                // by heap corruption or a stack imbalance from COM Interop or P/Invoke.  That extremely
-                // misleading error isn't right, and we can temporarily work around this by using Environment.Exit
-                // if a debugger is attached.  The right fix is to plumb FailFast correctly through our native
-                // Watson code, adding in a TypeOfReportedError for fatal managed errors.
-                if (Debugger.IsAttached)
-                    Environment._Exit(exitCode);
-                else
-                    Environment.FailFast(message, unchecked((uint) exitCode));
-#endif
             }
         }
     
       // Called when an assert happens.
       // windowTitle can be null.
-      [System.Security.SecurityCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       internal extern static int ShowDefaultAssertDialog(String conditionString, String message, String stackTrace, String windowTitle);
     }
index b441fc3..ab60ee4 100644 (file)
@@ -33,7 +33,6 @@ namespace System.Diagnostics {
         {
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override AssertFilters  AssertFailure(String condition, String message, 
                                   StackTrace location, StackTrace.TraceFormat stackTraceFormat,
                                   String windowTitle)
index 057d40f..27f4f4c 100644 (file)
@@ -32,6 +32,7 @@
 
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.CodeAnalysis;
 using System.Diagnostics.Contracts;
 
@@ -287,7 +288,7 @@ namespace System.Diagnostics.Contracts {
         /// </summary>
         /// <param name="condition">Expression to assume will always be true.</param>
         /// <remarks>
-        /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>.
+        /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
         /// </remarks>
         [Pure]
         [Conditional("DEBUG")]
@@ -308,7 +309,7 @@ namespace System.Diagnostics.Contracts {
         /// <param name="condition">Expression to assume will always be true.</param>
         /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
         /// <remarks>
-        /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>.
+        /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
         /// </remarks>
         [Pure]
         [Conditional("DEBUG")]
@@ -805,7 +806,6 @@ namespace System.Diagnostics.Contracts {
         [CLSCompliant(false)]
         [Pure]
         [ContractRuntimeIgnored]
-        [SecurityCritical]
 #if FEATURE_RELIABILITY_CONTRACTS
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
 #endif
@@ -852,7 +852,6 @@ namespace System.Diagnostics.Contracts {
         [CLSCompliant(false)]
         [Pure]
         [ContractRuntimeIgnored]
-        [SecurityCritical]
 #if FEATURE_RELIABILITY_CONTRACTS
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
 #endif
index 8434447..d5e3f29 100644 (file)
@@ -51,7 +51,6 @@ namespace System.Diagnostics.Contracts {
         /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly.
         /// It is NEVER used to indicate failure of actual contracts at runtime.
         /// </summary>
-        [SecuritySafeCritical]
         static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind)
         {
             if (_assertingMustUseRewriter)
@@ -121,18 +120,14 @@ namespace System.Diagnostics.Contracts {
         /// </summary>
         public static event EventHandler<ContractFailedEventArgs> ContractFailed {
 #if FEATURE_UNTRUSTED_CALLERS
-            [SecurityCritical]
 #if FEATURE_LINK_DEMAND
-            [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
 #endif
 #endif
             add {
                 System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value;
             }
 #if FEATURE_UNTRUSTED_CALLERS
-            [SecurityCritical]
 #if FEATURE_LINK_DEMAND
-            [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
 #endif
 #endif
             remove {
@@ -176,9 +171,7 @@ namespace System.Diagnostics.Contracts {
         }
 
 #if FEATURE_UNTRUSTED_CALLERS
-        [SecurityCritical]
 #if FEATURE_LINK_DEMAND
-        [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
 #endif
 #endif
         public void SetHandled()
@@ -191,9 +184,7 @@ namespace System.Diagnostics.Contracts {
         }
 
 #if FEATURE_UNTRUSTED_CALLERS
-        [SecurityCritical]
 #if FEATURE_LINK_DEMAND
-        [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
 #endif
 #endif
         public void SetUnwind()
@@ -243,9 +234,7 @@ namespace System.Diagnostics.Contracts {
         }
 
 #if FEATURE_UNTRUSTED_CALLERS && FEATURE_SERIALIZATION
-        [SecurityCritical]
 #if FEATURE_LINK_DEMAND && FEATURE_SERIALIZATION
-        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
 #endif // FEATURE_LINK_DEMAND
 #endif // FEATURE_UNTRUSTED_CALLERS
         public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
@@ -284,7 +273,6 @@ namespace System.Runtime.CompilerServices
         internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed
         {
 #if FEATURE_UNTRUSTED_CALLERS
-            [SecurityCritical]
 #endif
             add {
                 // Eagerly prepare each event handler _marked with a reliability contract_, to 
@@ -301,7 +289,6 @@ namespace System.Runtime.CompilerServices
                 }
             }
 #if FEATURE_UNTRUSTED_CALLERS
-            [SecurityCritical]
 #endif
             remove {
                 lock (lockObject)
@@ -326,7 +313,6 @@ namespace System.Runtime.CompilerServices
         [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
         [System.Diagnostics.DebuggerNonUserCode]
 #if FEATURE_RELIABILITY_CONTRACTS
-        [SecuritySafeCritical]
 #endif
         static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage)
         {
@@ -361,10 +347,6 @@ namespace System.Runtime.CompilerServices
                     }
                     if (eventArgs.Unwind)
                     {
-#if !FEATURE_CORECLR 
-                        if (Environment.IsCLRHosted)
-                            TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException);
-#endif
                         // unwind
                         if (innerException == null) { innerException = eventArgs.thrownDuringHandler; }
                         throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException);
@@ -393,9 +375,6 @@ namespace System.Runtime.CompilerServices
         [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")]
         [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")]
         [System.Diagnostics.DebuggerNonUserCode]
-#if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR
-        [SecuritySafeCritical]
-#endif
         static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
         {
             // If we're here, our intent is to pop up a dialog box (if we can).  For developers 
@@ -403,21 +382,12 @@ namespace System.Runtime.CompilerServices
             // hosted in Internet Explorer, the assert window is great.  If we cannot
             // pop up a dialog box, throw an exception (consider a library compiled with 
             // "Assert On Failure" but used in a process that can't pop up asserts, like an 
-            // NT Service).  For the CLR hosted by server apps like SQL or Exchange, we should 
-            // trigger escalation policy.  
-#if !FEATURE_CORECLR
-            if (Environment.IsCLRHosted)
-            {
-                TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException);
-                // Hosts like SQL may choose to abort the thread, so we will not get here in all cases.
-                // But if the host's chosen action was to throw an exception, we should throw an exception
-                // here (which is easier to do in managed code with the right parameters).  
-                throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
-            }
-#endif // !FEATURE_CORECLR
+            // NT Service).
+
             if (!Environment.UserInteractive) {
                 throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
             }
+
             // May need to rethink Assert.Fail w/ TaskDialogIndirect as a model.  Window title.  Main instruction.  Content.  Expanded info.
             // Optional info like string for collapsed text vs. expanded text.
             String windowTitle = Environment.GetResourceString(GetResourceNameForFailure(kind));
@@ -494,28 +464,6 @@ namespace System.Runtime.CompilerServices
                 return failureMessage;
             }
         }
-
-#if !FEATURE_CORECLR
-        // Will trigger escalation policy, if hosted and the host requested us to do something (such as 
-        // abort the thread or exit the process).  Starting in Dev11, for hosted apps the default behavior 
-        // is to throw an exception.  
-        // Implementation notes:
-        // We implement our default behavior of throwing an exception by simply returning from our native 
-        // method inside the runtime and falling through to throw an exception.
-        // We must call through this method before calling the method on the Environment class
-        // because our security team does not yet support SecuritySafeCritical on P/Invoke methods.
-        // Note this can be called in the context of throwing another exception (EnsuresOnThrow).
-        [SecuritySafeCritical]
-        [DebuggerNonUserCode]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException)
-        {
-            String exceptionAsString = null;
-            if (innerException != null)
-                exceptionAsString = innerException.ToString();
-            Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString);
-        }
-#endif // !FEATURE_CORECLR
     }
 }  // namespace System.Runtime.CompilerServices
 
index 339c89e..8ebbc0a 100644 (file)
@@ -32,7 +32,6 @@ namespace System.Diagnostics
         // 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 
         // debugger is launched.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void Break()
         {
             if (!Debugger.IsAttached)
@@ -61,7 +60,6 @@ namespace System.Diagnostics
             BreakInternal();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static void BreakCanThrow()
         {
             if (!Debugger.IsAttached)
@@ -75,14 +73,12 @@ namespace System.Diagnostics
             BreakInternal();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void BreakInternal();
 
         // Launch launches & attaches a debugger to the process. If a debugger is already attached,
         // nothing happens.  
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool Launch()
         {
             if (Debugger.IsAttached)
@@ -147,7 +143,6 @@ namespace System.Diagnostics
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool LaunchInternal();
 
@@ -155,7 +150,6 @@ namespace System.Diagnostics
         //
         public static extern bool IsAttached
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
             get;
         }
@@ -173,20 +167,17 @@ namespace System.Diagnostics
         // 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. 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void Log(int level, String category, String message);
 
         // Checks to see if an attached debugger has logging enabled
         //  
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(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. 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void CustomNotification(ICustomDebuggerNotification data);
 
index a7124a2..1a1f5fa 100644 (file)
@@ -72,7 +72,7 @@ namespace System.Diagnostics.Tracing
             }
 
 
-            Contract.Assert((options & EventActivityOptions.Disable) == 0);
+            Debug.Assert((options & EventActivityOptions.Disable) == 0);
 
             var currentActivity = m_current.Value;
             var fullActivityName = NormalizeActivityName(providerName, activityName, task);
@@ -191,7 +191,7 @@ namespace System.Diagnostics.Tracing
                     else
                     {
                         orphan.m_stopped = 1;
-                        Contract.Assert(orphan.m_stopped != 0);
+                        Debug.Assert(orphan.m_stopped != 0);
                     }
                     orphan = orphan.m_creator;
                 }
@@ -221,7 +221,6 @@ namespace System.Diagnostics.Tracing
         /// <summary>
         /// Turns on activity tracking.    It is sticky, once on it stays on (race issues otherwise)
         /// </summary>
-        [System.Security.SecuritySafeCritical]
         public void Enable()
         {
             if (m_current == null)
@@ -366,7 +365,6 @@ namespace System.Diagnostics.Tracing
             /// byte (since the top nibble can't be zero you can determine if this is true by seeing if 
             /// this byte is nonZero.   This offset is needed to efficiently create the ID for child activities. 
             /// </summary>
-            [System.Security.SecuritySafeCritical]
             private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathGuidOffset)
             {
                 fixed (Guid* outPtr = &idRet)
@@ -403,7 +401,6 @@ namespace System.Diagnostics.Tracing
             /// sufficient space for this ID.   By doing this, we preserve the fact that this activity
             /// is a child (of unknown depth) from that ancestor.
             /// </summary>
-            [System.Security.SecurityCritical]
             private unsafe void CreateOverflowGuid(Guid* outPtr)
             {
                 // Search backwards for an ancestor that has sufficient space to put the ID.  
@@ -452,7 +449,6 @@ namespace System.Diagnostics.Tracing
             /// is the maximum number of bytes that fit in a GUID) if the path did not fit.  
             /// If 'overflow' is true, then the number is encoded as an 'overflow number (which has a
             /// special (longer prefix) that indicates that this ID is allocated differently 
-            [System.Security.SecurityCritical]
             private static unsafe int AddIdToGuid(Guid* outPtr, int whereToAddId, uint id, bool overflow = false)
             {
                 byte* ptr = (byte*)outPtr;
@@ -526,11 +522,10 @@ namespace System.Diagnostics.Tracing
             /// Thus if it is non-zero it adds to the current byte, otherwise it advances and writes
             /// the new byte (in the high bits) of the next byte.  
             /// </summary>
-            [System.Security.SecurityCritical]
             private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value)
             {
-                Contract.Assert(0 <= value && value < 16);
-                Contract.Assert(ptr < endPtr);
+                Debug.Assert(0 <= value && value < 16);
+                Debug.Assert(ptr < endPtr);
 
                 if (*ptr != 0)
                     *ptr++ |= (byte)value;
index c7e1292..ce0fcb6 100644 (file)
@@ -74,7 +74,6 @@ namespace System.Diagnostics.Tracing
 
         private static bool m_setInformationMissing;
 
-        [SecurityCritical]
         UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback;     // Trace Callback function
         private long m_regHandle;                        // Trace Registration Handle
         private byte m_level;                            // Tracing Level
@@ -128,7 +127,6 @@ namespace System.Diagnostics.Tracing
         // <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" />
         // <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" />
         // </SecurityKernel>
-        [System.Security.SecurityCritical]
         internal unsafe void Register(Guid providerGuid)
         {
             m_providerId = providerGuid;
@@ -157,7 +155,6 @@ namespace System.Diagnostics.Tracing
         // <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1">
         // <ReferencesCritical Name="Method: Deregister():Void" Ring="1" />
         // </SecurityKernel>
-        [System.Security.SecuritySafeCritical]
         protected virtual void Dispose(bool disposing)
         {
             //
@@ -220,7 +217,6 @@ namespace System.Diagnostics.Tracing
         // <UsesUnsafeCode Name="Parameter filterData of type: Void*" />
         // <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" />
         // </SecurityKernel>
-        [System.Security.SecurityCritical]
         unsafe void EtwEnableCallBack(
                         [In] ref System.Guid sourceId,
                         [In] int controlCode,
@@ -341,7 +337,6 @@ namespace System.Diagnostics.Tracing
         /// ETW session that was added or remove, and the bool specifies whether the
         /// session was added or whether it was removed from the set.
         /// </summary>
-        [System.Security.SecuritySafeCritical]
         private List<Tuple<SessionInfo, bool>> GetSessions()
         {
             List<SessionInfo> liveSessionList = null;
@@ -417,7 +412,6 @@ namespace System.Diagnostics.Tracing
         /// for the current process ID, calling 'action' for each session, and passing it the
         /// ETW session and the 'AllKeywords' the session enabled for the current provider.
         /// </summary>
-        [System.Security.SecurityCritical]
         private unsafe void GetSessionInfo(Action<int, long> action)
         {
             // We wish the EventSource package to be legal for Windows Store applications.   
@@ -463,7 +457,7 @@ namespace System.Diagnostics.Tracing
                 }
                 if (providerInstance->NextOffset == 0)
                     break;
-                Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
+                Debug.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
                 var structBase = (byte*)providerInstance;
                 providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset];
             }
@@ -545,7 +539,6 @@ namespace System.Diagnostics.Tracing
         /// returns an array of bytes representing the data, the index into that byte array where the data
         /// starts, and the command being issued associated with that data.  
         /// </summary>
-        [System.Security.SecurityCritical]
         private unsafe bool GetDataFromController(int etwSessionId,
                 UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart)
         {
@@ -678,7 +671,6 @@ namespace System.Diagnostics.Tracing
         // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" />
         // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" />
         // </SecurityKernel>
-        [System.Security.SecurityCritical]
         private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize)
         /*++
 
@@ -927,7 +919,6 @@ 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")]
-        [System.Security.SecurityCritical]
         internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload)
         {
             int status = 0;
@@ -1124,13 +1115,12 @@ 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")]
-        [System.Security.SecurityCritical]
         internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data)
         {
             if (childActivityID != null)
             {
                 // activity transfers are supported only for events that specify the Send or Receive opcode
-                Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
+                Debug.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
                                 (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive ||
                                 (EventOpcode)eventDescriptor.Opcode == EventOpcode.Start ||
                                 (EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop);
@@ -1147,7 +1137,6 @@ namespace System.Diagnostics.Tracing
         }
 
         [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
-        [System.Security.SecurityCritical]
         internal unsafe bool WriteEventRaw(
             ref EventDescriptor eventDescriptor,
             Guid* activityID,
@@ -1176,7 +1165,6 @@ namespace System.Diagnostics.Tracing
 
         // These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work
         // either with Manifest ETW or Classic ETW (if Manifest based ETW is not available).  
-        [SecurityCritical]
         private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback)
         {
             m_providerId = providerId;
@@ -1184,7 +1172,6 @@ namespace System.Diagnostics.Tracing
             return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
         }
 
-        [SecurityCritical]
         private uint EventUnregister(long registrationHandle)
         {
             return UnsafeNativeMethods.ManifestEtw.EventUnregister(registrationHandle);
@@ -1200,7 +1187,7 @@ namespace System.Diagnostics.Tracing
         }
         private static int bitindex(uint n)
         {
-            Contract.Assert(bitcount(n) == 1);
+            Debug.Assert(bitcount(n) == 1);
             int idx = 0;
             while ((n & (1 << idx)) == 0)
                 idx++;
index b089381..aa0d8d7 100644 (file)
@@ -529,7 +529,6 @@ namespace System.Diagnostics.Tracing
         /// </summary>
         internal static Guid InternalCurrentThreadActivityId
         {
-            [System.Security.SecurityCritical]
             get
             {
                 Guid retval = CurrentThreadActivityId;
@@ -543,7 +542,6 @@ namespace System.Diagnostics.Tracing
 
         internal static Guid FallbackActivityId
         {
-            [System.Security.SecurityCritical]
             get
             {
 #pragma warning disable 612, 618
@@ -714,7 +712,6 @@ namespace System.Diagnostics.Tracing
 
 #pragma warning disable 1591
         // optimized for common signatures (no args)
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId)
         {
@@ -722,7 +719,6 @@ namespace System.Diagnostics.Tracing
         }
 
         // optimized for common signatures (ints)
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, int arg1)
         {
@@ -735,7 +731,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, int arg1, int arg2)
         {
@@ -750,7 +745,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3)
         {
@@ -768,7 +762,6 @@ namespace System.Diagnostics.Tracing
         }
 
         // optimized for common signatures (longs)
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, long arg1)
         {
@@ -781,7 +774,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, long arg1, long arg2)
         {
@@ -796,7 +788,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, long arg1, long arg2, long arg3)
         {
@@ -814,7 +805,6 @@ namespace System.Diagnostics.Tracing
         }
 
         // optimized for common signatures (strings)
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, string arg1)
         {
@@ -831,7 +821,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, string arg1, string arg2)
         {
@@ -852,7 +841,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3)
         {
@@ -878,7 +866,6 @@ namespace System.Diagnostics.Tracing
         }
 
         // optimized for common signatures (string and ints)
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, string arg1, int arg2)
         {
@@ -897,7 +884,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3)
         {
@@ -919,7 +905,6 @@ namespace System.Diagnostics.Tracing
         }
 
         // optimized for common signatures (string and longs)
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, string arg1, long arg2)
         {
@@ -939,7 +924,6 @@ namespace System.Diagnostics.Tracing
         }
 
         // optimized for common signatures (long and string)
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, long arg1, string arg2)
         {
@@ -959,7 +943,6 @@ namespace System.Diagnostics.Tracing
         }
 
         // optimized for common signatures (int and string)
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, int arg1, string arg2)
         {
@@ -978,7 +961,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, byte[] arg1)
         {
@@ -1009,7 +991,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, long arg1, byte[] arg2)
         {
@@ -1067,7 +1048,6 @@ namespace System.Diagnostics.Tracing
             /// <param name="pointer">Pinned tracelogging-compatible metadata blob.</param>
             /// <param name="size">The size of the metadata blob.</param>
             /// <param name="reserved">Value for reserved: 2 for per-provider metadata, 1 for per-event metadata</param>
-            [SecurityCritical]
             internal unsafe void SetMetadata(byte* pointer, int size, int reserved)
             {
                 this.m_Ptr = (long)(ulong)(UIntPtr)pointer;
@@ -1109,7 +1089,6 @@ namespace System.Diagnostics.Tracing
         ///    }
         /// </code>
         /// </remarks>
-        [SecurityCritical]
         [CLSCompliant(false)]
         protected unsafe void WriteEventCore(int eventId, int eventDataCount, EventSource.EventData* data)
         {
@@ -1141,7 +1120,6 @@ namespace System.Diagnostics.Tracing
         ///    }
         /// </code>
         /// </remarks>
-        [SecurityCritical]
         [CLSCompliant(false)]
         protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* relatedActivityId, int eventDataCount, EventSource.EventData* data)
         {
@@ -1149,7 +1127,7 @@ namespace System.Diagnostics.Tracing
             {
                 try
                 {
-                    Contract.Assert(m_eventData != null);  // You must have initialized this if you enabled the source.
+                    Debug.Assert(m_eventData != null);  // You must have initialized this if you enabled the source.
                     if (relatedActivityId != null)
                         ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
 
@@ -1299,7 +1277,6 @@ namespace System.Diagnostics.Tracing
         /// method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/> 
         /// check so that the varargs call is not made when the EventSource is not active.  
         /// </summary>
-        [SecuritySafeCritical]
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
         protected unsafe void WriteEvent(int eventId, params object[] args)
         {
@@ -1314,7 +1291,6 @@ namespace System.Diagnostics.Tracing
         /// particular method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/>
         /// check so that the varargs call is not made when the EventSource is not active.
         /// </summary>
-        [SecuritySafeCritical]
         protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, params object[] args)
         {
             WriteEventVarargs(eventId, &relatedActivityId, args);
@@ -1381,7 +1357,7 @@ namespace System.Diagnostics.Tracing
 #if FEATURE_ACTIVITYSAMPLING
         internal void WriteStringToListener(EventListener listener, string msg, SessionMask m)
         {
-            Contract.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0));
+            Debug.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0));
 
             if (m_eventSourceEnabled)
             {
@@ -1403,7 +1379,6 @@ namespace System.Diagnostics.Tracing
         }
 #endif
 
-        [SecurityCritical]
         private unsafe void WriteEventRaw(
             string eventName,
             ref EventDescriptor eventDescriptor,
@@ -1445,7 +1420,6 @@ namespace System.Diagnostics.Tracing
         /// member, and any future access to the "Log" would throw the cached exception).
         /// </summary>
         [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")]
-        [SecuritySafeCritical]
         private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, string[] traits)
         {
             try
@@ -1515,7 +1489,7 @@ namespace System.Diagnostics.Tracing
                 }
 #endif // FEATURE_MANAGED_ETW
 
-                Contract.Assert(!m_eventSourceEnabled);     // We can't be enabled until we are completely initted.  
+                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;
             }
@@ -1744,7 +1718,6 @@ namespace System.Diagnostics.Tracing
             return new Guid(bytes);
         }
 
-        [SecurityCritical]
         private unsafe object DecodeObject(int eventId, int parameterId, ref EventSource.EventData* data)
         {
             // TODO FIX : We use reflection which in turn uses EventSource, right now we carefully avoid
@@ -1891,14 +1864,13 @@ namespace System.Diagnostics.Tracing
             return dispatcher;
         }
 
-        [SecurityCritical]
         private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object[] args)
         {
             if (m_eventSourceEnabled)
             {
                 try
                 {
-                    Contract.Assert(m_eventData != null);  // You must have initialized this if you enabled the source.  
+                    Debug.Assert(m_eventData != null);  // You must have initialized this if you enabled the source.  
                     if (childActivityID != null)
                     {
                         ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
@@ -2062,7 +2034,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecurityCritical]
         unsafe private object[] SerializeEventArgs(int eventId, object[] args)
         {
             TraceLoggingEventTypes eventTypes = m_eventData[eventId].TraceLoggingEventTypes;
@@ -2138,7 +2109,6 @@ namespace System.Diagnostics.Tracing
             return sum;
         }
 
-        [SecurityCritical]
         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
@@ -2162,7 +2132,6 @@ namespace System.Diagnostics.Tracing
         }
 
         // helper for writing to all EventListeners attached the current eventSource.  
-        [SecurityCritical]
         unsafe private void WriteToAllListeners(int eventId, Guid* childActivityID, params object[] args)
         {
             EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
@@ -2176,13 +2145,12 @@ namespace System.Diagnostics.Tracing
             DispatchToAllListeners(eventId, childActivityID, eventCallbackArgs);
         }
 
-        [SecurityCritical]
         private unsafe void DispatchToAllListeners(int eventId, Guid* childActivityID, EventWrittenEventArgs eventCallbackArgs)
         {
             Exception lastThrownException = null;
             for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next)
             {
-                Contract.Assert(dispatcher.m_EventEnabled != null);
+                Debug.Assert(dispatcher.m_EventEnabled != null);
                 if (eventId == -1 || dispatcher.m_EventEnabled[eventId])
                 {
 #if FEATURE_ACTIVITYSAMPLING
@@ -2218,7 +2186,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecuritySafeCritical]
         [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)
         {
@@ -2313,7 +2280,6 @@ namespace System.Diagnostics.Tracing
         }
 
 #if FEATURE_ACTIVITYSAMPLING
-        [SecurityCritical]
         unsafe private SessionMask GetEtwSessionMask(int eventId, Guid* childActivityID)
         {
             SessionMask etwSessions = new SessionMask();
@@ -2614,7 +2580,7 @@ namespace System.Diagnostics.Tracing
         {
             // PRECONDITION: We should be holding the EventListener.EventListenersLock
             // We defer commands until we are completely inited.  This allows error messages to be sent.  
-            Contract.Assert(m_completelyInited);
+            Debug.Assert(m_completelyInited);
 
 #if FEATURE_MANAGED_ETW
             if (m_provider == null)     // If we failed to construct
@@ -2626,7 +2592,7 @@ namespace System.Diagnostics.Tracing
             try
             {
                 EnsureDescriptorsInitialized();
-                Contract.Assert(m_eventData != null);
+                Debug.Assert(m_eventData != null);
 
                 // Find the per-EventSource dispatcher corresponding to registered dispatcher
                 commandArgs.dispatcher = GetDispatcher(commandArgs.listener);
@@ -2685,7 +2651,7 @@ namespace System.Diagnostics.Tracing
                     // hasn't changed.
                     // sesisonId = SessionMask.MAX when one of the legacy ETW sessions changed
                     // 0 <= perEventSourceSessionId < SessionMask.MAX for activity-tracing aware sessions
-                    Contract.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX);
+                    Debug.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX);
 
                     // Send the manifest if we are enabling an ETW session
                     if (bSessionEnable && commandArgs.dispatcher == null)
@@ -2740,7 +2706,7 @@ namespace System.Diagnostics.Tracing
                     // things like log messages, or test if keywords are enabled in the callback.  
                     if (commandArgs.enable)
                     {
-                        Contract.Assert(m_eventData != null);
+                        Debug.Assert(m_eventData != null);
                         m_eventSourceEnabled = true;
                     }
 
@@ -2828,9 +2794,9 @@ namespace System.Diagnostics.Tracing
                     }
 
                     // These are not used for non-update commands and thus should always be 'default' values
-                    // Contract.Assert(enable == true);
-                    // Contract.Assert(level == EventLevel.LogAlways);
-                    // Contract.Assert(matchAnyKeyword == EventKeywords.None);
+                    // Debug.Assert(enable == true);
+                    // Debug.Assert(level == EventLevel.LogAlways);
+                    // Debug.Assert(matchAnyKeyword == EventKeywords.None);
 
                     this.OnEventCommand(commandArgs);
                     var eventCommandCallback = m_eventCommandExecuted;
@@ -3025,11 +2991,10 @@ namespace System.Diagnostics.Tracing
             get { return m_eventSourceDisposed; }
         }
 
-        [SecuritySafeCritical]
         private void EnsureDescriptorsInitialized()
         {
 #if !ES_BUILD_STANDALONE
-            Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+            Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
 #endif
             if (m_eventData == null)
             {
@@ -3045,9 +3010,9 @@ namespace System.Diagnostics.Tracing
                 if (eventSourceGuid.Equals(Guid.Empty) || eventSourceName == null || eventData == null || manifest == null)
                 {
                     // GetMetadata failed, so we have to set it via reflection.
-                    Contract.Assert(m_rawManifest == null);
+                    Debug.Assert(m_rawManifest == null);
                     m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this);
-                    Contract.Assert(m_eventData != null);
+                    Debug.Assert(m_eventData != null);
 
                 }
                 else
@@ -3092,7 +3057,6 @@ namespace System.Diagnostics.Tracing
 
         // Send out the ETW manifest XML out to ETW
         // Today, we only send the manifest to ETW, custom listeners don't get it. 
-        [SecuritySafeCritical]
         private unsafe bool SendManifest(byte[] rawManifest)
         {
             bool success = true;
@@ -3100,7 +3064,7 @@ namespace System.Diagnostics.Tracing
             if (rawManifest == null)
                 return false;
 
-            Contract.Assert(!SelfDescribingEvents);
+            Debug.Assert(!SelfDescribingEvents);
 
 #if FEATURE_MANAGED_ETW
             fixed (byte* dataPtr = rawManifest)
@@ -3204,7 +3168,7 @@ namespace System.Diagnostics.Tracing
                 {
                     Attribute attr = null;
 
-                    Contract.Assert(data.ConstructorArguments.Count <= 1);
+                    Debug.Assert(data.ConstructorArguments.Count <= 1);
 
                     if (data.ConstructorArguments.Count == 1)
                     {
@@ -3491,7 +3455,7 @@ namespace System.Diagnostics.Tracing
                                     int startEventId = eventAttribute.EventId - 1;
                                     if (eventData != null && startEventId < eventData.Length)
                                     {
-                                        Contract.Assert(0 <= startEventId);                // Since we reserve id 0, we know that id-1 is <= 0
+                                        Debug.Assert(0 <= startEventId);                // Since we reserve id 0, we know that id-1 is <= 0
                                         EventMetadata startEventMetadata = eventData[startEventId];
 
                                         // If you remove the Stop and add a Start does that name match the Start Event's Name?
@@ -3754,7 +3718,7 @@ namespace System.Diagnostics.Tracing
 
             // We give a task to things if they don't have one.  
             // TODO this is moderately expensive (N*N).   We probably should not even bother....   
-            Contract.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info);
+            Debug.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info);
             for (int idx = 0; idx < eventData.Length; ++idx)
             {
                 // skip unused Event IDs. 
@@ -3824,7 +3788,6 @@ namespace System.Diagnostics.Tracing
         /// </summary>
         /// <param name="method">The method to probe.</param>
         /// <returns>The literal value or -1 if the value could not be determined. </returns>
-        [SecuritySafeCritical]
         [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Switch statement is clearer than alternatives")]
         static private int GetHelperCallFirstArg(MethodInfo method)
         {
@@ -3937,7 +3900,7 @@ namespace System.Diagnostics.Tracing
                             goto default;
                         break;
                     default:
-                        /* Contract.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] +
+                        /* Debug.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] +
                             " at " + idx + " in method " + method.Name); */
                         return -1;
                 }
@@ -4020,7 +3983,7 @@ namespace System.Diagnostics.Tracing
         {
             get
             {
-                Contract.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) !=
+                Debug.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) !=
                                 ((m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0));
                 return (m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0;
             }
@@ -4042,7 +4005,7 @@ namespace System.Diagnostics.Tracing
 #if FEATURE_ACTIVITYSAMPLING
         private void ReportActivitySamplingInfo(EventListener listener, SessionMask sessions)
         {
-            Contract.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0));
+            Debug.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0));
 
             for (int perEventSourceSessionId = 0; perEventSourceSessionId < SessionMask.MAX; ++perEventSourceSessionId)
             {
@@ -4053,7 +4016,7 @@ namespace System.Diagnostics.Tracing
                 if (listener == null)
                 {
                     EtwSession etwSession = m_etwSessionIdMap[perEventSourceSessionId];
-                    Contract.Assert(etwSession != null);
+                    Debug.Assert(etwSession != null);
                     af = etwSession.m_activityFilter;
                 }
                 else
@@ -4446,10 +4409,6 @@ namespace System.Diagnostics.Tracing
                 if (!s_EventSourceShutdownRegistered)
                 {
                     s_EventSourceShutdownRegistered = true;
-#if (!ES_BUILD_PCL && !FEATURE_CORECLR && !PROJECTN)
-                    AppDomain.CurrentDomain.ProcessExit += DisposeOnShutdown;
-                    AppDomain.CurrentDomain.DomainUnload += DisposeOnShutdown;
-#endif
                 }
 
 
@@ -4515,7 +4474,7 @@ namespace System.Diagnostics.Tracing
         private static void RemoveReferencesToListenerInEventSources(EventListener listenerToRemove)
         {
 #if !ES_BUILD_STANDALONE
-            Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+            Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
 #endif
             // Foreach existing EventSource in the appdomain
             foreach (WeakReference eventSourceRef in s_EventSources)
@@ -4535,7 +4494,7 @@ namespace System.Diagnostics.Tracing
                             EventDispatcher cur = prev.m_Next;
                             if (cur == null)
                             {
-                                Contract.Assert(false, "EventSource did not have a registered EventListener!");
+                                Debug.Assert(false, "EventSource did not have a registered EventListener!");
                                 break;
                             }
                             if (cur.m_Listener == listenerToRemove)
@@ -4575,13 +4534,13 @@ namespace System.Diagnostics.Tracing
                     EventSource eventSource = eventSourceRef.Target as EventSource;
                     if (eventSource == null)
                         continue;
-                    Contract.Assert(eventSource.m_id == id, "Unexpected event source ID.");
+                    Debug.Assert(eventSource.m_id == id, "Unexpected event source ID.");
 
                     // None listeners on eventSources exist in the dispatcher list.   
                     EventDispatcher dispatcher = eventSource.m_Dispatchers;
                     while (dispatcher != null)
                     {
-                        Contract.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list.");
+                        Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list.");
                         dispatcher = dispatcher.m_Next;
                     }
 
@@ -4591,7 +4550,7 @@ namespace System.Diagnostics.Tracing
                         dispatcher = eventSource.m_Dispatchers;
                         for (;;)
                         {
-                            Contract.Assert(dispatcher != null, "Listener is not on all eventSources.");
+                            Debug.Assert(dispatcher != null, "Listener is not on all eventSources.");
                             if (dispatcher.m_Listener == listener)
                                 break;
                             dispatcher = dispatcher.m_Next;
@@ -4821,7 +4780,6 @@ namespace System.Diagnostics.Tracing
         /// </summary>
         public Guid ActivityId
         {
-            [System.Security.SecurityCritical]
             get { return EventSource.CurrentThreadActivityId; }
         }
 
@@ -4830,7 +4788,6 @@ namespace System.Diagnostics.Tracing
         /// </summary>
         public Guid RelatedActivityId
         {
-            [System.Security.SecurityCritical]
             get;
             internal set;
         }
@@ -4851,7 +4808,7 @@ namespace System.Diagnostics.Tracing
                 if (m_payloadNames == null)
                 {
                     // Self described events are identified by id -1.
-                    Contract.Assert(EventId != -1);
+                    Debug.Assert(EventId != -1);
 
                     var names = new List<string>();
                     foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters)
@@ -5280,7 +5237,7 @@ namespace System.Diagnostics.Tracing
         public static void DisableFilter(ref ActivityFilter filterList, EventSource source)
         {
 #if !ES_BUILD_STANDALONE
-            Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+            Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
 #endif
 
             if (filterList == null)
@@ -5348,7 +5305,7 @@ namespace System.Diagnostics.Tracing
                                     string startEvents)
         {
 #if !ES_BUILD_STANDALONE
-            Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+            Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
 #endif
 
             // first remove all filters associated with 'source'
@@ -5435,7 +5392,6 @@ namespace System.Diagnostics.Tracing
         /// If 'childActivityID' is present, it will be added to the active set if the 
         /// current activity is active.  
         /// </summary>
-        [SecurityCritical]
         unsafe public static bool PassesActivityFilter(
                                     ActivityFilter filterList,
                                     Guid* childActivityID,
@@ -5443,7 +5399,7 @@ namespace System.Diagnostics.Tracing
                                     EventSource source,
                                     int eventId)
         {
-            Contract.Assert(filterList != null && filterList.m_activeActivities != null);
+            Debug.Assert(filterList != null && filterList.m_activeActivities != null);
             bool shouldBeLogged = false;
             if (triggeringEvent)
             {
@@ -5516,7 +5472,6 @@ namespace System.Diagnostics.Tracing
             return shouldBeLogged;
         }
 
-        [System.Security.SecuritySafeCritical]
         public static bool IsCurrentActivityActive(ActivityFilter filterList)
         {
             var activeActivities = GetActiveActivities(filterList);
@@ -5533,13 +5488,12 @@ namespace System.Diagnostics.Tracing
         /// value for  'currentActivityid' is an indication tha caller has already verified
         /// that the current activity is active.
         /// </summary>
-        [SecurityCritical]
         unsafe public static void FlowActivityIfNeeded(ActivityFilter filterList, Guid* currentActivityId, Guid* childActivityID)
         {
-            Contract.Assert(childActivityID != null);
+            Debug.Assert(childActivityID != null);
 
             var activeActivities = GetActiveActivities(filterList);
-            Contract.Assert(activeActivities != null);
+            Debug.Assert(activeActivities != null);
 
             // take currentActivityId == null to mean we *know* the current activity is "active"
             if (currentActivityId != null && !activeActivities.ContainsKey(*currentActivityId))
@@ -5596,7 +5550,7 @@ namespace System.Diagnostics.Tracing
         public void Dispose()
         {
 #if !ES_BUILD_STANDALONE
-            Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+            Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
 #endif
             // m_myActivityDelegate is still alive (held by the static EventSource.s_activityDying). 
             // Therefore we are ok to take a dependency on m_myActivityDelegate being valid even 
@@ -5623,7 +5577,7 @@ namespace System.Diagnostics.Tracing
             m_samplingFreq = samplingFreq;
             m_next = existingFilter;
 
-            Contract.Assert(existingFilter == null ||
+            Debug.Assert(existingFilter == null ||
                             (existingFilter.m_activeActivities == null) == (existingFilter.m_rootActiveActivities == null));
 
             // if this is the first filter we add for this session, we need to create a new 
@@ -5697,10 +5651,10 @@ namespace System.Diagnostics.Tracing
         private static bool EnableFilter(ref ActivityFilter filterList, EventSource source, int perEventSourceSessionId, int eventId, int samplingFreq)
         {
 #if !ES_BUILD_STANDALONE
-            Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+            Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
 #endif
-            Contract.Assert(samplingFreq > 0);
-            Contract.Assert(eventId >= 0);
+            Debug.Assert(samplingFreq > 0);
+            Debug.Assert(eventId >= 0);
 
             filterList = new ActivityFilter(source, perEventSourceSessionId, eventId, samplingFreq, filterList);
 
@@ -5831,7 +5785,7 @@ namespace System.Diagnostics.Tracing
 
         public static void RemoveEtwSession(EtwSession etwSession)
         {
-            Contract.Assert(etwSession != null);
+            Debug.Assert(etwSession != null);
             if (s_etwSessions == null || etwSession == null)
                 return;
 
@@ -5912,7 +5866,7 @@ namespace System.Diagnostics.Tracing
 
         public static SessionMask FromId(int perEventSourceSessionId)
         {
-            Contract.Assert(perEventSourceSessionId < MAX);
+            Debug.Assert(perEventSourceSessionId < MAX);
             return new SessionMask((uint)1 << perEventSourceSessionId);
         }
 
@@ -5930,12 +5884,12 @@ namespace System.Diagnostics.Tracing
         {
             get
             {
-                Contract.Assert(perEventSourceSessionId < MAX);
+                Debug.Assert(perEventSourceSessionId < MAX);
                 return (m_mask & (1 << perEventSourceSessionId)) != 0;
             }
             set
             {
-                Contract.Assert(perEventSourceSessionId < MAX);
+                Debug.Assert(perEventSourceSessionId < MAX);
                 if (value) m_mask |= ((uint)1 << perEventSourceSessionId);
                 else m_mask &= ~((uint)1 << perEventSourceSessionId);
             }
@@ -6166,7 +6120,7 @@ namespace System.Diagnostics.Tracing
         private EventChannelType EventChannelToChannelType(EventChannel channel)
         {
 #if !ES_BUILD_STANDALONE
-            Contract.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug);
+            Debug.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug);
 #endif
             return (EventChannelType)((int)channel - (int)EventChannel.Admin + (int)EventChannelType.Admin);
         }
@@ -6209,8 +6163,8 @@ namespace System.Diagnostics.Tracing
 #endif
         public void StartEvent(string eventName, EventAttribute eventAttribute)
         {
-            Contract.Assert(numParams == 0);
-            Contract.Assert(this.eventName == null);
+            Debug.Assert(numParams == 0);
+            Debug.Assert(this.eventName == null);
             this.eventName = eventName;
             numParams = 0;
             byteArrArgIndices = null;
@@ -6645,13 +6599,7 @@ namespace System.Diagnostics.Tracing
         private static List<CultureInfo> GetSupportedCultures(ResourceManager resources)
         {
             var cultures = new List<CultureInfo>();
-#if !ES_BUILD_PCL && !FEATURE_CORECLR && !PROJECTN
-            foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures /*| CultureTypes.NeutralCultures*/))
-            {
-                if (resources.GetResourceSet(ci, true, false) != null)
-                    cultures.Add(ci);
-            }
-#endif // !ES_BUILD_PCL && !FEATURE_CORECLR
+
             if (!cultures.Contains(CultureInfo.CurrentUICulture))
                 cultures.Insert(0, CultureInfo.CurrentUICulture);
             return cultures;
index 00bd0b7..0a689ef 100644 (file)
@@ -29,7 +29,6 @@ namespace System.Diagnostics.Tracing
         /// </summary>
         /// <param name="activityId">A Guid that represents the new activity with which to mark 
         /// the current thread</param>
-        [System.Security.SecuritySafeCritical]
         public static void SetCurrentThreadActivityId(Guid activityId)
         {
             if (TplEtwProvider.Log != null)
@@ -80,7 +79,6 @@ namespace System.Diagnostics.Tracing
         /// the current thread</param>
         /// <param name="oldActivityThatWillContinue">The Guid that represents the current activity  
         /// which will continue at some point in the future, on the current thread</param>
-        [System.Security.SecuritySafeCritical]
         public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue)
         {
             oldActivityThatWillContinue = activityId;
@@ -104,7 +102,6 @@ namespace System.Diagnostics.Tracing
         /// </summary>
         public static Guid CurrentThreadActivityId
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 // We ignore errors to keep with the convention that EventSources do not throw 
@@ -186,7 +183,6 @@ namespace System.Diagnostics.Tracing
     
     internal partial class EventProvider
     {
-        [System.Security.SecurityCritical]
         internal unsafe int SetInformation(
             UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass,
             IntPtr data,
index d0d687e..079d7f4 100644 (file)
@@ -22,7 +22,6 @@ namespace System.Diagnostics.Tracing
     /// EventWrite. The instance must be Disabled before the arrays referenced
     /// by the pointers are freed or unpinned.
     /// </summary>
-    [SecurityCritical]
     internal unsafe struct DataCollector
     {
         [ThreadStatic]
index a894d89..5967ad6 100644 (file)
@@ -4,6 +4,7 @@
 
 using System.Collections.Generic;
 using System.Collections;
+using System.Diagnostics;
 
 #if !ES_BUILD_AGAINST_DOTNET_V35
 using Contract = System.Diagnostics.Contracts.Contract;
@@ -26,7 +27,7 @@ namespace System.Diagnostics.Tracing
     {
         internal EventPayload(List<string> payloadNames, List<object> payloadValues) 
         {
-            Contract.Assert(payloadNames.Count == payloadValues.Count);
+            Debug.Assert(payloadNames.Count == payloadValues.Count);
 
             m_names = payloadNames;
             m_values = payloadValues;
index 0f34d95..3ea7812 100644 (file)
@@ -1,5 +1,6 @@
 ï»¿using System.Reflection;
 using System.Runtime.InteropServices;
+using System.Diagnostics;
 
 #if !ES_BUILD_AGAINST_DOTNET_V35
 using Contract = System.Diagnostics.Contracts.Contract;
@@ -132,7 +133,7 @@ namespace System.Diagnostics.Tracing
         {
             get
             {
-                Contract.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type.");
+                Debug.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type.");
                 return _reference;
             }
         }
@@ -141,7 +142,7 @@ namespace System.Diagnostics.Tracing
         {
             get
             {
-                Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
+                Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
                 return _scalar;
             }
         }
@@ -150,7 +151,7 @@ namespace System.Diagnostics.Tracing
         {
             get
             {
-                Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
+                Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
                 return _scalarLength;
             }
         }
index e51aff0..901a0ed 100644 (file)
@@ -5,6 +5,7 @@
 using System;
 using System.Collections.Generic;
 using System.Reflection;
+using System.Diagnostics;
 
 #if !ES_BUILD_AGAINST_DOTNET_V35
 using Contract = System.Diagnostics.Contracts.Contract;
@@ -269,7 +270,7 @@ namespace System.Diagnostics.Tracing
             : base(type)
         {
             var typeArgs = type.GenericTypeArguments;
-            Contract.Assert(typeArgs.Length == 1);
+            Debug.Assert(typeArgs.Length == 1);
             this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck);
             this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue"));
             this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value"));
index 4b6e633..04a047f 100644 (file)
@@ -21,7 +21,6 @@ namespace System.Diagnostics.Tracing
     /// full-trust code, this abstraction is unnecessary (though it probably
     /// doesn't hurt anything).
     /// </summary>
-    [SecuritySafeCritical]
     internal unsafe class TraceLoggingDataCollector
     {
         internal static readonly TraceLoggingDataCollector Instance = new TraceLoggingDataCollector();
index a34ed7b..07a5675 100644 (file)
@@ -110,7 +110,6 @@ namespace System.Diagnostics.Tracing
         /// (Native API: EventWriteTransfer)
         /// </summary>
         /// <param name="eventName">The name of the event. Must not be null.</param>
-        [SecuritySafeCritical]
         public unsafe void Write(string eventName)
         {
             if (eventName == null)
@@ -138,7 +137,6 @@ namespace System.Diagnostics.Tracing
         /// Options for the event, such as the level, keywords, and opcode. Unset
         /// options will be set to default values.
         /// </param>
-        [SecuritySafeCritical]
         public unsafe void Write(string eventName, EventSourceOptions options)
         {
             if (eventName == null)
@@ -175,7 +173,6 @@ namespace System.Diagnostics.Tracing
         /// public instance properties of data will be written recursively to
         /// create the fields of the event.
         /// </param>
-        [SecuritySafeCritical]
         public unsafe void Write<T>(
             string eventName,
             T data)
@@ -212,7 +209,6 @@ namespace System.Diagnostics.Tracing
         /// public instance properties of data will be written recursively to
         /// create the fields of the event.
         /// </param>
-        [SecuritySafeCritical]
         public unsafe void Write<T>(
             string eventName,
             EventSourceOptions options,
@@ -251,7 +247,6 @@ namespace System.Diagnostics.Tracing
         /// public instance properties of data will be written recursively to
         /// create the fields of the event.
         /// </param>
-        [SecuritySafeCritical]
         public unsafe void Write<T>(
             string eventName,
             ref EventSourceOptions options,
@@ -297,7 +292,6 @@ namespace System.Diagnostics.Tracing
         /// public instance properties of data will be written recursively to
         /// create the fields of the event.
         /// </param>
-        [SecuritySafeCritical]
         public unsafe void Write<T>(
             string eventName,
             ref EventSourceOptions options,
@@ -354,7 +348,6 @@ namespace System.Diagnostics.Tracing
         /// the values must match the number and types of the fields described by the
         /// eventTypes parameter.
         /// </param>
-        [SecuritySafeCritical]
         private unsafe void WriteMultiMerge(
             string eventName,
             ref EventSourceOptions options,
@@ -415,7 +408,6 @@ namespace System.Diagnostics.Tracing
         /// the values must match the number and types of the fields described by the
         /// eventTypes parameter.
         /// </param>
-        [SecuritySafeCritical]
         private unsafe void WriteMultiMergeInner(
             string eventName,
             ref EventSourceOptions options,
@@ -526,7 +518,6 @@ namespace System.Diagnostics.Tracing
         /// The number and types of the values must match the number and types of the 
         /// fields described by the eventTypes parameter.
         /// </param>
-        [SecuritySafeCritical]
         internal unsafe void WriteMultiMerge(
             string eventName,
             ref EventSourceOptions options,
@@ -604,7 +595,6 @@ namespace System.Diagnostics.Tracing
 #endif // FEATURE_MANAGED_ETW
         }
 
-        [SecuritySafeCritical]
         private unsafe void WriteImpl(
             string eventName,
             ref EventSourceOptions options,
@@ -721,7 +711,6 @@ namespace System.Diagnostics.Tracing
             }
         }
 
-        [SecurityCritical]
         private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
         {
             EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
@@ -750,7 +739,6 @@ namespace System.Diagnostics.Tracing
             System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState,
             System.Runtime.ConstrainedExecution.Cer.Success)]
 #endif
-        [SecurityCritical]
         [NonEvent]
         private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
         {
index 80e7b86..84f6b91 100644 (file)
@@ -33,7 +33,6 @@ namespace System.Diagnostics {
         // 
         // All switches (except for the global LogSwitch) have a parent LogSwitch.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public LogSwitch(String name, String description, LogSwitch parent)
         {
             if (name != null && name.Length == 0)
@@ -58,7 +57,6 @@ namespace System.Diagnostics {
                 throw new ArgumentNullException ((name==null ? nameof(name) : nameof(parent)));
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal LogSwitch(String name, String description)
         {
             strName = name;
@@ -100,7 +98,6 @@ namespace System.Diagnostics {
         public  virtual LoggingLevels  MinimumLevel
         {
             get { return iLevel; }
-            [System.Security.SecuritySafeCritical]  // auto-generated
             set 
             { 
                 iLevel = value; 
index 397c3e1..06d675e 100644 (file)
@@ -11,13 +11,7 @@ namespace System.Diagnostics {
     using System.Security.Permissions;
     using System.Diagnostics.Contracts;
 
-    // There is no good reason for the methods of this class to be virtual.  
-    // In order to ensure trusted code can trust the data it gets from a 
-    // StackTrace, we use an InheritanceDemand to prevent partially-trusted
-    // subclasses.
-#if !FEATURE_CORECLR
-    [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
+    // There is no good reason for the methods of this class to be virtual.
     [Serializable]
     [System.Runtime.InteropServices.ComVisible(true)]
     public class StackFrame
@@ -49,9 +43,6 @@ namespace System.Diagnostics {
         }
 
         // Constructs a StackFrame corresponding to the active stack frame.
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-#endif
         public StackFrame()
         {
             InitMembers();
@@ -59,9 +50,6 @@ namespace System.Diagnostics {
         }
     
         // Constructs a StackFrame corresponding to the active stack frame.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public StackFrame(bool fNeedFileInfo)
         {
             InitMembers();
@@ -78,9 +66,6 @@ namespace System.Diagnostics {
     
         // Constructs a StackFrame corresponding to a calling stack frame.
         // 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public StackFrame(int skipFrames, bool fNeedFileInfo)
         {
             InitMembers();
@@ -200,11 +185,6 @@ namespace System.Diagnostics {
         // information is normally extracted from the debugging symbols
         // for the executable.
         //
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         public virtual String GetFileName()
         {
             if (strFileName != null)
@@ -242,7 +222,6 @@ namespace System.Diagnostics {
     
         // Builds a readable representation of the stack frame
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString()
         {
             StringBuilder sb = new StringBuilder(255);
index 06f38c4..7dc5d9d 100644 (file)
@@ -61,14 +61,12 @@ namespace System.Diagnostics {
             IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset, 
             out string sourceFile, out int sourceLine, out int sourceColumn);
 
-#if FEATURE_CORECLR
         private static Type s_symbolsType = null;
         private static MethodInfo s_symbolsMethodInfo = null;
 
         [ThreadStatic]
         private static int t_reentrancy = 0;
-#endif
-        
+
         public StackFrameHelper(Thread target)
         {
             targetThread = target;
@@ -111,7 +109,6 @@ namespace System.Diagnostics {
         {
             StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception);
 
-#if FEATURE_CORECLR
             if (!fNeedFileInfo)
                 return;
 
@@ -164,12 +161,10 @@ namespace System.Diagnostics {
             {
                 t_reentrancy--;
             }
-#endif
         }
 
         void IDisposable.Dispose()
         {
-#if FEATURE_CORECLR
             if (getSourceLineInfo != null)
             {
                 IDisposable disposable = getSourceLineInfo.Target as IDisposable;
@@ -178,10 +173,8 @@ namespace System.Diagnostics {
                     disposable.Dispose();
                 }
             }
-#endif
         }
 
-        [System.Security.SecuritySafeCritical]
         public virtual MethodBase GetMethodBase(int i) 
         { 
             // There may be a better way to do this.
@@ -219,7 +212,6 @@ namespace System.Diagnostics {
         // serialization implementation
         //
         [OnSerializing]
-        [SecuritySafeCritical]
         void OnSerializing(StreamingContext context)
         {
             // this is called in the process of serializing this object.
@@ -244,7 +236,6 @@ namespace System.Diagnostics {
         }
 
         [OnDeserialized]
-        [SecuritySafeCritical]
         void OnDeserialized(StreamingContext context)
         {
             // after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle
@@ -267,9 +258,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.
-#if !FEATURE_CORECLR
-    [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
     [Serializable]
     [System.Runtime.InteropServices.ComVisible(true)]
     public class StackTrace
@@ -280,9 +268,6 @@ namespace System.Diagnostics {
         private int m_iMethodsToSkip;
 
         // Constructs a stack trace from the current location.
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-#endif
         public StackTrace()
         {
             m_iNumOfFrames = 0;
@@ -292,9 +277,6 @@ namespace System.Diagnostics {
 
         // Constructs a stack trace from the current location.
         //
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public StackTrace(bool fNeedFileInfo)
         {
             m_iNumOfFrames = 0;
@@ -305,9 +287,6 @@ namespace System.Diagnostics {
         // Constructs a stack trace from the current location, in a caller's
         // frame
         //
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public StackTrace(int skipFrames)
         {
     
@@ -325,9 +304,6 @@ namespace System.Diagnostics {
         // Constructs a stack trace from the current location, in a caller's
         // frame
         //
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public StackTrace(int skipFrames, bool fNeedFileInfo)
         {
     
@@ -357,9 +333,6 @@ namespace System.Diagnostics {
 
         // Constructs a stack trace from the current location.
         //
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public StackTrace(Exception e, bool fNeedFileInfo)
         {
             if (e == null)
@@ -374,9 +347,6 @@ namespace System.Diagnostics {
         // Constructs a stack trace from the current location, in a caller's
         // frame
         //
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public StackTrace(Exception e, int skipFrames)
         {
             if (e == null)
@@ -396,9 +366,6 @@ namespace System.Diagnostics {
         // Constructs a stack trace from the current location, in a caller's
         // frame
         //
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo)
         {
             if (e == null)
@@ -430,9 +397,6 @@ namespace System.Diagnostics {
 
         // Constructs a stack trace for the given thread
         //
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         [Obsolete("This constructor has been deprecated.  Please use a constructor that does not require a Thread parameter.  http://go.microsoft.com/fwlink/?linkid=14202")]
         public StackTrace(Thread targetThread, bool needFileInfo)
         {    
@@ -443,7 +407,6 @@ namespace System.Diagnostics {
 
         }
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e);
     
@@ -576,9 +539,6 @@ namespace System.Diagnostics {
     
         // Builds a readable representation of the stack trace
         //
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] 
-#endif
         public override String ToString()
         {
             // Include a trailing newline for backwards compatibility
@@ -596,9 +556,6 @@ namespace System.Diagnostics {
             
         // Builds a readable representation of the stack trace, specifying 
         // the format for backwards compatibility.
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         internal String ToString(TraceFormat traceFormat)
         {
             bool displayFilenames = true;   // we'll try, but demand may fail
@@ -656,26 +613,22 @@ namespace System.Diagnostics {
                             else
                                 fFirstTyParam = false;
 
-                            sb.Append(typars[k].Name);             
+                            sb.Append(typars[k].Name);
                             k++;
                         }   
                         sb.Append(']');    
                     }
 
                     ParameterInfo[] pi = null;
-#if FEATURE_CORECLR
                     try
                     {
-#endif
                         pi = mb.GetParameters();
-#if FEATURE_CORECLR
                     }
                     catch
                     {
                         // The parameter info cannot be loaded, so we don't
                         // append the parameter list.
                     }
-#endif
                     if (pi != null)
                     {
                         // arguments printing
@@ -712,15 +665,6 @@ namespace System.Diagnostics {
                         {
                             fileName = sf.GetFileName();
                         }
-#if FEATURE_CAS_POLICY
-                        catch (NotSupportedException)
-                        {
-                            // Having a deprecated stack modifier on the callstack (such as Deny) will cause
-                            // a NotSupportedException to be thrown.  Since we don't know if the app can
-                            // access the file names, we'll conservatively hide them.
-                            displayFilenames = false;
-                        }
-#endif // FEATURE_CAS_POLICY
                         catch (SecurityException)
                         {
                             // If the demand for displaying filenames fails, then it won't
@@ -754,9 +698,6 @@ namespace System.Diagnostics {
 
         // This helper is called from within the EE to construct a string representation
         // of the current stack trace.
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo)
         {
             // Note all the frames in System.Diagnostics will be skipped when capturing 
index b6177be..a0d3640 100644 (file)
@@ -31,9 +31,6 @@ namespace System.Diagnostics.SymbolStore {
         // Define a source document. Guid's will be provided for the
         // languages, vendors, and document types that we currently know
         // about.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         ISymbolDocumentWriter DefineDocument(String url,
                                           Guid language,
                                           Guid languageVendor,
@@ -42,9 +39,6 @@ namespace System.Diagnostics.SymbolStore {
         // Define the method that the user has defined as their entrypoint
         // for this module. This would be, perhaps, the user's main method
         // rather than compiler generated stubs before main.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         void SetUserEntryPoint(SymbolToken entryMethod);
     
         // Open a method to emit symbol information into. The given method
@@ -55,25 +49,16 @@ namespace System.Diagnostics.SymbolStore {
         // defined symbols for that method.
         //
         // There can be only one open method at a time.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         void OpenMethod(SymbolToken method);
     
         // Close the current method. Once a method is closed, no more
         // symbols can be defined within it.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         void CloseMethod();
     
         // Define a group of sequence points within the current method.
         // Each line/column defines the start of a statement within a
         // method. The arrays should be sorted by offset. The offset is
         // always the offset from the start of the method, in bytes.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         void DefineSequencePoints(ISymbolDocumentWriter document,
                                   int[] offsets,
                                   int[] lines,
@@ -96,17 +81,11 @@ namespace System.Diagnostics.SymbolStore {
         // Note: scope id's are only valid in the current method.
         //
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         int OpenScope(int startOffset);
     
         // Close the current lexical scope. Once a scope is closed no more
         // variables can be defined within it. endOffset points past the
         // last instruction in the scope.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         void CloseScope(int endOffset);
     
         // Define the offset range for a given lexical scope.
@@ -120,9 +99,6 @@ namespace System.Diagnostics.SymbolStore {
         // variable of the same name that has multiple homes throughout a
         // scope. (Note: start/end offsets must not overlap in such a
         // case.)
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         void DefineLocalVariable(String name,
                                         FieldAttributes attributes,
                                         byte[] signature,
@@ -178,9 +154,6 @@ namespace System.Diagnostics.SymbolStore {
         // Defines a custom attribute based upon its name. Not to be
         // confused with Metadata custom attributes, these attributes are
         // held in the symbol store.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         void SetSymAttribute(SymbolToken parent, String name, byte[] data);
     
         // Opens a new namespace. Call this before defining methods or
@@ -195,9 +168,6 @@ namespace System.Diagnostics.SymbolStore {
         // current scope will also stop using the namespace, and the
         // namespace will be in use in all scopes that inherit from the
         // currently open scope.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         void UsingNamespace(String fullName);
         
         // Specifies the true start and end of a method within a source
index f600da8..6916ce3 100644 (file)
@@ -22,7 +22,6 @@ namespace System.Diagnostics {
    // programatically, by registry (specifics....) or environment
    // variables.
     [Serializable]
-    [HostProtection(Synchronization=true, ExternalThreading=true)]
     internal delegate void LogMessageEventHandler(LoggingLevels level, LogSwitch category, 
                                                     String message, 
                                                     StackTrace location);
@@ -240,10 +239,8 @@ namespace System.Diagnostics {
         
     
         // Native method to inform the EE about the creation of a new LogSwitch
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void AddLogSwitch(LogSwitch logSwitch);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void ModifyLogSwitch (int iNewLevel, String strSwitchName, String strParentName);
     }
index b2d509a..ce146a1 100644 (file)
@@ -44,7 +44,6 @@ namespace System {
         internal static double NegativeZero = BitConverter.Int64BitsToDouble(unchecked((long)0x8000000000000000));
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool IsInfinity(double d) {
             return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;
@@ -79,14 +78,12 @@ namespace System {
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static bool IsNegative(double d) {
             return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000;
         }
 
         [Pure]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool IsNaN(double d)
         {
@@ -187,7 +184,6 @@ namespace System {
         //The hashcode for a double is the absolute value of the integer representation
         //of that double.
         //
-        [System.Security.SecuritySafeCritical]
         public unsafe override int GetHashCode() {
             double d = m_value;
             if (d == 0) {
@@ -198,25 +194,21 @@ namespace System {
             return unchecked((int)value) ^ ((int)(value >> 32));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider));
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format, IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider));
index c54c99a..4790d9a 100644 (file)
@@ -25,7 +25,6 @@ namespace System {
             return String.Empty;
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
index 38228f7..d39e005 100644 (file)
@@ -9,6 +9,7 @@ using System.Globalization;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Runtime.Versioning;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System 
@@ -23,7 +24,6 @@ namespace System
         #endregion
 
         #region Private Static Methods
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static TypeValuesAndNames GetCachedValuesAndNames(RuntimeType enumType, bool getNames)
         {
             TypeValuesAndNames entry = enumType.GenericCache as TypeValuesAndNames;
@@ -47,7 +47,6 @@ namespace System
             return entry;
         }
 
-        [System.Security.SecuritySafeCritical]
         private unsafe String InternalFormattedHexString()
         {
             fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
@@ -71,7 +70,7 @@ namespace System
                     case CorElementType.U8:
                         return (*(ulong*)pValue).ToString("X16", null);
                     default:
-                        Contract.Assert(false, "Invalid Object type in Format");
+                        Debug.Assert(false, "Invalid Object type in Format");
                         throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
                 }
             }
@@ -106,7 +105,7 @@ namespace System
                     return ((UInt64)(Int64)value).ToString("X16", null);
                 // All unsigned types will be directly cast
                 default:
-                    Contract.Assert(false, "Invalid Object type in Format");
+                    Debug.Assert(false, "Invalid Object type in Format");
                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
             }
         }
@@ -157,7 +156,7 @@ namespace System
 
             String[] names = entry.Names;
             ulong[] values = entry.Values;
-            Contract.Assert(names.Length == values.Length);
+            Debug.Assert(names.Length == values.Length);
 
             int index = values.Length - 1;
             StringBuilder retval = new StringBuilder();
@@ -245,27 +244,23 @@ namespace System
                     break;
                 // All unsigned types will be directly cast
                 default:
-                    Contract.Assert(false, "Invalid Object type in ToUInt64");
+                    Debug.Assert(false, "Invalid Object type in ToUInt64");
                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
             }
 
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int InternalCompareTo(Object o1, Object o2);
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [System.Security.SuppressUnmanagedCodeSecurity]
         private static extern void GetEnumValuesAndNames(RuntimeTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, bool getNames);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern Object InternalBoxEnum(RuntimeType enumType, long value);
         #endregion
@@ -328,7 +323,7 @@ namespace System
                         return m_innerException;
 
                     default:
-                        Contract.Assert(false, "Unknown EnumParseFailure: " + m_failure);
+                        Debug.Assert(false, "Unknown EnumParseFailure: " + m_failure);
                         return new ArgumentException(Environment.GetResourceString("Arg_EnumValueNotFound"));
                 }
             }
@@ -728,7 +723,6 @@ namespace System
         #endregion
 
         #region Private Methods
-        [System.Security.SecuritySafeCritical]
         internal unsafe Object GetValue()
         {
             fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
@@ -764,13 +758,12 @@ namespace System
                     case CorElementType.U:
                         return *(UIntPtr*)pValue;
                     default:
-                        Contract.Assert(false, "Invalid primitive type");
+                        Debug.Assert(false, "Invalid primitive type");
                         return null;
                 }
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         private unsafe ulong ToUInt64()
         {
             fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
@@ -817,28 +810,24 @@ namespace System
                             return *(uint*)pValue;
                         }
                     default:
-                        Contract.Assert(false, "Invalid primitive type");
+                        Debug.Assert(false, "Invalid primitive type");
                         return 0;
                 }
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern bool InternalHasFlag(Enum flags);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern CorElementType InternalGetCorElementType();
 
         #endregion
 
         #region Object Overrides
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern override bool Equals(Object obj);
 
-        [System.Security.SecuritySafeCritical]
         public override unsafe int GetHashCode()
         {
             // CONTRACT with the runtime: GetHashCode of enum types is implemented as GetHashCode of the underlying type.
@@ -878,7 +867,7 @@ namespace System
                     case CorElementType.U:
                         return (*(UIntPtr*)pValue).GetHashCode();
                     default:
-                        Contract.Assert(false, "Invalid primitive type");
+                        Debug.Assert(false, "Invalid primitive type");
                         return 0;
                 }
             }
@@ -907,7 +896,6 @@ namespace System
         #endregion
 
         #region IComparable
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public int CompareTo(Object target)
         {
             const int retIncompatibleMethodTables = 2;  // indicates that the method tables did not match
@@ -935,7 +923,7 @@ namespace System
             else
             {
                 // assert valid return code (3)
-                Contract.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid");
+                Debug.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid");
                 
                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
             }
@@ -973,7 +961,6 @@ namespace System
             return ToString();
         }
 
-        [System.Security.SecuritySafeCritical]
         public Boolean HasFlag(Enum flag) {
             if (flag == null)
                 throw new ArgumentNullException(nameof(flag));
@@ -1044,7 +1031,7 @@ namespace System
                 return TypeCode.Char;
             }
 
-            Contract.Assert(false, "Unknown underlying type.");
+            Debug.Assert(false, "Unknown underlying type.");
             throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
         }
 
@@ -1140,7 +1127,6 @@ namespace System
         #endregion
     
         #region ToObject
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(true)]
         public static Object ToObject(Type enumType, sbyte value)
@@ -1156,7 +1142,6 @@ namespace System
             return InternalBoxEnum(rtType, value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public static Object ToObject(Type enumType, short value)
         {
@@ -1171,7 +1156,6 @@ namespace System
             return InternalBoxEnum(rtType, value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public static Object ToObject(Type enumType, int value)
         {
@@ -1186,7 +1170,6 @@ namespace System
             return InternalBoxEnum(rtType, value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public static Object ToObject(Type enumType, byte value)
         {
@@ -1201,7 +1184,6 @@ namespace System
             return InternalBoxEnum(rtType, value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(true)]
         public static Object ToObject(Type enumType, ushort value)
@@ -1217,7 +1199,6 @@ namespace System
             return InternalBoxEnum(rtType, value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(true)]
         public static Object ToObject(Type enumType, uint value)
@@ -1233,7 +1214,6 @@ namespace System
             return InternalBoxEnum(rtType, value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public static Object ToObject(Type enumType, long value)
         {
@@ -1248,7 +1228,6 @@ namespace System
             return InternalBoxEnum(rtType, value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(true)]
         public static Object ToObject(Type enumType, ulong value)
@@ -1264,7 +1243,6 @@ namespace System
             return InternalBoxEnum(rtType, unchecked((long)value));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static Object ToObject(Type enumType, char value)
         {
             if (enumType == null)
@@ -1278,7 +1256,6 @@ namespace System
             return InternalBoxEnum(rtType, value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static Object ToObject(Type enumType, bool value)
         {
             if (enumType == null)
diff --git a/src/mscorlib/src/System/Environment.Unix.cs b/src/mscorlib/src/System/Environment.Unix.cs
deleted file mode 100644 (file)
index 13fba7e..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections;
-using System.Collections.Generic;
-
-namespace System
-{
-    public static partial class Environment
-    {
-        private static readonly unsafe Lazy<Dictionary<string, string>> s_environ = new Lazy<Dictionary<string, string>>(() =>
-        {
-            // We cache on Unix as using the block isn't thread safe
-            return GetRawEnvironmentVariables();
-        });
-
-        private static string GetEnvironmentVariableCore(string variable)
-        {
-            // Ensure variable doesn't include a null char
-            int nullEnd = variable.IndexOf('\0');
-            if (nullEnd != -1)
-            {
-                variable = variable.Substring(0, nullEnd);
-            }
-
-            // Get the value of the variable
-            lock (s_environ)
-            {
-                string value;
-                return s_environ.Value.TryGetValue(variable, out value) ? value : null;
-            }
-        }
-
-        private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
-        {
-            return target == EnvironmentVariableTarget.Process ?
-                GetEnvironmentVariableCore(variable) :
-                null;
-        }
-
-        private static IDictionary GetEnvironmentVariablesCore()
-        {
-            lock (s_environ)
-            {
-                return new Dictionary<string, string>(s_environ.Value);
-            }
-        }
-
-        private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target)
-        {
-            return target == EnvironmentVariableTarget.Process ?
-                GetEnvironmentVariablesCore() :
-                new Dictionary<string, string>();
-        }
-
-        private static void SetEnvironmentVariableCore(string variable, string value)
-        {
-            int nullEnd;
-
-            // Ensure variable doesn't include a null char
-            nullEnd = variable.IndexOf('\0');
-            if (nullEnd != -1)
-            {
-                variable = variable.Substring(0, nullEnd);
-            }
-
-            // Ensure value doesn't include a null char
-            if (value != null)
-            {
-                nullEnd = value.IndexOf('\0');
-                if (nullEnd != -1)
-                {
-                    value = value.Substring(0, nullEnd);
-                }
-            }
-
-            lock (s_environ)
-            {
-                // Remove the entry if the value is null, otherwise add/overwrite it
-                if (value == null)
-                {
-                    s_environ.Value.Remove(variable);
-                }
-                else
-                {
-                    s_environ.Value[variable] = value;
-                }
-            }
-        }
-
-        private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
-        {
-            if (target == EnvironmentVariableTarget.Process)
-            {
-                SetEnvironmentVariableCore(variable, value);
-            }
-            // other targets ignored
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/mscorlib/src/System/Environment.Win32.cs b/src/mscorlib/src/System/Environment.Win32.cs
deleted file mode 100644 (file)
index ac3c6a7..0000000
+++ /dev/null
@@ -1,226 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Microsoft.Win32;
-using System.Collections;
-using System.Collections.Generic;
-using System.Runtime.InteropServices;
-using System.Text;
-
-namespace System
-{
-    public static partial class Environment
-    {
-        private static string GetEnvironmentVariableCore(string variable)
-        {
-            if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
-            {
-                // Environment variable accessors are not approved modern API.
-                // Behave as if the variable was not found in this case.
-                return null;
-            }
-
-            StringBuilder sb = StringBuilderCache.Acquire(128); // A somewhat reasonable default size
-            int requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
-
-            if (requiredSize == 0 && Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND)
-            {
-                StringBuilderCache.Release(sb);
-                return null;
-            }
-
-            while (requiredSize > sb.Capacity)
-            {
-                sb.Capacity = requiredSize;
-                sb.Length = 0;
-                requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
-            }
-
-            return StringBuilderCache.GetStringAndRelease(sb);
-        }
-
-        private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
-        {
-            if (target == EnvironmentVariableTarget.Process)
-                return GetEnvironmentVariableCore(variable);
-
-#if FEATURE_WIN32_REGISTRY
-            RegistryKey baseKey;
-            string keyName;
-
-            if (target == EnvironmentVariableTarget.Machine)
-            {
-                baseKey = Registry.LocalMachine;
-                keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
-            }
-            else if (target == EnvironmentVariableTarget.User)
-            {
-                Debug.Assert(target == EnvironmentVariableTarget.User);
-                baseKey = Registry.CurrentUser;
-                keyName = "Environment";
-            }
-            else
-            {
-                throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
-            }
-
-            using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
-            {
-                return environmentKey?.GetValue(variable) as string;
-            }
-#else
-            throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
-#endif
-        }
-
-        private static IDictionary GetEnvironmentVariablesCore()
-        {
-            if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
-            {
-                // Environment variable accessors are not approved modern API.
-                // Behave as if no environment variables are defined in this case.
-                return new Hashtable(0);
-            }
-
-            return GetRawEnvironmentVariables();
-        }
-
-        private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target)
-        {
-            if (target == EnvironmentVariableTarget.Process)
-                return GetEnvironmentVariablesCore();
-
-#if FEATURE_WIN32_REGISTRY
-            RegistryKey baseKey;
-            string keyName;
-            if (target == EnvironmentVariableTarget.Machine)
-            {
-                baseKey = Registry.LocalMachine;
-                keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
-            }
-            else if (target == EnvironmentVariableTarget.User)
-            {
-                Debug.Assert(target == EnvironmentVariableTarget.User);
-                baseKey = Registry.CurrentUser;
-                keyName = @"Environment";
-            }
-            else
-            {
-                throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
-            }
-
-            using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
-            {
-                var table = new Dictionary<string, string>();
-                if (environmentKey != null)
-                {
-                    foreach (string name in environmentKey.GetValueNames())
-                    {
-                        table.Add(name, environmentKey.GetValue(name, "").ToString());
-                    }
-                }
-                return table;
-            }
-#endif // FEATURE_WIN32_REGISTRY
-
-            throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
-        }
-
-        private static void SetEnvironmentVariableCore(string variable, string value)
-        {
-            // explicitly null out value if is the empty string.
-            if (string.IsNullOrEmpty(value) || value[0] == '\0')
-                value = null;
-
-            if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
-            {
-                // Environment variable accessors are not approved modern API.
-                // so we throw PlatformNotSupportedException.
-                throw new PlatformNotSupportedException();
-            }
-
-            if (!Win32Native.SetEnvironmentVariable(variable, value))
-            {
-                int errorCode = Marshal.GetLastWin32Error();
-
-                switch (errorCode)
-                {
-                    case Win32Native.ERROR_ENVVAR_NOT_FOUND:
-                        // Allow user to try to clear a environment variable
-                        return;
-                    case Win32Native.ERROR_FILENAME_EXCED_RANGE:
-                        // The error message from Win32 is "The filename or extension is too long",
-                        // which is not accurate.
-                        throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"));
-                    default:
-                        throw new ArgumentException(Win32Native.GetMessage(errorCode));
-                }
-            }
-        }
-
-        private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
-        {
-            if (target == EnvironmentVariableTarget.Process)
-            {
-                SetEnvironmentVariableCore(variable, value);
-                return;
-            }
-
-            // explicitly null out value if is the empty string.
-            if (string.IsNullOrEmpty(value) || value[0] == '\0')
-                value = null;
-
-#if FEATURE_WIN32_REGISTRY
-            RegistryKey baseKey;
-            string keyName;
-
-            if (target == EnvironmentVariableTarget.Machine)
-            {
-                baseKey = Registry.LocalMachine;
-                keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
-            }
-            else if (target == EnvironmentVariableTarget.User)
-            {
-                Debug.Assert(target == EnvironmentVariableTarget.User);
-
-                // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name.
-                const int MaxUserEnvVariableLength = 255;
-                if (variable.Length >= MaxUserEnvVariableLength)
-                {
-                    throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable));
-                }
-
-                baseKey = Registry.CurrentUser;
-                keyName = "Environment";
-            }
-            else
-            {
-                throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
-            }
-
-            using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true))
-            {
-                if (environmentKey != null)
-                {
-                    if (value == null)
-                    {
-                        environmentKey.DeleteValue(variable, throwOnMissingValue: false);
-                    }
-                    else
-                    {
-                        environmentKey.SetValue(variable, value);
-                    }
-                }
-            }
-
-            // send a WM_SETTINGCHANGE message to all windows
-            IntPtr r = Win32Native.SendMessageTimeout(new IntPtr(Win32Native.HWND_BROADCAST), Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
-            if (r == IntPtr.Zero) Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
-
-#else // FEATURE_WIN32_REGISTRY
-            throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)target));
-#endif
-        }
-    }
-}
\ No newline at end of file
index 6799078..835219a 100644 (file)
@@ -88,11 +88,10 @@ namespace System {
                 }
             }
             
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
             internal String GetResourceString(String key)  {
                 if (key == null || key.Length == 0) {
-                    Contract.Assert(false, "Environment::GetResourceString with null or empty key.  Bug in caller, or weird recursive loading problem?");
+                    Debug.Assert(false, "Environment::GetResourceString with null or empty key.  Bug in caller, or weird recursive loading problem?");
                     return "[Resource lookup failed - null or empty resource name]";
                 }
 
@@ -124,11 +123,6 @@ namespace System {
                 return userData.m_retVal;
             }
 
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #else
-            [System.Security.SecuritySafeCritical]
-            #endif
             private void GetResourceStringCode(Object userDataIn)
             {
                 GetResourceStringUserData userData = (GetResourceStringUserData) userDataIn;
@@ -188,14 +182,11 @@ namespace System {
                 String s = rh.SystemResMgr.GetString(key, null);
                 rh.currentlyLoading.RemoveAt(rh.currentlyLoading.Count - 1); // Pop
 
-                Contract.Assert(s!=null, "Managed resource string lookup failed.  Was your resource name misspelled?  Did you rebuild mscorlib after adding a resource to resources.txt?  Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString.  Resource name was: \""+key+"\"");
+                Debug.Assert(s!=null, "Managed resource string lookup failed.  Was your resource name misspelled?  Did you rebuild mscorlib after adding a resource to resources.txt?  Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString.  Resource name was: \""+key+"\"");
 
                 userData.m_retVal = s;
             }
 
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             [PrePrepareMethod]
             private void GetResourceStringBackoutCode(Object userDataIn, bool exceptionThrown)
             {
@@ -247,32 +238,24 @@ namespace System {
         **Exceptions: None
         ==============================================================================*/
         public static extern int TickCount {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
             get;
         }
         
         // Terminates this process with the given exit code.
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal static extern void _Exit(int exitCode);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         public static void Exit(int exitCode) {
             _Exit(exitCode);
         }
 
 
         public static extern int ExitCode {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
             get;
     
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
             set;
         }
@@ -280,11 +263,9 @@ namespace System {
         // Note: The CLR's Watson bucketization code looks at the caller of the FCALL method
         // to assign blame for crashes.  Don't mess with this, such as by making it call 
         // another managed helper method, unless you consult with some CLR Watson experts.
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void FailFast(String message);
 
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void FailFast(String message, uint exitCode);
 
@@ -301,44 +282,9 @@ namespace System {
         //    if the exception object is preallocated, the runtime will use the callsite's
         //    IP for bucketing. If the exception object is not preallocated, it will use the bucket
         //    details contained in the object (if any).
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void FailFast(String message, Exception exception);
 
-#if !FEATURE_CORECLR
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]  // Our security team doesn't yet allow safe-critical P/Invoke methods.
-        [SuppressUnmanagedCodeSecurity]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-        internal static extern void TriggerCodeContractFailure(ContractFailureKind failureKind, String message, String condition, String exceptionAsString);
-
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]  // Our security team doesn't yet allow safe-critical P/Invoke methods.
-        [SuppressUnmanagedCodeSecurity]
-        [return: MarshalAs(UnmanagedType.Bool)]
-        private static extern bool GetIsCLRHosted();
-
-        internal static bool IsCLRHosted {
-            [SecuritySafeCritical]
-            get { return GetIsCLRHosted(); }
-        }
-
-        public static String CommandLine {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            get {
-                new EnvironmentPermission(EnvironmentPermissionAccess.Read, "Path").Demand();
-
-                String commandLine = null;
-                GetCommandLine(JitHelpers.GetStringHandleOnStack(ref commandLine));
-                return commandLine;
-            }
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        private static extern void GetCommandLine(StringHandleOnStack retString);
-#endif // !FEATURE_CORECLR
-
         /*===============================CurrentDirectory===============================
         **Action:  Provides a getter and setter for the current directory.  The original
         **         current directory is the one from which the process was started.  
@@ -352,9 +298,6 @@ namespace System {
                 return Directory.GetCurrentDirectory();
             }
 
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             set { 
                 Directory.SetCurrentDirectory(value);
             }
@@ -362,22 +305,12 @@ namespace System {
 
         // Returns the system directory (ie, C:\WinNT\System32).
         public static String SystemDirectory {
-#if FEATURE_CORECLR
-            [System.Security.SecurityCritical]
-#else
-            [System.Security.SecuritySafeCritical]  // auto-generated
-#endif
             get {
                 StringBuilder sb = new StringBuilder(Path.MaxPath);
                 int r = Win32Native.GetSystemDirectory(sb, Path.MaxPath);
-                Contract.Assert(r < Path.MaxPath, "r < Path.MaxPath");
+                Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath");
                 if (r==0) __Error.WinIOError();
                 String path = sb.ToString();
-                
-#if !FEATURE_CORECLR
-                // Do security check
-                new FileIOPermission(FileIOPermissionAccess.PathDiscovery, path).Demand();
-#endif
 
                 return path;
             }
@@ -386,11 +319,10 @@ namespace System {
         // Returns the windows directory (ie, C:\WinNT).
         // Used by NLS+ custom culures only at the moment.
         internal static String InternalWindowsDirectory {
-            [System.Security.SecurityCritical]  // auto-generated
             get {
                 StringBuilder sb = new StringBuilder(Path.MaxPath);
                 int r = Win32Native.GetWindowsDirectory(sb, Path.MaxPath);
-                Contract.Assert(r < Path.MaxPath, "r < Path.MaxPath");
+                Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath");
                 if (r==0) __Error.WinIOError();
                 String path = sb.ToString();
                 
@@ -398,7 +330,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String ExpandEnvironmentVariables(String name)
         {
             if (name == null)
@@ -441,63 +372,6 @@ namespace System {
 
             int size;
 
-#if !FEATURE_CORECLR
-            bool isFullTrust = CodeAccessSecurityEngine.QuickCheckForAllDemands();
-
-            // Do a security check to guarantee we can read each of the 
-            // individual environment variables requested here.
-            String[] varArray = name.Split(new char[] {'%'});
-            StringBuilder vars = isFullTrust ? null : new StringBuilder();
-
-            bool fJustExpanded = false; // to accommodate expansion alg.
-
-            for(int i=1; i<varArray.Length-1; i++) { // Skip first and last tokens
-                // ExpandEnvironmentStrings' greedy algorithm expands every
-                // non-boundary %-delimited substring, provided the previous
-                // has not been expanded.
-                // if "foo" is not expandable, and "PATH" is, then both
-                // %foo%PATH% and %foo%foo%PATH% will expand PATH, but
-                // %PATH%PATH% will expand only once.
-                // Therefore, if we've just expanded, skip this substring.
-                if (varArray[i].Length == 0 || fJustExpanded == true)
-                {
-                    fJustExpanded = false;
-                    continue; // Nothing to expand
-                }
-                // Guess a somewhat reasonable initial size, call the method, then if
-                // it fails (ie, the return value is larger than our buffer size),
-                // make a new buffer & try again.
-                blob.Length = 0;
-                String envVar = "%" + varArray[i] + "%";
-                size = Win32Native.ExpandEnvironmentStrings(envVar, blob, currentSize);
-                if (size == 0)
-                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
-
-                // some environment variable might be changed while this function is called
-                while (size > currentSize) {
-                    currentSize = size;
-                    blob.Capacity = currentSize;
-                    blob.Length = 0;
-                    size = Win32Native.ExpandEnvironmentStrings(envVar, blob, currentSize);
-                    if (size == 0)
-                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
-                }
-
-                if (!isFullTrust) {
-                    String temp = blob.ToString();
-                    fJustExpanded = (temp != envVar);
-                    if (fJustExpanded) { // We expanded successfully, we need to do String comparison here
-                        // since %FOO% can become %FOOD
-                        vars.Append(varArray[i]);
-                        vars.Append(';');
-                    }
-                }
-            }
-     
-            if (!isFullTrust)
-                new EnvironmentPermission(EnvironmentPermissionAccess.Read, vars.ToString()).Demand();
-#endif // !FEATURE_CORECLR
-
             blob.Length = 0;
             size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize);
             if (size == 0)
@@ -518,7 +392,6 @@ namespace System {
         }
 
         public static String MachineName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
 
                 // UWP Debug scenarios
@@ -530,9 +403,6 @@ namespace System {
 
                 // In future release of operating systems, you might be able to rename a machine without
                 // rebooting.  Therefore, don't cache this machine name.
-#if !FEATURE_CORECLR
-                new EnvironmentPermission(EnvironmentPermissionAccess.Read, "COMPUTERNAME").Demand();
-#endif
                 StringBuilder buf = new StringBuilder(MaxMachineNameLength);
                 int len = MaxMachineNameLength;
                 if (Win32Native.GetComputerName(buf, ref len) == 0)
@@ -541,20 +411,17 @@ namespace System {
             }
         }
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern Int32 GetProcessorCount();
 
         public static int ProcessorCount {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return GetProcessorCount();
             }
         }
 
         public static int SystemPageSize {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 (new EnvironmentPermission(PermissionState.Unrestricted)).Demand();
                 Win32Native.SYSTEM_INFO info = new Win32Native.SYSTEM_INFO();
@@ -570,11 +437,9 @@ namespace System {
         **Arguments: None
         **Exceptions: None.
         ==============================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String[] GetCommandLineArgs()
         {
             new EnvironmentPermission(EnvironmentPermissionAccess.Read, "Path").Demand();
-#if FEATURE_CORECLR
             /*
              * There are multiple entry points to a hosted app.
              * The host could use ::ExecuteAssembly() or ::CreateDelegate option
@@ -590,31 +455,18 @@ namespace System {
              */
             if(s_CommandLineArgs != null)
                 return (string[])s_CommandLineArgs.Clone();
-#endif
+
             return GetCommandLineArgsNative();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern String[] GetCommandLineArgsNative();
 
-#if !FEATURE_CORECLR
-        // We need to keep this Fcall since it is used in AppDomain.cs.
-        // If we call GetEnvironmentVariable from AppDomain.cs, we will use StringBuilder class.
-        // That has side effect to change the ApartmentState of the calling Thread to MTA.
-        // So runtime can't change the ApartmentState of calling thread any more.
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        internal static extern String nativeGetEnvironmentVariable(String variable);
-#endif //!FEATURE_CORECLR
-
-#if FEATURE_CORECLR
         private static string[] s_CommandLineArgs = null;
         private static void SetCommandLineArgs(string[] cmdLineArgs)
         {
             s_CommandLineArgs = cmdLineArgs;
         }
-#endif
 
         private unsafe static char[] GetEnvironmentCharArray()
         {
@@ -669,7 +521,6 @@ namespace System {
         **Exceptions:  IOException.
         **Permissions: SystemInfo Permission.
         ==============================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String[] GetLogicalDrives() {
             new EnvironmentPermission(PermissionState.Unrestricted).Demand();
                                  
@@ -739,12 +590,10 @@ namespace System {
         **Arguments:
         **Exceptions:
         ==============================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private static extern long GetWorkingSet();
 
         public static long WorkingSet {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 new EnvironmentPermission(PermissionState.Unrestricted).Demand();
                 return GetWorkingSet();
@@ -759,7 +608,6 @@ namespace System {
         **Exceptions:
         ==============================================================================*/
         public static OperatingSystem OSVersion {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 Contract.Ensures(Contract.Result<OperatingSystem>() != null);
 
@@ -783,7 +631,7 @@ namespace System {
                     Version v =  new Version(osvi.MajorVersion, osvi.MinorVersion, osvi.BuildNumber, (osviEx.ServicePackMajor << 16) |osviEx.ServicePackMinor);
                     m_os = new OperatingSystem(id, v, osvi.CSDVersion);
                 }
-                Contract.Assert(m_os != null, "m_os != null");
+                Debug.Assert(m_os != null, "m_os != null");
                 return m_os;
             }
         }
@@ -828,7 +676,6 @@ namespace System {
 
         // Does the current version of Windows have Windows Runtime suppport?
         internal static bool IsWinRTSupported {
-            [SecuritySafeCritical]
             get {
                 if (!s_CheckedWinRT) {
                     s_WinRTSupported = WinRTSupported();
@@ -839,7 +686,6 @@ namespace System {
             }
         }
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
@@ -848,11 +694,9 @@ namespace System {
 
 #endif // FEATURE_CORESYSTEM
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool GetVersion(Microsoft.Win32.Win32Native.OSVERSIONINFO  osVer);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool GetVersionEx(Microsoft.Win32.Win32Native.OSVERSIONINFOEX  osVer);
 
@@ -864,7 +708,6 @@ namespace System {
         **Exceptions:
         ==============================================================================*/
         public static String StackTrace {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 Contract.Ensures(Contract.Result<String>() != null);
 
@@ -873,9 +716,6 @@ namespace System {
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         internal static String GetStackTrace(Exception e, bool needFileInfo)
         {
             // Note: Setting needFileInfo to true will start up COM and set our
@@ -892,7 +732,6 @@ namespace System {
             return st.ToString( System.Diagnostics.StackTrace.TraceFormat.Normal );
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static void InitResourceHelper() {
             // Only the default AppDomain should have a ResourceHelper.  All calls to 
             // GetResourceString from any AppDomain delegate to GetResourceStringLocal 
@@ -917,20 +756,11 @@ namespace System {
             }
         }
 
-#if !FEATURE_CORECLR
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        internal extern static String GetResourceFromDefault(String key);           
-#endif
-
         // Looks up the resource string value for key.
         // 
         // if you change this method's signature then you must change the code that calls it
         // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature
         // as well as metasig.h to create the new signature type
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         // NoInlining causes the caller and callee to not be inlined in mscorlib as it is an assumption of StackCrawlMark use
         [MethodImpl(MethodImplOptions.NoInlining)]
         internal static String GetResourceStringLocal(String key) {
@@ -940,13 +770,8 @@ namespace System {
             return m_resHelper.GetResourceString(key);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static String GetResourceString(String key) {
-#if FEATURE_CORECLR
             return GetResourceStringLocal(key);
-#else
-            return GetResourceFromDefault(key);
-#endif //FEATURE_CORECLR
         }
 
         // The reason the following overloads exist are to reduce code bloat.
@@ -1026,7 +851,6 @@ namespace System {
         }
 
         public static bool Is64BitOperatingSystem {
-            [System.Security.SecuritySafeCritical]
             get {
 #if BIT64
                     // 64-bit programs run only on 64-bit
@@ -1041,20 +865,11 @@ namespace System {
         }
 
         public static extern bool HasShutdownStarted {
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
             get;
         }
 
-#if !FEATURE_CORECLR
-        // This is the temporary Whidbey stub for compatibility flags
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecurityCritical]
-        internal static extern bool GetCompatibilityFlag(CompatibilityFlag flag);
-#endif //!FEATURE_CORECLR
-
         public static string UserName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 new EnvironmentPermission(EnvironmentPermissionAccess.Read,"UserName").Demand();
 
@@ -1068,40 +883,13 @@ namespace System {
             }
         }
 
-        // Note that this is a handle to a process window station, but it does
-        // not need to be closed.  CloseWindowStation would ignore this handle.
-        // We also do handle equality checking as well.  This isn't a great fit
-        // for SafeHandle.  We don't gain anything by using SafeHandle here.
-#if !FEATURE_CORECLR
-        private static volatile IntPtr processWinStation;        // Doesn't need to be initialized as they're zero-init.
-        private static volatile bool isUserNonInteractive;   
-#endif
-
-        public static bool UserInteractive {
-            [System.Security.SecuritySafeCritical]  // auto-generated
+        public static bool UserInteractive
+        {
             get {
-#if !FEATURE_CORECLR
-                IntPtr hwinsta = Win32Native.GetProcessWindowStation();
-                if (hwinsta != IntPtr.Zero && processWinStation != hwinsta) {
-                    int lengthNeeded = 0;
-                    Win32Native.USEROBJECTFLAGS flags = new Win32Native.USEROBJECTFLAGS();
-                    if (Win32Native.GetUserObjectInformation(hwinsta, Win32Native.UOI_FLAGS, flags, Marshal.SizeOf(flags),ref lengthNeeded)) {
-                        if ((flags.dwFlags & Win32Native.WSF_VISIBLE) == 0) {
-                            isUserNonInteractive = true;
-                        }
-                    }
-                    processWinStation = hwinsta;
-                }
-
-                // The logic is reversed to avoid static initialization to true
-                return !isUserNonInteractive;
-#else
                 return true;
-#endif
             }
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static string GetFolderPath(SpecialFolder folder) {
             if (!Enum.IsDefined(typeof(SpecialFolder), folder))
                 throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)folder));
@@ -1110,7 +898,6 @@ namespace System {
             return InternalGetFolderPath(folder, SpecialFolderOption.None);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option) {
             if (!Enum.IsDefined(typeof(SpecialFolder),folder))
                 throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)folder));
@@ -1121,13 +908,11 @@ namespace System {
             return InternalGetFolderPath(folder, option);
         }
 
-        [System.Security.SecurityCritical]
         internal static string UnsafeGetFolderPath(SpecialFolder folder)
         {
             return InternalGetFolderPath(folder, SpecialFolderOption.None, suppressSecurityChecks: true);
         }
 
-        [System.Security.SecurityCritical]
         private static string InternalGetFolderPath(SpecialFolder folder, SpecialFolderOption option, bool suppressSecurityChecks = false)
         {
 #if FEATURE_CORESYSTEM
@@ -1148,13 +933,6 @@ namespace System {
                     throw new PlatformNotSupportedException();
             }
 #else // FEATURE_CORESYSTEM
-#if !FEATURE_CORECLR
-            if (option == SpecialFolderOption.Create && !suppressSecurityChecks) {
-                FileIOPermission createPermission = new FileIOPermission(PermissionState.None);
-                createPermission.AllFiles = FileIOPermissionAccess.Write;
-                createPermission.Demand();
-            }
-#endif
 
             StringBuilder sb = new StringBuilder(Path.MaxPath);
             int hresult = Win32Native.SHGetFolderPath(IntPtr.Zero,                    /* hwndOwner: [in] Reserved */
@@ -1192,14 +970,12 @@ namespace System {
                 // On CoreCLR we can check with the host if we're not trying to use any special options.
                 // Otherwise, we need to do a full demand since hosts aren't expecting to handle requests to
                 // create special folders.
-#if FEATURE_CORECLR
                 if (option == SpecialFolderOption.None)
                 {
                     FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, s);
                     state.EnsureState();
                 }
                 else
-#endif // FEATURE_CORECLR
                 {
                     new FileIOPermission(FileIOPermissionAccess.PathDiscovery, s).Demand();
                 }
@@ -1210,7 +986,6 @@ namespace System {
 
         public static string UserDomainName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 new EnvironmentPermission(EnvironmentPermissionAccess.Read,"UserDomain").Demand();
 
@@ -1343,7 +1118,7 @@ namespace System {
             //          
             // "MyDocuments" is a better name than "Personal"
             //
-            MyDocuments = Win32Native.CSIDL_PERSONAL,                         
+            MyDocuments = Win32Native.CSIDL_PERSONAL,
             //  
             //     Represents the program files folder. 
             //  
@@ -1351,101 +1126,7 @@ namespace System {
             //  
             //     Represents the folder for components that are shared across applications. 
             //  
-            CommonProgramFiles =  Win32Native.CSIDL_PROGRAM_FILES_COMMON,            
-#if !FEATURE_CORECLR
-            //
-            //      <user name>\Start Menu\Programs\Administrative Tools
-            //
-            AdminTools             = Win32Native.CSIDL_ADMINTOOLS,
-            //
-            //      USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
-            //
-            CDBurning              = Win32Native.CSIDL_CDBURN_AREA,
-            //
-            //      All Users\Start Menu\Programs\Administrative Tools
-            //
-            CommonAdminTools       = Win32Native.CSIDL_COMMON_ADMINTOOLS,
-            //
-            //      All Users\Documents
-            //
-            CommonDocuments        = Win32Native.CSIDL_COMMON_DOCUMENTS,
-            //
-            //      All Users\My Music
-            //
-            CommonMusic            = Win32Native.CSIDL_COMMON_MUSIC,
-            //
-            //      Links to All Users OEM specific apps
-            //
-            CommonOemLinks         = Win32Native.CSIDL_COMMON_OEM_LINKS,
-            //
-            //      All Users\My Pictures
-            //
-            CommonPictures         = Win32Native.CSIDL_COMMON_PICTURES,
-            //
-            //      All Users\Start Menu
-            //
-            CommonStartMenu        = Win32Native.CSIDL_COMMON_STARTMENU,
-            //
-            //      All Users\Start Menu\Programs
-            //
-            CommonPrograms         = Win32Native.CSIDL_COMMON_PROGRAMS,
-            //
-            //     All Users\Startup
-            //
-            CommonStartup          = Win32Native.CSIDL_COMMON_STARTUP,
-            //
-            //      All Users\Desktop
-            //
-            CommonDesktopDirectory = Win32Native.CSIDL_COMMON_DESKTOPDIRECTORY,
-            //
-            //      All Users\Templates
-            //
-            CommonTemplates        = Win32Native.CSIDL_COMMON_TEMPLATES,
-            //
-            //      All Users\My Video
-            //
-            CommonVideos           = Win32Native.CSIDL_COMMON_VIDEO,
-            //
-            //      windows\fonts
-            //
-            Fonts                  = Win32Native.CSIDL_FONTS,
-            //
-            //      %APPDATA%\Microsoft\Windows\Network Shortcuts
-            //
-            NetworkShortcuts       = Win32Native.CSIDL_NETHOOD,
-            //
-            //      %APPDATA%\Microsoft\Windows\Printer Shortcuts
-            //
-            PrinterShortcuts       = Win32Native.CSIDL_PRINTHOOD,
-            //
-            //      USERPROFILE
-            //
-            UserProfile            = Win32Native.CSIDL_PROFILE,
-            //
-            //      x86 Program Files\Common on RISC
-            //
-            CommonProgramFilesX86  = Win32Native.CSIDL_PROGRAM_FILES_COMMONX86,
-            //
-            //      x86 C:\Program Files on RISC
-            //
-            ProgramFilesX86        = Win32Native.CSIDL_PROGRAM_FILESX86,
-            //
-            //      Resource Directory
-            //
-            Resources              = Win32Native.CSIDL_RESOURCES,
-            //
-            //      Localized Resource Directory
-            //
-            LocalizedResources     = Win32Native.CSIDL_RESOURCES_LOCALIZED,
-            //
-            //      %windir%\System32 or %windir%\syswow64
-            //
-            SystemX86               = Win32Native.CSIDL_SYSTEMX86,
-            //
-            //      GetWindowsDirectory()
-            //
-            Windows                = Win32Native.CSIDL_WINDOWS,
-#endif // !FEATURE_CORECLR
+            CommonProgramFiles =  Win32Native.CSIDL_PROGRAM_FILES_COMMON,
         }
 
         public static int CurrentManagedThreadId
@@ -1459,7 +1140,6 @@ namespace System {
 
         internal static extern int CurrentProcessorNumber
         {
-            [System.Security.SecuritySafeCritical]
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
             get;
         }
@@ -1606,5 +1286,219 @@ namespace System {
             }
             return results;
         }
+
+        private static string GetEnvironmentVariableCore(string variable)
+        {
+            if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
+            {
+                // Environment variable accessors are not approved modern API.
+                // Behave as if the variable was not found in this case.
+                return null;
+            }
+
+            StringBuilder sb = StringBuilderCache.Acquire(128); // A somewhat reasonable default size
+            int requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
+
+            if (requiredSize == 0 && Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND)
+            {
+                StringBuilderCache.Release(sb);
+                return null;
+            }
+
+            while (requiredSize > sb.Capacity)
+            {
+                sb.Capacity = requiredSize;
+                sb.Length = 0;
+                requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
+            }
+
+            return StringBuilderCache.GetStringAndRelease(sb);
+        }
+
+        private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
+        {
+            if (target == EnvironmentVariableTarget.Process)
+                return GetEnvironmentVariableCore(variable);
+
+#if !FEATURE_WIN32_REGISTRY
+            return null;
+#else
+            RegistryKey baseKey;
+            string keyName;
+
+            if (target == EnvironmentVariableTarget.Machine)
+            {
+                baseKey = Registry.LocalMachine;
+                keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
+            }
+            else if (target == EnvironmentVariableTarget.User)
+            {
+                Debug.Assert(target == EnvironmentVariableTarget.User);
+                baseKey = Registry.CurrentUser;
+                keyName = "Environment";
+            }
+            else
+            {
+                throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
+            }
+
+            using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
+            {
+                return environmentKey?.GetValue(variable) as string;
+            }
+#endif
+        }
+
+        private static IDictionary GetEnvironmentVariablesCore()
+        {
+            if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
+            {
+                // Environment variable accessors are not approved modern API.
+                // Behave as if no environment variables are defined in this case.
+                return new Dictionary<string, string>(0);
+            }
+
+            return GetRawEnvironmentVariables();
+        }
+
+        private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target)
+        {
+            if (target == EnvironmentVariableTarget.Process)
+                return GetEnvironmentVariablesCore();
+
+#if !FEATURE_WIN32_REGISTRY
+            // Without registry support we have nothing to return
+            return new Dictionary<string, string>(0);
+#else
+            RegistryKey baseKey;
+            string keyName;
+            if (target == EnvironmentVariableTarget.Machine)
+            {
+                baseKey = Registry.LocalMachine;
+                keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
+            }
+            else if (target == EnvironmentVariableTarget.User)
+            {
+                Debug.Assert(target == EnvironmentVariableTarget.User);
+                baseKey = Registry.CurrentUser;
+                keyName = @"Environment";
+            }
+            else
+            {
+                throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
+            }
+
+            using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
+            {
+                var table = new Dictionary<string, string>();
+                if (environmentKey != null)
+                {
+                    foreach (string name in environmentKey.GetValueNames())
+                    {
+                        table.Add(name, environmentKey.GetValue(name, "").ToString());
+                    }
+                }
+                return table;
+            }
+#endif // FEATURE_WIN32_REGISTRY
+        }
+
+        private static void SetEnvironmentVariableCore(string variable, string value)
+        {
+            // explicitly null out value if is the empty string.
+            if (string.IsNullOrEmpty(value) || value[0] == '\0')
+                value = null;
+
+            if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
+            {
+                // Environment variable accessors are not approved modern API.
+                // so we throw PlatformNotSupportedException.
+                throw new PlatformNotSupportedException();
+            }
+
+            if (!Win32Native.SetEnvironmentVariable(variable, value))
+            {
+                int errorCode = Marshal.GetLastWin32Error();
+
+                switch (errorCode)
+                {
+                    case Win32Native.ERROR_ENVVAR_NOT_FOUND:
+                        // Allow user to try to clear a environment variable
+                        return;
+                    case Win32Native.ERROR_FILENAME_EXCED_RANGE:
+                        // The error message from Win32 is "The filename or extension is too long",
+                        // which is not accurate.
+                        throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"));
+                    default:
+                        throw new ArgumentException(Win32Native.GetMessage(errorCode));
+                }
+            }
+        }
+
+        private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
+        {
+            if (target == EnvironmentVariableTarget.Process)
+            {
+                SetEnvironmentVariableCore(variable, value);
+                return;
+            }
+
+#if !FEATURE_WIN32_REGISTRY
+            // other targets ignored
+            return;
+#else
+            // explicitly null out value if is the empty string.
+            if (string.IsNullOrEmpty(value) || value[0] == '\0')
+                value = null;
+
+            RegistryKey baseKey;
+            string keyName;
+
+            if (target == EnvironmentVariableTarget.Machine)
+            {
+                baseKey = Registry.LocalMachine;
+                keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
+            }
+            else if (target == EnvironmentVariableTarget.User)
+            {
+                Debug.Assert(target == EnvironmentVariableTarget.User);
+
+                // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name.
+                const int MaxUserEnvVariableLength = 255;
+                if (variable.Length >= MaxUserEnvVariableLength)
+                {
+                    throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable));
+                }
+
+                baseKey = Registry.CurrentUser;
+                keyName = "Environment";
+            }
+            else
+            {
+                throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
+            }
+
+            using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true))
+            {
+                if (environmentKey != null)
+                {
+                    if (value == null)
+                    {
+                        environmentKey.DeleteValue(variable, throwOnMissingValue: false);
+                    }
+                    else
+                    {
+                        environmentKey.SetValue(variable, value);
+                    }
+                }
+            }
+
+            // send a WM_SETTINGCHANGE message to all windows
+            IntPtr r = Win32Native.SendMessageTimeout(new IntPtr(Win32Native.HWND_BROADCAST),
+                Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
+
+            if (r == IntPtr.Zero) Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
+#endif // FEATURE_WIN32_REGISTRY
+        }
     }
 }
index 07e34c2..a8ee328 100644 (file)
@@ -73,7 +73,6 @@ namespace System {
             _innerException = innerException;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected Exception(SerializationInfo info, StreamingContext context) 
         {
             if (info==null)
@@ -143,7 +142,6 @@ namespace System {
         }
 
         public virtual IDictionary Data { 
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 if (_data == null)
                     if (IsImmutableAgileException(this))
@@ -155,7 +153,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool IsImmutableAgileException(Exception e);
 
@@ -260,11 +257,9 @@ namespace System {
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static extern private IRuntimeMethodInfo GetMethodFromStackTrace(Object stackTrace);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private MethodBase GetExceptionMethodFromStackTrace()
         {
             IRuntimeMethodInfo method = GetMethodFromStackTrace(_stackTrace);
@@ -277,7 +272,6 @@ namespace System {
         }
     
         public MethodBase TargetSite {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return GetTargetSiteInternal();
             }
@@ -285,7 +279,6 @@ namespace System {
     
 
         // this function is provided as a private helper to avoid the security demand
-        [System.Security.SecurityCritical]  // auto-generated
         private MethodBase GetTargetSiteInternal() {
             if (_exceptionMethod!=null) {
                 return _exceptionMethod;
@@ -306,9 +299,6 @@ namespace System {
         // available, null is returned.
         public virtual String StackTrace
         {
-#if FEATURE_CORECLR
-            [System.Security.SecuritySafeCritical] 
-#endif
             get 
             {
                 // By default attempt to include file and line number info
@@ -321,24 +311,11 @@ namespace System {
         // is true.  Note that this requires FileIOPermission(PathDiscovery), and so
         // will usually fail in CoreCLR.  To avoid the demand and resulting
         // SecurityException we can explicitly not even try to get fileinfo.
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         private string GetStackTrace(bool needFileInfo)
         {
             string stackTraceString = _stackTraceString;
             string remoteStackTraceString = _remoteStackTraceString;
 
-#if !FEATURE_CORECLR
-            if (!needFileInfo)
-            {
-                // Filter out file names/paths and line numbers from _stackTraceString and _remoteStackTraceString.
-                // This is used only when generating stack trace for Watson where the strings must be PII-free.
-                stackTraceString = StripFileInfo(stackTraceString, false);
-                remoteStackTraceString = StripFileInfo(remoteStackTraceString, true);
-            }
-#endif // !FEATURE_CORECLR
-
             // if no stack trace, try to get one
             if (stackTraceString != null)
             {
@@ -380,9 +357,6 @@ namespace System {
         }
     
         public virtual String Source {
-#if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-#endif
             get { 
                 if (_source == null)
                 {
@@ -411,23 +385,14 @@ namespace System {
 
                 return _source;
             }
-#if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-#endif
             set { _source = value; }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] 
-#endif
         public override String ToString()
         {
             return ToString(true, true);
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         private String ToString(bool needFileLineInfo, bool needMessage) {
             String message = (needMessage ? Message : null);
             String s;
@@ -454,7 +419,6 @@ namespace System {
             return s;
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         private String GetExceptionMethodString() {
             MethodBase methBase = GetTargetSiteInternal();
             if (methBase==null) {
@@ -487,7 +451,7 @@ namespace System {
                 result.Append(separator);
                 result.Append(rci.ToString());
             } else {
-                Contract.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
+                Debug.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
                 RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase;
                 Type t = rmi.DeclaringType;
                 result.Append((int)MemberTypes.Method);
@@ -507,9 +471,8 @@ namespace System {
             return result.ToString();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private MethodBase GetExceptionMethodFromString() {
-            Contract.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
+            Debug.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
             String[] args = _exceptionMethodString.Split(new char[]{'\0', '\n'});
             if (args.Length!=5) {
                 throw new SerializationException();
@@ -544,7 +507,6 @@ namespace System {
         }
 #endif // FEATURE_SERIALIZATION
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context) 
         {
             if (info == null)
@@ -597,7 +559,7 @@ namespace System {
                 // often created in the VM with AllocateObject instead if the managed construtor)
                 // If you are adding code to use a SafeSerializationManager from an mscorlib exception, update
                 // this assert to ensure that it fails when that exception's _safeSerializationManager is NULL 
-                Contract.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)), 
+                Debug.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)), 
                                 "User defined exceptions must have a valid _safeSerializationManager");
             
                 // Handle serializing any transparent or partial trust subclass data
@@ -662,9 +624,6 @@ namespace System {
 
         // This is used by the runtime when re-throwing a managed exception.  It will
         //  copy the stack trace to _remoteStackTraceString.
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] 
-#endif
         internal void InternalPreserveStackTrace()
         {
             string tmpStackTraceString;
@@ -737,33 +696,21 @@ namespace System {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void PrepareForForeignExceptionRaise();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void GetStackTracesDeepCopy(Exception exception, out object currentStackTrace, out object dynamicMethodArray);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void SaveStackTracesFromDeepCopy(Exception exception, object currentStackTrace, object dynamicMethodArray);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern object CopyStackTrace(object currentStackTrace);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern object CopyDynamicMethods(object currentDynamicMethods);
 
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private extern string StripFileInfo(string stackTrace, bool isRemoteStackTrace);
-#endif // !FEATURE_CORECLR
-
-        [SecuritySafeCritical]
         internal object DeepCopyStackTrace(object currentStackTrace)
         {
             if (currentStackTrace != null)
@@ -776,7 +723,6 @@ namespace System {
             }
         }
 
-        [SecuritySafeCritical]
         internal object DeepCopyDynamicMethods(object currentDynamicMethods)
         {
             if (currentDynamicMethods != null)
@@ -789,7 +735,6 @@ namespace System {
             }
         }
         
-        [SecuritySafeCritical]
         internal void GetStackTracesDeepCopy(out object currentStackTrace, out object dynamicMethodArray)
         {
             GetStackTracesDeepCopy(this, out currentStackTrace, out dynamicMethodArray);
@@ -797,7 +742,6 @@ namespace System {
 
         // This is invoked by ExceptionDispatchInfo.Throw to restore the exception stack trace, corresponding to the original throw of the
         // exception, just before the exception is "rethrown".
-        [SecuritySafeCritical]
         internal void RestoreExceptionDispatchInfo(System.Runtime.ExceptionServices.ExceptionDispatchInfo exceptionDispatchInfo)
         {
             bool fCanProcessException = !(IsImmutableAgileException(this));
@@ -900,7 +844,6 @@ namespace System {
 
         // InternalToString is called by the runtime to get the exception text 
         // and create a corresponding CrossAppDomainMarshaledException
-        [System.Security.SecurityCritical]  // auto-generated
         internal virtual String InternalToString()
         {
             try 
@@ -929,13 +872,11 @@ namespace System {
 
         internal bool IsTransient
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return nIsTransient(_HResult);
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static bool nIsTransient(int hr);
 
@@ -957,7 +898,6 @@ namespace System {
         }
 
         // See comment on ExceptionMessageKind
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static String GetMessageFromNativeResources(ExceptionMessageKind kind)
         {
             string retMesg = null;
@@ -965,16 +905,11 @@ namespace System {
             return retMesg;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetMessageFromNativeResources(ExceptionMessageKind kind, StringHandleOnStack retMesg);
     }
 
-
-
-#if FEATURE_CORECLR
-
     //--------------------------------------------------------------------------
     // Telesto: Telesto doesn't support appdomain marshaling of objects so
     // managed exceptions that leak across appdomain boundaries are flatted to
@@ -996,17 +931,10 @@ namespace System {
         // Normally, only Telesto's UEF will see these exceptions.
         // This override prints out the original Exception's ToString()
         // output and hides the fact that it is wrapped inside another excepton.
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         internal override String InternalToString()
         {
             return Message;
         }
-    
     }
-#endif
-
-
 }
 
index 93c3bbd..e338e44 100644 (file)
@@ -63,68 +63,53 @@ namespace System {
 
     public static class GC 
     {
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int GetGCLatencyMode();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int SetGCLatencyMode(int newLatencyMode);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal static extern int _StartNoGCRegion(long totalSize, bool lohSizeKnown, long lohSize, bool disallowFullBlockingGC);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal static extern int _EndNoGCRegion();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int GetLOHCompactionMode();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void SetLOHCompactionMode(int newLOHCompactionMode);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int GetGenerationWR(IntPtr handle);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern long GetTotalMemory();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void _Collect(int generation, int mode);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int GetMaxGeneration();
     
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private static extern int _CollectionCount (int generation, int getSpecialGCCount);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool IsServerGC();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private static extern void _AddMemoryPressure(UInt64 bytesAllocated);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private static extern void _RemoveMemoryPressure(UInt64 bytesAllocated);
         
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void AddMemoryPressure (long bytesAllocated) {
             if( bytesAllocated <= 0) {
                 throw new ArgumentOutOfRangeException(nameof(bytesAllocated), 
@@ -140,7 +125,6 @@ namespace System {
             _AddMemoryPressure((ulong)bytesAllocated);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void RemoveMemoryPressure (long bytesAllocated) {
             if( bytesAllocated <= 0) {
                 throw new ArgumentOutOfRangeException(nameof(bytesAllocated), 
@@ -159,7 +143,6 @@ namespace System {
 
         // Returns the generation that obj is currently in.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern int GetGeneration(Object obj);
 
@@ -172,25 +155,21 @@ namespace System {
     
         // Garbage Collect all generations.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void Collect() {
             //-1 says to GC all generations.
             _Collect(-1, (int)InternalGCCollectionMode.Blocking);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void Collect(int generation, GCCollectionMode mode) 
         {
             Collect(generation, mode, true);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void Collect(int generation, GCCollectionMode mode, bool blocking) 
         {
             Collect(generation, mode, blocking, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting)
         {
             if (generation<0) 
@@ -227,7 +206,6 @@ namespace System {
             _Collect(generation, iInternalModes);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static int CollectionCount (int generation) 
         {
@@ -240,7 +218,6 @@ namespace System {
         }
 
         // pass in true to get the BGC or FGC count.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal static int CollectionCount (int generation, bool getSpecialGCCount) 
         {
@@ -295,7 +272,6 @@ namespace System {
 
         // Returns the generation in which wo currently resides.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static int GetGeneration(WeakReference wo) {
             int result = GetGenerationWR(wo.m_handle);
             KeepAlive(wo);
@@ -305,16 +281,13 @@ namespace System {
         // Returns the maximum GC generation.  Currently assumes only 1 heap.
         //
         public static int MaxGeneration {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return GetMaxGeneration(); }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void _WaitForPendingFinalizers();
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void WaitForPendingFinalizers() {
             // QCalls can not be exposed from mscorlib directly, need to wrap it.
             _WaitForPendingFinalizers();
@@ -322,12 +295,10 @@ namespace System {
     
         // Indicates that the system should not call the Finalize() method on
         // an object that would normally require this call.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private static extern void _SuppressFinalize(Object o);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static void SuppressFinalize(Object obj) {
             if (obj == null)
@@ -340,11 +311,9 @@ namespace System {
         // for which SuppressFinalize has already been called. The other situation 
         // where calling ReRegisterForFinalize is useful is inside a finalizer that 
         // needs to resurrect itself or an object that it references.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _ReRegisterForFinalize(Object o);
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void ReRegisterForFinalize(Object obj) {
             if (obj == null)
                 throw new ArgumentNullException(nameof(obj));
@@ -356,7 +325,6 @@ namespace System {
         // the GC heap.  This does not return the total size of the GC heap, but
         // only the live objects in the GC heap.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static long GetTotalMemory(bool forceFullCollection) {
             long size = GetTotalMemory();
             if (!forceFullCollection)
@@ -379,16 +347,13 @@ namespace System {
             return newSize;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern long _GetAllocatedBytesForCurrentThread();
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static long GetAllocatedBytesForCurrentThread() {
             return _GetAllocatedBytesForCurrentThread();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool _RegisterForFullGCNotification(int maxGenerationPercentage, int largeObjectHeapPercentage);
 
@@ -401,7 +366,6 @@ namespace System {
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int _WaitForFullGCComplete(int millisecondsTimeout);
 
-        [SecurityCritical]
         public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold)
         {
             if ((maxGenerationThreshold <= 0) || (maxGenerationThreshold >= 100))
@@ -430,7 +394,6 @@ namespace System {
             }
         }
 
-        [SecurityCritical]
         public static void CancelFullGCNotification()
         {
             if (!_CancelFullGCNotification())
@@ -439,13 +402,11 @@ namespace System {
             }
         }
 
-        [SecurityCritical]
         public static GCNotificationStatus WaitForFullGCApproach()
         {
             return (GCNotificationStatus)_WaitForFullGCApproach(-1);
         }
 
-        [SecurityCritical]
         public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout)
         {
             if (millisecondsTimeout < -1)
@@ -454,13 +415,11 @@ namespace System {
             return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout);
         }
 
-        [SecurityCritical]
         public static GCNotificationStatus WaitForFullGCComplete()
         {
             return (GCNotificationStatus)_WaitForFullGCComplete(-1);
         }
 
-        [SecurityCritical]
         public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout)
         {
             if (millisecondsTimeout < -1)
@@ -484,7 +443,6 @@ namespace System {
             AllocationExceeded = 3
         }
 
-        [SecurityCritical]
         static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
         {
             StartNoGCRegionStatus status = (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
@@ -498,31 +456,26 @@ namespace System {
             return true;
         }
 
-        [SecurityCritical]
         public static bool TryStartNoGCRegion(long totalSize)
         {
             return StartNoGCRegionWorker(totalSize, false, 0, false);
         }
 
-        [SecurityCritical]
         public static bool TryStartNoGCRegion(long totalSize, long lohSize)
         {
             return StartNoGCRegionWorker(totalSize, true, lohSize, false);
         }
 
-        [SecurityCritical]
         public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC)
         {
             return StartNoGCRegionWorker(totalSize, false, 0, disallowFullBlockingGC);
         }
 
-        [SecurityCritical]
         public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC)
         {
             return StartNoGCRegionWorker(totalSize, true, lohSize, disallowFullBlockingGC);
         }
 
-        [SecurityCritical]
         static EndNoGCRegionStatus EndNoGCRegionWorker()
         {
             EndNoGCRegionStatus status = (EndNoGCRegionStatus)_EndNoGCRegion();
@@ -536,106 +489,9 @@ namespace System {
             return EndNoGCRegionStatus.Succeeded;
         }
 
-        [SecurityCritical]
         public static void EndNoGCRegion()
         {
             EndNoGCRegionWorker();
         }
     }
-
-#if !FEATURE_CORECLR
-    internal class SizedReference : IDisposable
-    {
-        [System.Security.SecurityCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern IntPtr CreateSizedRef(Object o);
-
-        [System.Security.SecurityCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern void FreeSizedRef(IntPtr h);
-
-        [System.Security.SecurityCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern Object GetTargetOfSizedRef(IntPtr h);
-
-        [System.Security.SecurityCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern Int64 GetApproximateSizeOfSizedRef(IntPtr h);
-
-        #pragma warning disable 420
-        [System.Security.SecuritySafeCritical]
-        private void Free()
-        {
-            IntPtr temp = _handle;
-            if (temp != IntPtr.Zero && 
-                (Interlocked.CompareExchange(ref _handle, IntPtr.Zero, temp) == temp))
-            {
-                FreeSizedRef(temp);
-            }
-        }
-
-        internal volatile IntPtr _handle;
-
-        [System.Security.SecuritySafeCritical]
-        public SizedReference(Object target)
-        {
-            IntPtr temp = IntPtr.Zero;
-            temp = CreateSizedRef(target);
-            _handle = temp;
-        }
-
-        ~SizedReference()
-        {
-            Free();
-        }
-
-        public Object Target
-        {
-            [System.Security.SecuritySafeCritical]
-            get 
-            {
-                IntPtr temp = _handle; 
-                if (temp == IntPtr.Zero)
-                {
-                    return null;
-                }
-
-                Object o = GetTargetOfSizedRef(temp);
-
-                return (_handle == IntPtr.Zero) ? null : o;
-            }
-        }
-
-        public Int64 ApproximateSize
-        {
-            [System.Security.SecuritySafeCritical]
-            get 
-            {
-                IntPtr temp = _handle; 
-                
-                if (temp == IntPtr.Zero)
-                {
-                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized"));
-                }
-
-                Int64 size = GetApproximateSizeOfSizedRef(temp);
-
-                if (_handle == IntPtr.Zero)
-                {
-                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized"));
-                }
-                else
-                {
-                    return size;
-                }
-            }
-        }
-
-        public void Dispose()
-        {
-            Free();
-            GC.SuppressFinalize(this);
-        }
-    }
-#endif
 }
index a79a232..d046038 100644 (file)
@@ -7,6 +7,7 @@ namespace System.Globalization {
     using System.Runtime.CompilerServices;
     using System.Globalization;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // This abstract class represents a calendar. A calendar reckons time in
@@ -229,7 +230,7 @@ namespace System.Globalization {
             get {
                 // The following code assumes that the current era value can not be -1.
                 if (m_currentEraValue == -1) {
-                    Contract.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
+                    Debug.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
                     m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
                 }
                 return (m_currentEraValue);
@@ -529,7 +530,7 @@ namespace System.Globalization {
             // this value can be less than 0.  It's fine since we are making it positive again in calculating offset.
             int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
             int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
-            Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
+            Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
             return ((dayOfYear + offset) / 7 + 1);
         }
 
@@ -845,7 +846,6 @@ namespace System.Globalization {
             throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static int GetSystemTwoDigitYearSetting(int CalID, int defaultYearValue)
         {
             // Call nativeGetTwoDigitYearMax
index 8c187f0..6f583fb 100644 (file)
@@ -9,6 +9,7 @@ namespace System.Globalization
     using System.Runtime.InteropServices;    
     using System.Runtime.CompilerServices;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     //
     // List of calendar data
@@ -121,7 +122,7 @@ namespace System.Globalization
             this.bUseUserOverrides = bUseUserOverrides;
             if (!nativeGetCalendarData(this, localeName, calendarId))
             {
-                Contract.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
+                Debug.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
                 
                 // Something failed, try invariant for missing parts
                 // This is really not good, but we don't want the callers to crash.
@@ -436,17 +437,14 @@ namespace System.Globalization
 
         
         // Get native two digit year max
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int nativeGetTwoDigitYearMax(int calID);
 
         // Call native side to load our calendar data
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool nativeGetCalendarData(CalendarData data, String localeName, int calendar);
 
         // Call native side to figure out which calendars are allowed
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int nativeGetCalendars(String localeName, bool useUserOverride, [In, Out] int[] calendars);
 
index 7084511..1113cd5 100644 (file)
@@ -5,6 +5,7 @@
 namespace System.Globalization
 {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     internal class CalendricalCalculationsHelper
@@ -153,7 +154,7 @@ namespace System.Globalization
         // the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges
         static double DefaultEphemerisCorrection(int gregorianYear)
         {
-            Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
+            Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
             long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
             double daysSinceStartOf1810 = january1stOfYear - StartOf1810;
             double x = TwelveHours + daysSinceStartOf1810;
@@ -162,34 +163,34 @@ namespace System.Globalization
 
         static double EphemerisCorrection1988to2019(int gregorianYear)
         {
-            Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
+            Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
             return (double)(gregorianYear - 1933) / SecondsPerDay;
         }
 
         static double EphemerisCorrection1900to1987(int gregorianYear)
         {
-            Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
+            Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
             double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
             return PolynomialSum(Coefficients1900to1987, centuriesFrom1900);
         }
 
         static double EphemerisCorrection1800to1899(int gregorianYear)
         {
-            Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
+            Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
             double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
             return PolynomialSum(Coefficients1800to1899, centuriesFrom1900);
         }
 
         static double EphemerisCorrection1700to1799(int gregorianYear)
         {
-            Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
+            Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
             double yearsSince1700 = gregorianYear - 1700;
             return PolynomialSum(Coefficients1700to1799, yearsSince1700) / SecondsPerDay;
         }
 
         static double EphemerisCorrection1620to1699(int gregorianYear)
         {
-            Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
+            Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
             double yearsSince1600 = gregorianYear - 1600;
             return PolynomialSum(Coefficients1620to1699, yearsSince1600) / SecondsPerDay;
         }
@@ -216,7 +217,7 @@ namespace System.Globalization
                 }
             }
 
-            Contract.Assert(false, "Not expected to come here");
+            Debug.Assert(false, "Not expected to come here");
             return DefaultEphemerisCorrection(year);
         }
 
@@ -405,7 +406,7 @@ namespace System.Globalization
                     break;
                 }
             }
-            Contract.Assert(day != upperBoundNewYearDay);
+            Debug.Assert(day != upperBoundNewYearDay);
 
             return day - 1;
         }
index 04c1065..2822b41 100644 (file)
@@ -23,6 +23,7 @@ namespace System.Globalization {
     using System.Runtime.Versioning;
     using System.Reflection;
     using System.Security;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
 
@@ -46,14 +47,11 @@ namespace System.Globalization {
         static bool s_initialized = InitTable();
 
         // The native pointer to the 12:4:4 index table of the Unicode cateogry data.
-        [SecurityCritical]
         unsafe static ushort* s_pCategoryLevel1Index;
-        [SecurityCritical]
         unsafe static byte* s_pCategoriesValue;
 
         // The native pointer to the 12:4:4 index table of the Unicode numeric data.
         // The value of this index table is an index into the real value table stored in s_pNumericValues.
-        [SecurityCritical]
         unsafe static ushort* s_pNumericLevel1Index;
 
         // The numeric value table, which is indexed by s_pNumericLevel1Index.
@@ -61,12 +59,10 @@ namespace System.Globalization {
         // unsafe static double* s_pNumericValues;
         // To get around the IA64 alignment issue.  Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting
         // at 4-byte boundary.  This cause a alignment issue since double is 8-byte.
-        [SecurityCritical]
         unsafe static byte* s_pNumericValues;
 
         // The digit value table, which is indexed by s_pNumericLevel1Index.  It shares the same indice as s_pNumericValues.
         // Every item contains the value for decimal digit/digit value.
-        [SecurityCritical]
         unsafe static DigitValues* s_pDigitValues;
 
         internal const String UNICODE_INFO_FILE_NAME = "charinfo.nlp";
@@ -111,7 +107,6 @@ namespace System.Globalization {
         //use.  We allocate this once in the class initializer and then we don't need to worry
         //about it again.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe static bool InitTable() {
 
             // Go to native side and get pointer to the native table
@@ -143,8 +138,8 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
 
         internal static int InternalConvertToUtf32(String s, int index) {
-            Contract.Assert(s != null, "s != null");
-            Contract.Assert(index >= 0 && index < s.Length, "index < s.Length");
+            Debug.Assert(s != null, "s != null");
+            Debug.Assert(index >= 0 && index < s.Length, "index < s.Length");
             if (index < s.Length - 1) {
                 int temp1 = (int)s[index] - HIGH_SURROGATE_START;
                 if (temp1 >= 0 && temp1 <= 0x3ff) {
@@ -181,9 +176,9 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
 
         internal static int InternalConvertToUtf32(String s, int index, out int charLength) {
-            Contract.Assert(s != null, "s != null");
-            Contract.Assert(s.Length > 0, "s.Length > 0");
-            Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+            Debug.Assert(s != null, "s != null");
+            Debug.Assert(s.Length > 0, "s.Length > 0");
+            Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
             charLength = 1;
             if (index < s.Length - 1) {
                 int temp1 = (int)s[index] - HIGH_SURROGATE_START;
@@ -209,8 +204,8 @@ namespace System.Globalization {
 
         internal static bool IsWhiteSpace(String s, int index)
         {
-            Contract.Assert(s != null, "s!=null");
-            Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+            Debug.Assert(s != null, "s!=null");
+            Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
 
             UnicodeCategory uc = GetUnicodeCategory(s, index);
             // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
@@ -245,9 +240,8 @@ namespace System.Globalization {
         //
         // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static double InternalGetNumericValue(int ch) {
-            Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+            Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
             // Get the level 2 item from the highest 12 bit (8 - 19) of ch.
             ushort index = s_pNumericLevel1Index[ch >> 8];
             // Get the level 2 WORD offset from the 4 - 7 bit of ch.  This provides the base offset of the level 3 table.
@@ -278,9 +272,8 @@ namespace System.Globalization {
         //
         // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
         //        
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static DigitValues* InternalGetDigitValues(int ch) {
-            Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+            Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
             // Get the level 2 item from the highest 12 bit (8 - 19) of ch.
             ushort index = s_pNumericLevel1Index[ch >> 8];
             // Get the level 2 WORD offset from the 4 - 7 bit of ch.  This provides the base offset of the level 3 table.
@@ -292,12 +285,10 @@ namespace System.Globalization {
             return &(s_pDigitValues[pBytePtr[(ch & 0x000f)]]);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static sbyte InternalGetDecimalDigitValue(int ch) {
             return (InternalGetDigitValues(ch)->decimalDigit);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static sbyte InternalGetDigitValue(int ch) {
             return (InternalGetDigitValues(ch)->digit);
         }
@@ -441,9 +432,8 @@ namespace System.Globalization {
         //
         ////////////////////////////////////////////////////////////////////////
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static byte InternalGetCategoryValue(int ch, int offset) {
-            Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+            Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
             // Get the level 2 item from the highest 12 bit (8 - 19) of ch.
             ushort index = s_pCategoryLevel1Index[ch >> 8];
             // Get the level 2 WORD offset from the 4 - 7 bit of ch.  This provides the base offset of the level 3 table.
@@ -457,7 +447,7 @@ namespace System.Globalization {
             // Make sure that OtherNotAssigned is the last category in UnicodeCategory.
             // If that changes, change the following assertion as well.
             //
-            //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
+            //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
             return (uc);
         }
 
@@ -489,8 +479,8 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
 
         internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) {
-            Contract.Assert(value != null, "value can not be null");
-            Contract.Assert(index < value.Length, "index < value.Length");
+            Debug.Assert(value != null, "value can not be null");
+            Debug.Assert(index < value.Length, "index < value.Length");
 
             return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
         }
@@ -503,15 +493,15 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
 
         internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) {
-            Contract.Assert(str != null, "str can not be null");
-            Contract.Assert(str.Length > 0, "str.Length > 0");;
-            Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
+            Debug.Assert(str != null, "str can not be null");
+            Debug.Assert(str.Length > 0, "str.Length > 0");;
+            Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
 
             return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
         }
 
         internal static bool IsCombiningCategory(UnicodeCategory uc) {
-            Contract.Assert(uc >= 0, "uc >= 0");
+            Debug.Assert(uc >= 0, "uc >= 0");
             return (
                 uc == UnicodeCategory.NonSpacingMark ||
                 uc == UnicodeCategory.SpacingCombiningMark ||
index 9da4a6b..dcf1f32 100644 (file)
@@ -32,6 +32,7 @@ namespace System.Globalization {
     using System.Security.Permissions;
     using Microsoft.Win32;
     using System.Security;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     //
@@ -221,7 +222,6 @@ namespace System.Globalization {
             return(IsSortable(ch.ToString()));
         }
 
-        [System.Security.SecuritySafeCritical]
         [System.Runtime.InteropServices.ComVisible(false)]
         public static bool IsSortable(String text) {
             if (text == null) {
@@ -291,7 +291,7 @@ namespace System.Globalization {
 #if FEATURE_USE_LCID
             // This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more.
             culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort)
-            Contract.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
+            Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
 #endif
         }
 
@@ -321,14 +321,7 @@ namespace System.Globalization {
         {
             get
             {
-                Contract.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set");
-#if !FEATURE_CORECLR
-                if (m_name == "zh-CHT" || m_name == "zh-CHS")
-                {
-                    return m_name;
-                }
-#endif // FEATURE_CORECLR
-
+                Debug.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set");
                 return (m_sortName);
             }
         }
@@ -354,7 +347,7 @@ namespace System.Globalization {
             // some NLS VM functions can handle COMPARE_OPTIONS_ORDINAL
             // in which case options should be simply cast to int instead of using this function
             // Does not look like the best approach to me but for now I am going to leave it as it is
-            Contract.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately");
+            Debug.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately");
 
             // Use "linguistic casing" by default (load the culture's casing exception tables)
             int nativeCompareFlags = NORM_LINGUISTIC_CASING;
@@ -369,7 +362,7 @@ namespace System.Globalization {
             // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
             if (options == CompareOptions.Ordinal)                { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
 
-            Contract.Assert(((options & ~(CompareOptions.IgnoreCase |
+            Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
                                           CompareOptions.IgnoreKanaType |
                                           CompareOptions.IgnoreNonSpace |
                                           CompareOptions.IgnoreSymbols |
@@ -377,7 +370,7 @@ namespace System.Globalization {
                                           CompareOptions.StringSort)) == 0) ||
                              (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
 
-            Contract.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here");
+            Debug.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here");
 
             return nativeCompareFlags;
         }
@@ -400,7 +393,6 @@ namespace System.Globalization {
             return (Compare(string1, string2, CompareOptions.None));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual int Compare(String string1, String string2, CompareOptions options){
 
             if (options == CompareOptions.OrdinalIgnoreCase)
@@ -471,7 +463,6 @@ namespace System.Globalization {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2, CompareOptions options)
         {
             if (options == CompareOptions.OrdinalIgnoreCase)
@@ -548,7 +539,6 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual bool IsPrefix(String source, String prefix, CompareOptions options)
         {
             if (source == null || prefix == null) {
@@ -603,7 +593,6 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual bool IsSuffix(String source, String suffix, CompareOptions options)
         {
             if (source == null || suffix == null) {
@@ -749,7 +738,6 @@ namespace System.Globalization {
             return IndexOf(source, value, startIndex, count, CompareOptions.None);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual int IndexOf(String source, char value, int startIndex, int count, CompareOptions options)
         {
             // Validate inputs
@@ -782,7 +770,6 @@ namespace System.Globalization {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual int IndexOf(String source, String value, int startIndex, int count, CompareOptions options)
         {
             // Validate inputs
@@ -931,7 +918,6 @@ namespace System.Globalization {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count, CompareOptions options)
         {
             // Verify Arguments
@@ -980,7 +966,6 @@ namespace System.Globalization {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count, CompareOptions options)
         {
             // Verify Arguments
@@ -1053,7 +1038,6 @@ namespace System.Globalization {
             return CreateSortKey(source, CompareOptions.None);
         }
 
-        [System.Security.SecuritySafeCritical]
         private SortKey CreateSortKey(String source, CompareOptions options)
         {
             if (source==null) { throw new ArgumentNullException(nameof(source)); }
@@ -1209,7 +1193,6 @@ namespace System.Globalization {
             return GetHashCodeOfString(source, options, false, 0);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal int GetHashCodeOfString(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
         {
             //
@@ -1261,40 +1244,16 @@ namespace System.Globalization {
         }
 #endif
 
-        [System.Security.SecuritySafeCritical]
         internal static IntPtr InternalInitSortHandle(String localeName, out IntPtr handleOrigin)
         {
             return NativeInternalInitSortHandle(localeName, out handleOrigin);
         }
 
-#if !FEATURE_CORECLR
-        private const int SORT_VERSION_WHIDBEY = 0x00001000;
-        private const int SORT_VERSION_V4 = 0x00060101;
-
-        internal static bool IsLegacy20SortingBehaviorRequested
-        {
-            get
-            {
-                return InternalSortVersion == SORT_VERSION_WHIDBEY;
-            }
-        }
-
-        private static uint InternalSortVersion
-        {
-            [System.Security.SecuritySafeCritical]
-            get
-            {
-                return InternalGetSortVersion();
-            }
-        }
-#endif
-
         [OptionalField(VersionAdded = 3)]
         private SortVersion m_SortVersion;
 
         public SortVersion Version
         {
-            [SecuritySafeCritical]
             get
             {
                 if(m_SortVersion == null) 
@@ -1309,39 +1268,27 @@ namespace System.Globalization {
             }
         }
         
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool InternalGetNlsVersionEx(IntPtr handle, IntPtr handleOrigin, String localeName, ref Win32Native.NlsVersionInfoEx lpNlsVersionInformation);
 
-#if !FEATURE_CORECLR
-        [System.Security.SecurityCritical]
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SuppressUnmanagedCodeSecurity]
-        private static extern uint InternalGetSortVersion();
-
-#endif
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern IntPtr NativeInternalInitSortHandle(String localeName, out IntPtr handleOrigin);
 
         // Get a locale sensitive sort hash code from native code -- COMNlsInfo::InternalGetGlobalizedHashCode
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern int InternalGetGlobalizedHashCode(IntPtr handle, IntPtr handleOrigin, string localeName, string source, int length, int dwFlags, bool forceRandomizedHashing, long additionalEntropy);
 
         // Use native API calls to see if this string is entirely defined -- COMNlsInfo::InternalIsSortable
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool InternalIsSortable(IntPtr handle, IntPtr handleOrigin, String localeName, String source, int length);
 
         // Compare a string using the native API calls -- COMNlsInfo::InternalCompareString
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern int InternalCompareString(IntPtr handle, IntPtr handleOrigin, String localeName, String string1, int offset1, int length1,
@@ -1349,13 +1296,11 @@ namespace System.Globalization {
 
         // InternalFindNLSStringEx parameters is not exactly matching kernel32::FindNLSStringEx parameters.
         // Call through to NewApis::FindNLSStringEx so we can get the right behavior
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern int InternalFindNLSStringEx(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, int startIndex, string target, int targetCount);
 
         // Call through to NewAPis::LCMapStringEx so we can get appropriate behavior for all platforms
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern int InternalGetSortKey(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, byte[] target, int targetCount);
index 7b56ba4..0bcb796 100644 (file)
@@ -10,13 +10,10 @@ namespace System.Globalization
     using System.Collections.Generic;
     using System.Text;
     using System.Threading;
-#if !FEATURE_CORECLR
-    using System.Reflection;
-    using System.Resources;
-#endif
     using System.Runtime.CompilerServices;
     using System.Runtime.InteropServices;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Security;
 
@@ -466,23 +463,6 @@ namespace System.Globalization
         }
         private volatile static CultureData s_Invariant;
 
-
-#if !FEATURE_CORECLR
-        internal static volatile ResourceSet MscorlibResourceSet;
-#endif
-
-#if !FEATURE_CORECLR
-        [System.Security.SecurityCritical]  // auto-generated
-        private static bool IsResourcePresent(String resourceKey)
-        {
-            if (MscorlibResourceSet == null)
-            {
-                MscorlibResourceSet = new ResourceSet(typeof(Environment).Assembly.GetManifestResourceStream("mscorlib.resources"));
-            }
-            return MscorlibResourceSet.GetString(resourceKey) != null;
-        }
-#endif
-
         ///////////////
         // Constructors //
         ///////////////
@@ -549,13 +529,7 @@ namespace System.Globalization
             // Ask native code if that one's real
             if (culture.InitCultureData() == false)
             {
-#if !FEATURE_CORECLR
-                if (culture.InitCompatibilityCultureData() == false
-                 && culture.InitLegacyAlternateSortData() == false)
-#endif
-                {
-                    return null;
-                }
+                return null;
             }
 
             return culture;
@@ -567,142 +541,12 @@ namespace System.Globalization
             {
                 return false;
             }
-
-#if !FEATURE_CORECLR
-            if (CultureInfo.IsTaiwanSku)
-            {
-                TreatTaiwanParentChainAsHavingTaiwanAsSpecific();
-            }
-#endif
-            return true;
-        }
-
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-        private void TreatTaiwanParentChainAsHavingTaiwanAsSpecific()
-        {
-            if (IsNeutralInParentChainOfTaiwan() && IsOsPriorToWin7() && !IsReplacementCulture)
-            {
-                // force population of fields that should have information that is
-                // different than zh-TW:
-                string s = SNATIVELANGUAGE;
-                s = SENGLISHLANGUAGE;
-                s = SLOCALIZEDLANGUAGE;
-                s = STEXTINFO;
-                s = SCOMPAREINFO;
-                s = FONTSIGNATURE;
-                int i = IDEFAULTANSICODEPAGE;
-                i = IDEFAULTOEMCODEPAGE;
-                i = IDEFAULTMACCODEPAGE;
-
-                this.sSpecificCulture = "zh-TW";
-                this.sWindowsName = "zh-TW";
-            }
-        }
-
-        private bool IsNeutralInParentChainOfTaiwan()
-        {
-            return this.sRealName == "zh" || this.sRealName == "zh-Hant";
-  }
-
-        static readonly Version s_win7Version = new Version(6, 1);
-        static private bool IsOsPriorToWin7()
-        {
-            return Environment.OSVersion.Platform == PlatformID.Win32NT &&
-                   Environment.OSVersion.Version < s_win7Version;
-        }
-        static private bool IsOsWin7OrPrior()
-        {
-            return Environment.OSVersion.Platform == PlatformID.Win32NT &&
-                Environment.OSVersion.Version < new Version(6, 2); // Win7 is 6.1.Build.Revision so we have to check for anything less than 6.2
-        }
-
-        private bool InitCompatibilityCultureData()
-        {
-            // for compatibility handle the deprecated ids: zh-chs, zh-cht
-            string cultureName = this.sRealName;
-
-            string fallbackCultureName;
-            string realCultureName;
-            switch (AnsiToLower(cultureName))
-            {
-                case "zh-chs":
-                    fallbackCultureName = "zh-Hans";
-                    realCultureName = "zh-CHS";
-                    break;
-                case "zh-cht":
-                    fallbackCultureName = "zh-Hant";
-                    realCultureName = "zh-CHT";
-                    break;
-                default:
-                    return false;
-            }
-
-            this.sRealName = fallbackCultureName;
-            if (InitCultureData() == false)
-            {
-                return false;
-            }
-            // fixup our data
-            this.sName = realCultureName; // the name that goes back to the user
-            this.sParent = fallbackCultureName;
-            this.bFramework = true;
-
-            return true;
-        }
-
-        private bool InitLegacyAlternateSortData()
-        {
-            if (!CompareInfo.IsLegacy20SortingBehaviorRequested)
-            {
-                return false;
-            }
-
-            // For V2 compatibility, handle deprecated alternate sorts
-            string cultureName = this.sRealName;
-
-            switch (AnsiToLower(cultureName))
-            {
-                case "ko-kr_unicod":
-                    cultureName = "ko-KR_unicod";
-                    this.sRealName = "ko-KR";
-                    this.iLanguage = 0x00010412;
-                    break;
-                case "ja-jp_unicod":
-                    cultureName = "ja-JP_unicod";
-                    this.sRealName = "ja-JP";
-                    this.iLanguage = 0x00010411;
-                    break;
-                case "zh-hk_stroke":
-                    cultureName = "zh-HK_stroke";
-                    this.sRealName = "zh-HK";
-                    this.iLanguage = 0x00020c04;
-                    break;
-                default:
-                    return false;
-            }
-
-            if (nativeInitCultureData(this) == false)
-            {
-                return false;
-            }
-
-            this.sRealName = cultureName;
-            this.sCompareInfo = cultureName;
-            this.bFramework = true;
-
             return true;
         }
 
-#if FEATURE_WIN32_REGISTRY
-        private static String s_RegionKey = @"System\CurrentControlSet\Control\Nls\RegionMapping";
-#endif // FEATURE_WIN32_REGISTRY
-
-#endif // !FEATURE_CORECLR
         // Cache of regions we've already looked up
         private static volatile Dictionary<String, CultureData> s_cachedRegions;
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static CultureData GetCultureDataForRegion(String cultureName, bool useUserOverride)
         {
             // First do a shortcut for Invariant
@@ -749,41 +593,6 @@ namespace System.Globalization
             //
             // Not found in the hash table, look it up the hard way
             //
-#if !FEATURE_CORECLR
-#if FEATURE_WIN32_REGISTRY
-            // First try the registry in case there are overrides of our table
-            try
-            {
-                // Open in read-only mode.
-                // Use InternalOpenSubKey so that we avoid the security check.
-                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.InternalOpenSubKey(s_RegionKey, false);
-
-                if (key != null)
-                {
-                    try
-                    {
-                        Object value = key.InternalGetValue(cultureName, null, false, false);
-
-                        if (value != null)
-                        {
-                            // Get the name of the locale to try.
-                            String specificForRegion = value.ToString();
-
-                            // See if it's real
-                            retVal = GetCultureData(specificForRegion, useUserOverride);
-                        }
-                    }
-                    finally
-                    {
-                        key.Close();
-                    }
-                }
-            }
-            // If this fails for any reason, we'll just ignore it, likely it just isn't there.
-            catch (ObjectDisposedException) { }
-            catch (ArgumentException) { }
-#endif // FEATURE_WIN32_REGISTRY
-#endif // !FEATURE_CORECLR
 
             // If not a valid mapping from the registry we'll have to try the hard coded table
             if (retVal == null || (retVal.IsNeutralCulture == true))
@@ -841,7 +650,6 @@ namespace System.Globalization
 #if FEATURE_USE_LCID
         // Obtain locale name from LCID
         // NOTE: This will get neutral names, unlike the OS API
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern String LCIDToLocaleName(int lcid);
 
@@ -851,25 +659,6 @@ namespace System.Globalization
             String localeName = null;
             CultureData retVal = null;
 
-#if !FEATURE_CORECLR
-            // If V2 legacy sort is requested, then provide deprecated alternate sorts
-            if (CompareInfo.IsLegacy20SortingBehaviorRequested)
-            {
-                switch (culture)
-                {
-                    case 0x00010412:
-                        localeName = "ko-KR_unicod";
-                        break;
-                    case 0x00010411:
-                        localeName = "ja-JP_unicod";
-                        break;
-                    case 0x00020c04:
-                        localeName = "zh-HK_stroke";
-                        break;
-                }
-            }
-#endif
-
             if (localeName == null)
             {
                 // Convert the lcid to a name, then use that
@@ -886,19 +675,6 @@ namespace System.Globalization
             }
             else
             {
-#if !FEATURE_CORECLR
-                switch (localeName)
-                {
-                    // for compatibility with Whidbey, when requesting
-                    // a locale from LCID, return the old localeName
-                    case "zh-Hans":
-                        localeName = "zh-CHS";
-                        break;
-                    case "zh-Hant":
-                        localeName = "zh-CHT";
-                        break;
-                }
-#endif
                 // Valid name, use it
                 retVal = GetCultureData(localeName, bUseUserOverride);
             }
@@ -921,7 +697,6 @@ namespace System.Globalization
             s_replacementCultureNames = null;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static CultureInfo[] GetCultures(CultureTypes types)
         {
             // Disable  warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete
@@ -972,29 +747,12 @@ namespace System.Globalization
 
             int arrayLength = cultureNames.Length;
 
-#if !FEATURE_CORECLR
-            if ((types & (CultureTypes.NeutralCultures | CultureTypes.FrameworkCultures)) != 0) // add zh-CHT and zh-CHS
-            {
-                arrayLength += 2;
-            }
-#endif // FEATURE_CORECLR
-
             CultureInfo[] cultures = new CultureInfo[arrayLength];
 
             for (int i = 0; i < cultureNames.Length; i++)
             {
                 cultures[i] = new CultureInfo(cultureNames[i]);
             }
-
-#if !FEATURE_CORECLR
-            if ((types & (CultureTypes.NeutralCultures | CultureTypes.FrameworkCultures)) != 0) // add zh-CHT and zh-CHS
-            {
-                Contract.Assert(arrayLength == cultureNames.Length + 2, "CultureData.nativeEnumCultureNames() Incorrect array size");
-                cultures[cultureNames.Length] = new CultureInfo("zh-CHS");
-                cultures[cultureNames.Length + 1] = new CultureInfo("zh-CHT");
-            }
-#endif // FEATURE_CORECLR
-
 #pragma warning restore 618
 
             return cultures;
@@ -1032,10 +790,9 @@ namespace System.Globalization
         ////////////////////////////////////////////////////////////////////////
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static bool IsReplacementCultureName(String name)
         {
-            Contract.Assert(name != null, "IsReplacementCultureName(): name should not be null");
+            Debug.Assert(name != null, "IsReplacementCultureName(): name should not be null");
             String[] replacementCultureNames = s_replacementCultureNames;
             if (replacementCultureNames == null)
             {
@@ -1045,7 +802,7 @@ namespace System.Globalization
                 }
 
                 // Even if we don't have any replacement cultures, the returned replacementCultureNames will still an empty string array, not null.
-                Contract.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null");
+                Debug.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null");
                 Array.Sort(replacementCultureNames);
                 s_replacementCultureNames = replacementCultureNames;
             }
@@ -1069,7 +826,7 @@ namespace System.Globalization
         {
             get
             {
-                Contract.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+                Debug.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
                 // since windows doesn't know about zh-CHS and zh-CHT,
                 // we leave sRealName == zh-Hanx but we still need to
                 // pretend that it was zh-CHX.
@@ -1097,7 +854,7 @@ namespace System.Globalization
         {
             get
             {
-                //                Contract.Assert(this.sName != null,
+                //                Debug.Assert(this.sName != null,
                 //                    "[CultureData.SNAME] Expected this.sName to be populated by COMNlsInfo::nativeInitCultureData already");
                 if (this.sName == null)
                 {
@@ -1110,31 +867,12 @@ namespace System.Globalization
         // Parent name (which may be a custom locale/culture)
         internal String SPARENT
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sParent == null)
                 {
                     // Ask using the real name, so that we get parents of neutrals
                     this.sParent = DoGetLocaleInfo(this.sRealName, LOCALE_SPARENT);
-
-#if !FEATURE_CORECLR
-                    // for compatibility, the chain should be:
-                    // zh-CN -> zh-CHS -> zh-Hans -> zh
-                    // zh-TW -> zh-CHT -> zh-Hant -> zh
-                    Contract.Assert(this.sName != "zh-CHS" && this.sName != "zh-CHT",
-                                    "sParent should have been initialized for zh-CHS and zh-CHT when they were constructed, otherwise we get recursion");
-                    switch (this.sParent)
-                    {
-                        case "zh-Hans":
-                            this.sParent = "zh-CHS";
-                            break;
-                        case "zh-Hant":
-                            this.sParent = "zh-CHT";
-                            break;
-                    }
-#endif
-
                 }
                 return this.sParent;
             }
@@ -1143,18 +881,10 @@ namespace System.Globalization
         // Localized pretty name for this locale (ie: Inglis (estados Unitos))
         internal String SLOCALIZEDDISPLAYNAME
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sLocalizedDisplayName == null)
                 {
-#if !FEATURE_CORECLR
-                    String resourceKey = "Globalization.ci_" + this.sName;
-                    if (IsResourcePresent(resourceKey))
-                    {
-                        this.sLocalizedDisplayName = Environment.GetResourceString(resourceKey);
-                    }
-#endif
                     // If it hasn't been found (Windows 8 and up), fallback to the system
                     if (String.IsNullOrEmpty(this.sLocalizedDisplayName))
                     {
@@ -1184,7 +914,6 @@ namespace System.Globalization
         // English pretty name for this locale (ie: English (United States))
         internal String SENGDISPLAYNAME
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sEnglishDisplayName == null)
@@ -1193,17 +922,6 @@ namespace System.Globalization
                     if (this.IsNeutralCulture)
                     {
                         this.sEnglishDisplayName = this.SENGLISHLANGUAGE;
-#if !FEATURE_CORECLR
-                        // differentiate the legacy display names
-                        switch (this.sName)
-                        {
-                            case "zh-CHS":
-                            case "zh-CHT":
-                                this.sEnglishDisplayName += " Legacy";
-                                break;
-                        }
-#endif
-
                     }
                     else
                     {
@@ -1237,7 +955,6 @@ namespace System.Globalization
         // Native pretty name for this locale (ie: Deutsch (Deutschland))
         internal String SNATIVEDISPLAYNAME
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sNativeDisplayName == null)
@@ -1246,32 +963,10 @@ namespace System.Globalization
                     if (this.IsNeutralCulture)
                     {
                         this.sNativeDisplayName = this.SNATIVELANGUAGE;
-#if !FEATURE_CORECLR
-                        // differentiate the legacy display names
-                        switch (this.sName)
-                        {
-                            case "zh-CHS":
-                                this.sNativeDisplayName += " \u65E7\u7248";
-                                break;
-                            case "zh-CHT":
-                                this.sNativeDisplayName += " \u820A\u7248";
-                                break;
-                        }
-#endif
                     }
                     else
                     {
-#if !FEATURE_CORECLR
-                        if (IsIncorrectNativeLanguageForSinhala())
-                        {
-                            // work around bug in Windows 7 for native name of Sinhala
-                            this.sNativeDisplayName ="\x0dc3\x0dd2\x0d82\x0dc4\x0dbd (\x0DC1\x0DCA\x200D\x0DBB\x0DD3\x0020\x0DBD\x0D82\x0D9A\x0DCF)";
-                        }
-                        else
-#endif
-                        {
-                            this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME);
-                        }
+                        this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME);
 
                         // if it isn't found build one:
                         if (String.IsNullOrEmpty(this.sNativeDisplayName))
@@ -1291,7 +986,7 @@ namespace System.Globalization
             get
             {
                 // This got populated when ComNlsInfo::nativeInitCultureData told us we had a culture
-                Contract.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already");
+                Debug.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already");
                 return this.sSpecificCulture;
             }
         }
@@ -1303,7 +998,6 @@ namespace System.Globalization
         // iso 639 language name, ie: en
         internal String SISO639LANGNAME
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sISO639Language == null)
@@ -1317,7 +1011,6 @@ namespace System.Globalization
         // iso 639 language name, ie: eng
         internal String SISO639LANGNAME2
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sISO639Language2 == null)
@@ -1331,7 +1024,6 @@ namespace System.Globalization
         // abbreviated windows language name (ie: enu) (non-standard, avoid this)
         internal String SABBREVLANGNAME
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sAbbrevLang == null)
@@ -1346,7 +1038,6 @@ namespace System.Globalization
         // This is only valid for Windows 8 and higher neutrals:
         internal String SLOCALIZEDLANGUAGE
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sLocalizedLanguage == null)
@@ -1369,7 +1060,6 @@ namespace System.Globalization
         // English name for this language (Windows Only) ie: German
         internal String SENGLISHLANGUAGE
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sEnglishLanguage == null)
@@ -1383,18 +1073,10 @@ namespace System.Globalization
         // Native name of this language (Windows Only) ie: Deutsch
         internal String SNATIVELANGUAGE
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sNativeLanguage == null)
                 {
-#if !FEATURE_CORECLR
-                    if (IsIncorrectNativeLanguageForSinhala())
-                    {
-                        this.sNativeLanguage = "\x0dc3\x0dd2\x0d82\x0dc4\x0dbd";
-                    }
-                    else
-#endif
                     {
                         this.sNativeLanguage = DoGetLocaleInfo(LOCALE_SNATIVELANGUAGENAME);
                     }
@@ -1403,15 +1085,6 @@ namespace System.Globalization
             }
         }
 
-#if !FEATURE_CORECLR
-        private bool IsIncorrectNativeLanguageForSinhala()
-        {
-            return IsOsWin7OrPrior() 
-                && (sName == "si-LK" || sName == "si")
-                && !IsReplacementCulture;
-        }
-#endif
-
         ///////////
         // Region //
         ///////////
@@ -1419,7 +1092,6 @@ namespace System.Globalization
         // region name (eg US)
         internal String SREGIONNAME
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sRegionName == null)
@@ -1455,18 +1127,10 @@ namespace System.Globalization
         // localized name for the country
         internal string SLOCALIZEDCOUNTRY
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sLocalizedCountry == null)
                 {
-#if !FEATURE_CORECLR
-                    String resourceKey = "Globalization.ri_" + this.SREGIONNAME;
-                    if (IsResourcePresent(resourceKey))
-                    {
-                        this.sLocalizedCountry = Environment.GetResourceString(resourceKey);
-                    }
-#endif
                     // If it hasn't been found (Windows 8 and up), fallback to the system
                     if (String.IsNullOrEmpty(this.sLocalizedCountry))
                     {
@@ -1488,7 +1152,6 @@ namespace System.Globalization
         // english country name (RegionInfo) ie: Germany
         internal String SENGCOUNTRY
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sEnglishCountry == null)
@@ -1502,7 +1165,6 @@ namespace System.Globalization
         // native country name (RegionInfo) ie: Deutschland
         internal String SNATIVECOUNTRY
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sNativeCountry == null)
@@ -1516,7 +1178,6 @@ namespace System.Globalization
         // ISO 3166 Country Name
         internal String SISO3166CTRYNAME
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sISO3166CountryName == null)
@@ -1530,7 +1191,6 @@ namespace System.Globalization
         // ISO 3166 Country Name
         internal String SISO3166CTRYNAME2
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sISO3166CountryName2 == null)
@@ -1544,7 +1204,6 @@ namespace System.Globalization
         // abbreviated Country Name (windows version, non-standard, avoid)
         internal String SABBREVCTRYNAME
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sAbbrevCountry == null)
@@ -1588,7 +1247,6 @@ namespace System.Globalization
         // Console fallback name (ie: locale to use for console apps for unicode-only locales)
         internal String SCONSOLEFALLBACKNAME
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sConsoleFallbackName == null)
@@ -1628,7 +1286,6 @@ namespace System.Globalization
         // (user can override) grouping of digits
         internal int[] WAGROUPING
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.waGrouping == null || UseUserOverride)
@@ -1646,7 +1303,6 @@ namespace System.Globalization
         // Not a Number
         internal String SNAN
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sNaN == null)
@@ -1660,7 +1316,6 @@ namespace System.Globalization
         // + Infinity
         internal String SPOSINFINITY
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sPositiveInfinity == null)
@@ -1674,7 +1329,6 @@ namespace System.Globalization
         // - Infinity
         internal String SNEGINFINITY
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sNegativeInfinity == null)
@@ -1721,7 +1375,6 @@ namespace System.Globalization
         // Percent (%) symbol
         internal String SPERCENT
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sPercent == null)
@@ -1736,7 +1389,6 @@ namespace System.Globalization
         // PerMille (‰) symbol
         internal String SPERMILLE
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sPerMille == null)
@@ -1755,7 +1407,6 @@ namespace System.Globalization
         // (user can override) local monetary symbol, eg: $
         internal String SCURRENCY
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sCurrency == null || UseUserOverride)
@@ -1769,7 +1420,6 @@ namespace System.Globalization
         // international monetary symbol (RegionInfo), eg: USD
         internal String SINTLSYMBOL
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sIntlMonetarySymbol == null)
@@ -1783,7 +1433,6 @@ namespace System.Globalization
         // English name for this currency (RegionInfo), eg: US Dollar
         internal String SENGLISHCURRENCY
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sEnglishCurrency == null)
@@ -1797,7 +1446,6 @@ namespace System.Globalization
         // Native name for this currency (RegionInfo), eg: Schweiz Frank
         internal String SNATIVECURRENCY
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sNativeCurrency == null)
@@ -1815,7 +1463,6 @@ namespace System.Globalization
         // (user can override) monetary grouping of digits
         internal int[] WAMONGROUPING
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.waMonetaryGrouping == null || UseUserOverride)
@@ -1849,7 +1496,6 @@ namespace System.Globalization
         // (user can override) list Separator
         internal String SLIST
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sListSeparator == null || UseUserOverride)
@@ -1876,7 +1522,6 @@ namespace System.Globalization
         // (user can override) AM designator
         internal String SAM1159
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sAM1159 == null || UseUserOverride)
@@ -1890,7 +1535,6 @@ namespace System.Globalization
         // (user can override) PM designator
         internal String SPM2359
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.sPM2359 == null || UseUserOverride)
@@ -2071,7 +1715,6 @@ namespace System.Globalization
         // time duration format
         internal String[] SADURATION
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (this.saDurationFormats == null)
@@ -2202,7 +1845,7 @@ namespace System.Globalization
                     // We then have to copy that list to a new array of the right size.
                     // Default calendar should be first
                     int[] calendarInts = new int[23];
-                    Contract.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+                    Debug.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
                     int count = CalendarData.nativeGetCalendars(this.sWindowsName, this.bUseOverrides, calendarInts);
 
                     // See if we had a calendar to add.
@@ -2247,7 +1890,6 @@ namespace System.Globalization
                         // Want 1st calendar to be default
                         // Prior to Vista the enumeration didn't have default calendar first
                         // Only a coreclr concern, culture.dll does the right thing.
-#if FEATURE_CORECLR
                         if (temp.Length > 1)
                         {
                             int i = DoGetLocaleInfoInt(LOCALE_ICALENDARTYPE);
@@ -2257,7 +1899,6 @@ namespace System.Globalization
                                 temp[0] = i;
                             }
                         }
-#endif
 
                         this.waCalendars = temp;
                     }
@@ -2276,7 +1917,7 @@ namespace System.Globalization
 
         internal CalendarData GetCalendar(int calendarId)
         {
-            Contract.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS,
+            Debug.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS,
                 "[CultureData.GetCalendar] Expect calendarId to be in a valid range");
 
             // arrays are 0 based, calendarIds are 1 based
@@ -2295,16 +1936,8 @@ namespace System.Globalization
             // Make sure that calendar has data
             if (calendarData == null || UseUserOverride)
             {
-                Contract.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+                Debug.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
                 calendarData = new CalendarData(this.sWindowsName, calendarId, this.UseUserOverride);
-#if !FEATURE_CORECLR
-                //Work around issue where Win7 data for MonthDay contains invalid two sets of data separated by semicolon
-                //even though MonthDay is not enumerated
-                if (IsOsWin7OrPrior() && !IsSupplementalCustomCulture && !IsReplacementCulture)
-                {
-                    calendarData.FixupWin7MonthDaySemicolonBug();
-                }
-#endif
                 calendars[calendarIndex] = calendarData;
             }
 
@@ -2348,7 +1981,7 @@ namespace System.Globalization
             {
                 if (this.iReadingLayout == undef)
                 {
-                    Contract.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+                    Debug.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
                     this.iReadingLayout = DoGetLocaleInfoInt(LOCALE_IREADINGLAYOUT);
                 }
 
@@ -2365,7 +1998,6 @@ namespace System.Globalization
         // es-ES_tradnl -> es-ES
         internal String STEXTINFO               // Text info name to use for text information
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 if (this.sTextInfo == null)
@@ -2391,7 +2023,6 @@ namespace System.Globalization
         // Compare info name (including sorting key) to use if custom
         internal String SCOMPAREINFO
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 if (this.sCompareInfo == null)
@@ -2427,7 +2058,6 @@ namespace System.Globalization
 
         private String SSCRIPTS
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (this.sScripts == null)
@@ -2440,7 +2070,6 @@ namespace System.Globalization
 
         private String SOPENTYPELANGUAGETAG
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return DoGetLocaleInfo(LOCALE_SOPENTYPELANGUAGETAG);
@@ -2449,7 +2078,6 @@ namespace System.Globalization
 
         private String FONTSIGNATURE
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (this.fontSignature == null)
@@ -2462,7 +2090,6 @@ namespace System.Globalization
 
         private String SKEYBOARDSTOINSTALL
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return DoGetLocaleInfo(LOCALE_SKEYBOARDSTOINSTALL);
@@ -2520,7 +2147,6 @@ namespace System.Globalization
 
         // Obtain locale name from LCID
         // NOTE: This will get neutral names, unlike the OS API
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int LocaleNameToLCID(String localeName);
 
@@ -2532,7 +2158,7 @@ namespace System.Globalization
             {
                 if (this.iLanguage == 0)
                 {
-                    Contract.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+                    Debug.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
                     this.iLanguage = LocaleNameToLCID(this.sRealName);
                 }
                 return this.iLanguage;
@@ -2588,21 +2214,21 @@ namespace System.Globalization
         // All of our era names
         internal String[] EraNames(int calendarId)
         {
-            Contract.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
+            Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
 
             return this.GetCalendar(calendarId).saEraNames;
         }
 
         internal String[] AbbrevEraNames(int calendarId)
         {
-            Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+            Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
 
             return this.GetCalendar(calendarId).saAbbrevEraNames;
         }
 
         internal String[] AbbreviatedEnglishEraNames(int calendarId)
         {
-            Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+            Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
 
             return this.GetCalendar(calendarId).saAbbrevEnglishEraNames;
         }
@@ -2614,7 +2240,6 @@ namespace System.Globalization
         // Time separator (derived from time format)
         internal String TimeSeparator
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (sTimeSeparator == null || UseUserOverride)
@@ -2860,8 +2485,8 @@ namespace System.Globalization
 
         private static int IndexOfTimePart(string format, int startIndex, string timeParts)
         {
-            Contract.Assert(startIndex >= 0, "startIndex cannot be negative");
-            Contract.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
+            Debug.Assert(startIndex >= 0, "startIndex cannot be negative");
+            Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
             bool inQuote = false;
             for (int i = startIndex; i < format.Length; ++i)
             {
@@ -2896,16 +2521,14 @@ namespace System.Globalization
             return -1;
         }
 
-        [System.Security.SecurityCritical]
         string DoGetLocaleInfo(uint lctype)
         {
-            Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+            Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
             return DoGetLocaleInfo(this.sWindowsName, lctype);
         }
 
         // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
         // "windows" name, which can be specific for downlevel (< windows 7) os's.
-        [System.Security.SecurityCritical]  // auto-generated
         string DoGetLocaleInfo(string localeName, uint lctype)
         {
             // Fix lctype if we don't want overrides
@@ -2915,7 +2538,7 @@ namespace System.Globalization
             }
 
             // Ask OS for data
-            Contract.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null");
+            Debug.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null");
             string result = CultureInfo.nativeGetLocaleInfoEx(localeName, lctype);
             if (result == null)
             {
@@ -2936,7 +2559,7 @@ namespace System.Globalization
 
             // Ask OS for data, note that we presume it returns success, so we have to know that
             // sWindowsName is valid before calling.
-            Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+            Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
             int result = CultureInfo.nativeGetLocaleInfoExInt(this.sWindowsName, lctype);
 
             return result;
@@ -2945,7 +2568,7 @@ namespace System.Globalization
         String[] DoEnumTimeFormats()
         {
             // Note that this gets overrides for us all the time
-            Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+            Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
             String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, 0, UseUserOverride));
 
             return result;
@@ -2954,7 +2577,7 @@ namespace System.Globalization
         String[] DoEnumShortTimeFormats()
         {
             // Note that this gets overrides for us all the time
-            Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+            Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
             String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, TIME_NOSECONDS, UseUserOverride));
 
             return result;
@@ -2979,7 +2602,6 @@ namespace System.Globalization
         //                          not affected by the Calendar property in DTFI.
         //
         ////////////////////////////////////////////////////////////////////////////
-        [System.Security.SecurityCritical]  // auto-generated
         internal void GetNFIValues(NumberFormatInfo nfi)
         {
             if (this.IsInvariantCulture)
@@ -3017,7 +2639,7 @@ namespace System.Globalization
                 //
                 // Ask native side for our data.
                 //
-                Contract.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+                Debug.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
                 CultureData.nativeGetNumberFormatInfoValues(this.sWindowsName, nfi, UseUserOverride);
             }
 
@@ -3060,17 +2682,6 @@ namespace System.Globalization
             {
                 nfi.currencyDecimalSeparator = nfi.numberDecimalSeparator;
             }
-
-#if !FEATURE_CORECLR
-            if ((932 == this.IDEFAULTANSICODEPAGE) ||
-               (949 == this.IDEFAULTANSICODEPAGE))
-            {
-                // Legacy behavior for cultures that use Japanese/Korean default ANSI code pages
-                // Note that this is a code point, not a character.  On Japanese/Korean machines this
-                // will be rendered as their currency symbol, not rendered as a "\"
-                nfi.ansiCurrencySymbol = "\x5c";
-            }
-#endif // !FEATURE_CORECLR
         }
 
         static private int ConvertFirstDayOfWeekMonToSun(int iTemp)
@@ -3337,20 +2948,16 @@ namespace System.Globalization
         internal const uint TIME_NOSECONDS = 0x00000002;   // Don't use seconds (get short time format for enumtimeformats on win7+)
 
         // Get our initial minimal culture data (name, parent, etc.)
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool nativeInitCultureData(CultureData cultureData);
 
         // Grab the NumberFormatInfo data
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool nativeGetNumberFormatInfoValues(String localeName, NumberFormatInfo nfi, bool useUserOverride);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern String[] nativeEnumTimeFormats(String localeName, uint dwFlags, bool useUserOverride);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [SuppressUnmanagedCodeSecurityAttribute()]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         internal static extern int nativeEnumCultureNames(int cultureTypes, ObjectHandleOnStack retStringArray);
index 1ef3809..fd9b0ed 100644 (file)
@@ -39,6 +39,7 @@ namespace System.Globalization {
     using System.Security.Permissions;
     using System.Reflection;
     using Microsoft.Win32;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Resources;
 
@@ -66,10 +67,6 @@ namespace System.Globalization {
         internal bool m_isReadOnly;
         internal CompareInfo compareInfo;
         internal TextInfo textInfo;
-        // Not serialized for now since we only build it privately for use in the CARIB (so rebuilding is OK)
-#if !FEATURE_CORECLR
-        [NonSerialized]internal RegionInfo regionInfo;
-#endif
         internal NumberFormatInfo numInfo;
         internal DateTimeFormatInfo dateTimeInfo;
         internal Calendar calendar;
@@ -88,7 +85,7 @@ namespace System.Globalization {
 #if FEATURE_LEAK_CULTURE_INFO
         [NonSerialized]private bool m_isSafeCrossDomain;
         [NonSerialized]private int m_createdDomainID;
-#endif // !FEATURE_CORECLR
+#endif // !FEATURE_LEAK_CULTURE_INFO
         [NonSerialized]private CultureInfo m_consoleFallbackCulture;
 
         // Names are confusing.  Here are 3 names we have:
@@ -150,7 +147,6 @@ namespace System.Globalization {
 
 #if FEATURE_APPX
         // When running under AppX, we use this to get some information about the language list
-        [SecurityCritical]
         private static volatile WindowsRuntimeResourceManagerBase s_WindowsRuntimeResourceManager;
 
         [ThreadStatic]
@@ -195,7 +191,6 @@ namespace System.Globalization {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static CultureInfo InitUserDefaultCulture()
         {
             String strDefault = GetDefaultLocaleName(LOCALE_USER_DEFAULT);
@@ -239,7 +234,6 @@ namespace System.Globalization {
         }
 
 #if FEATURE_APPX
-        [SecuritySafeCritical]
         internal static CultureInfo GetCultureInfoForUserPreferredLanguageInAppX()
         {
             // If a call to GetCultureInfoForUserPreferredLanguageInAppX() generated a recursive
@@ -285,7 +279,6 @@ namespace System.Globalization {
             return toReturn;
         }
 
-        [SecuritySafeCritical]
         internal static bool SetCultureInfoForUserPreferredLanguageInAppX(CultureInfo ci)
         {
             // If running within a compilation process (mscorsvw.exe, for example), it is illegal to
@@ -411,13 +404,13 @@ namespace System.Globalization {
             // e.g. for es-ES_tradnl: v2 puts es-ES in m_name; v4 puts es-ES_tradnl
             if (m_name == null || IsAlternateSortLcid(cultureID))
             {
-                Contract.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0");
+                Debug.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0");
                 InitializeFromCultureId(cultureID, m_useUserOverride);
             }
             else
             {
 #endif
-                Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
+                Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
 
                 this.m_cultureData = CultureData.GetCultureData(m_name, m_useUserOverride);
                 if (this.m_cultureData == null)
@@ -484,14 +477,14 @@ namespace System.Globalization {
         // For Silverlight, the answer is always no.
         internal bool IsSafeCrossDomain {
             get {
-                Contract.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0");
+                Debug.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0");
                 return m_isSafeCrossDomain;
             }
         }
 
         internal int CreatedDomainID {
             get {
-                Contract.Assert(m_createdDomainID != 0,  "[CultureInfo.CreatedDomain] m_createdDomainID != 0");
+                Debug.Assert(m_createdDomainID != 0,  "[CultureInfo.CreatedDomain] m_createdDomainID != 0");
                 return m_createdDomainID;
             }
         }
@@ -642,7 +635,7 @@ namespace System.Globalization {
         }
 
         internal static bool VerifyCultureName(CultureInfo culture, bool throwException) {
-            Contract.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
+            Debug.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
 
             //If we have an instance of one of our CultureInfos, the user can't have changed the
             //name and we know that all names are valid in files.
@@ -670,9 +663,6 @@ namespace System.Globalization {
             get {
                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
 
-#if !FEATURE_CORECLR
-                return Thread.CurrentThread.CurrentCulture;
-#else
                 // In the case of CoreCLR, Thread.m_CurrentCulture and
                 // Thread.m_CurrentUICulture are thread static so as not to let
                 // CultureInfo objects leak across AppDomain boundaries. The
@@ -693,7 +683,6 @@ namespace System.Globalization {
                     s_DefaultThreadCurrentCulture ??
                     s_userDefaultCulture ??
                     UserDefaultCulture;
-#endif
             }
 
             set {
@@ -768,9 +757,6 @@ namespace System.Globalization {
             get {
                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
 
-#if !FEATURE_CORECLR
-                return Thread.CurrentThread.CurrentUICulture;
-#else
                 // In the case of CoreCLR, Thread.m_CurrentCulture and
                 // Thread.m_CurrentUICulture are thread static so as not to let
                 // CultureInfo objects leak across AppDomain boundaries. The
@@ -791,7 +777,6 @@ namespace System.Globalization {
                     s_DefaultThreadCurrentUICulture ??
                     s_userDefaultUICulture ??
                     UserDefaultUICulture;
-#endif
             }
 
             set {
@@ -841,10 +826,6 @@ namespace System.Globalization {
                 return s_DefaultThreadCurrentCulture;
             }
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-            [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
-#pragma warning restore 618
             set {
 
                 // If you add pre-conditions to this method, check to see if you also need to 
@@ -859,10 +840,6 @@ namespace System.Globalization {
                 return s_DefaultThreadCurrentUICulture;
             }
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-            [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
-#pragma warning restore 618
             set {
 
                 //If they're trying to use a Culture with a name that we can't use in resource lookup,
@@ -913,7 +890,6 @@ namespace System.Globalization {
 
         public virtual CultureInfo Parent
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 Contract.Ensures(Contract.Result<CultureInfo>() != null);
@@ -1063,11 +1039,10 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
         public virtual String DisplayName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 Contract.Ensures(Contract.Result<String>() != null);
-                Contract.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");
+                Debug.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");
 
                 return m_cultureData.SLOCALIZEDDISPLAYNAME;
             }
@@ -1083,7 +1058,6 @@ namespace System.Globalization {
         //
         ////////////////////////////////////////////////////////////////////////
         public virtual String NativeName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 Contract.Ensures(Contract.Result<String>() != null);
                 return (this.m_cultureData.SNATIVEDISPLAYNAME);
@@ -1100,7 +1074,6 @@ namespace System.Globalization {
         //
         ////////////////////////////////////////////////////////////////////////
         public virtual String EnglishName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 Contract.Ensures(Contract.Result<String>() != null);
                 return (this.m_cultureData.SENGDISPLAYNAME);
@@ -1109,7 +1082,6 @@ namespace System.Globalization {
       
         // ie: en
         public virtual String TwoLetterISOLanguageName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 Contract.Ensures(Contract.Result<String>() != null);
                 return (this.m_cultureData.SISO639LANGNAME);
@@ -1118,7 +1090,6 @@ namespace System.Globalization {
 
         // ie: eng
         public virtual String ThreeLetterISOLanguageName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 Contract.Ensures(Contract.Result<String>() != null);
                 return (this.m_cultureData.SISO639LANGNAME2);
@@ -1134,7 +1105,6 @@ namespace System.Globalization {
         //
         ////////////////////////////////////////////////////////////////////////
         public virtual String ThreeLetterWindowsLanguageName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 Contract.Ensures(Contract.Result<String>() != null);
                 return (this.m_cultureData.SABBREVLANGNAME);
@@ -1174,31 +1144,6 @@ namespace System.Globalization {
             }
         }
 
-#if !FEATURE_CORECLR
-        ////////////////////////////////////////////////////////////////////////
-        //
-        //  RegionInfo
-        //
-        //  Gets the RegionInfo for this culture.
-        //
-        ////////////////////////////////////////////////////////////////////////
-        private RegionInfo Region
-        {
-            get
-            {
-                if (regionInfo==null)
-                {
-                    // Make a new regionInfo
-                    RegionInfo tempRegionInfo = new RegionInfo(this.m_cultureData);
-                    regionInfo = tempRegionInfo;
-                }
-                return (regionInfo);
-            }
-        }
-#endif // FEATURE_CORECLR
-
-
-
         ////////////////////////////////////////////////////////////////////////
         //
         //  TextInfo
@@ -1290,7 +1235,7 @@ namespace System.Globalization {
         {
             Contract.Ensures(Contract.Result<String>() != null);
 
-            Contract.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set");
+            Debug.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set");
             return m_name;
         }
 
@@ -1395,17 +1340,16 @@ namespace System.Globalization {
             }
         }
 
-
-
         public void ClearCachedData() {
             s_userDefaultUICulture = null;
             s_userDefaultCulture = null;
 
             RegionInfo.s_currentRegionInfo = null;
-#if !FEATURE_CORECLR // System.TimeZone does not exist in CoreCLR
+#pragma warning disable CS0618
             TimeZone.ResetTimeZone();
-#endif // FEATURE_CORECLR
+#pragma warning restore CS0618
             TimeZoneInfo.ClearCachedData();
+
             // Delete the cached cultures.
             s_LcidCachedCultures = null;
             s_NameCachedCultures = null;
@@ -1431,7 +1375,7 @@ namespace System.Globalization {
         //This function exists as a shortcut to prevent us from loading all of the non-gregorian
         //calendars unless they're required.
         internal static Calendar GetCalendarInstanceRare(int calType) {
-            Contract.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN");
+            Debug.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN");
 
             switch (calType) {
                 case Calendar.CAL_GREGORIAN_US:               // Gregorian (U.S.) calendar
@@ -1483,7 +1427,7 @@ namespace System.Globalization {
             get {
                 Contract.Ensures(Contract.Result<Calendar>() != null);
                 if (calendar == null) {
-                    Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
+                    Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
                     // Get the default calendar for this culture.  Note that the value can be
                     // from registry if this is a user default culture.
                     Calendar newObj = this.m_cultureData.DefaultCalendar;
@@ -1527,7 +1471,6 @@ namespace System.Globalization {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(false)]
         public CultureInfo GetConsoleFallbackUICulture()
         {
@@ -1934,22 +1877,18 @@ namespace System.Globalization {
         //
         
         // Get Locale Info Ex calls.  So we don't have to muck with the different int/string return types we declared two of these:
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern String nativeGetLocaleInfoEx(String localeName, uint field);
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int nativeGetLocaleInfoExInt(String localeName, uint field);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool nativeSetThreadLocale(String localeName);
 
-        [System.Security.SecurityCritical]
         private static String GetDefaultLocaleName(int localeType)
         {
-            Contract.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
+            Debug.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
 
             string localeName = null;
             if(InternalGetDefaultLocaleName(localeType, JitHelpers.GetStringHandleOnStack(ref localeName)))
@@ -1960,13 +1899,11 @@ namespace System.Globalization {
         }
 
         // Get the default locale name
-        [System.Security.SecurityCritical]  // auto-generated
         [SuppressUnmanagedCodeSecurity]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool InternalGetDefaultLocaleName(int localetype, StringHandleOnStack localeString);
 
-        [System.Security.SecuritySafeCritical] // auto-generated
         private static String GetUserDefaultUILanguage()
         {
             string userDefaultUiLanguage = null;
@@ -1978,13 +1915,11 @@ namespace System.Globalization {
         }
         
         // Get the user's default UI language, return locale name
-        [System.Security.SecurityCritical]  // auto-generated
         [SuppressUnmanagedCodeSecurity]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool InternalGetUserDefaultUILanguage(StringHandleOnStack userDefaultUiLanguage);
 
-        [System.Security.SecuritySafeCritical] // auto-generated
         private static String GetSystemDefaultUILanguage()
         {
             string systemDefaultUiLanguage = null;
@@ -1996,19 +1931,14 @@ namespace System.Globalization {
 
         }
 
-        [System.Security.SecurityCritical] // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [SuppressUnmanagedCodeSecurity]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool InternalGetSystemDefaultUILanguage(StringHandleOnStack systemDefaultUiLanguage);
 
-// Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern String[] nativeGetResourceFallbackArray();
-#endif
     }
 }
 
index 9b5264f..17c0b43 100644 (file)
@@ -66,7 +66,6 @@ namespace System.Globalization {
             m_invalidCultureName    = (string) info.GetValue("InvalidCultureName", typeof(string));
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
index f63de72..c6e0591 100644 (file)
@@ -11,6 +11,7 @@ namespace System {
     using System.Runtime.InteropServices;
     using System.Runtime.Versioning;
     using System.Security;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     /*  
@@ -171,13 +172,12 @@ namespace System {
         //
         ////////////////////////////////////////////////////////////////////////////
         internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) {
-            Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
+            Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
             FormatDigits(outputBuffer, value, len, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) {
-            Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
+            Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
 
             // Limit the use of this function to be two-digits, so that we have the same behavior
             // as RTM bits.
@@ -223,7 +223,7 @@ namespace System {
         
         private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi)
         {
-            Contract.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
+            Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
             if (repeat == 3)
             {            
                 return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
@@ -235,7 +235,7 @@ namespace System {
     
         private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi)
         {
-            Contract.Assert(month >=1 && month <= 12, "month >=1 && month <= 12");
+            Debug.Assert(month >=1 && month <= 12, "month >=1 && month <= 12");
             if (repeatCount == 3)
             {
                 return (dtfi.GetAbbreviatedMonthName(month));
@@ -276,7 +276,7 @@ namespace System {
         */
         private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi)
         {
-            Contract.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
+            Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
             if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) {
                 // This month is in a leap year
                 return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3)));
@@ -708,24 +708,13 @@ namespace System {
                     // accurate than the system's current offset because of daylight saving time.
                     offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime);
                 } else if (dateTime.Kind == DateTimeKind.Utc) {
-#if FEATURE_CORECLR
                     offset = TimeSpan.Zero;
-#else // FEATURE_CORECLR
-                    // This code path points to a bug in user code. It would make sense to return a 0 offset in this case.
-                    // However, because it was only possible to detect this in Whidbey, there is user code that takes a 
-                    // dependency on being serialize a UTC DateTime using the 'z' format, and it will work almost all the
-                    // time if it is offset by an incorrect conversion to local time when parsed. Therefore, we need to 
-                    // explicitly emit the local time offset, which we can do by removing the UTC flag.
-                    InvalidFormatForUtc(format, dateTime);
-                    dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local);
-                    offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
-#endif // FEATURE_CORECLR
                 } else {
                     offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
                 }
             }
             if (offset >= TimeSpan.Zero) {
-                result.Append('+');                
+                result.Append('+');
             }
             else {
                 result.Append('-');
@@ -1056,7 +1045,7 @@ namespace System {
                 index++;
             }
 
-            Contract.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
+            Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
         }
 
         internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
@@ -1138,7 +1127,6 @@ namespace System {
 
         // This is an MDA for cases when the user is using a local format with
         // a Utc DateTime.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static void InvalidFormatForUtc(String format, DateTime dateTime) {
 #if MDA_SUPPORTED
             Mda.DateTimeInvalidLocalFormat();
index 767757a..14cdeb6 100644 (file)
@@ -14,6 +14,7 @@ namespace System.Globalization {
     using System.Runtime.InteropServices;
     using System.Runtime.Versioning;
     using System.Text;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     //
@@ -208,7 +209,6 @@ namespace System.Globalization {
 
         private String LanguageName
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (m_langName == null)
@@ -231,7 +231,7 @@ namespace System.Globalization {
             {
                 // Get the abbreviated day names for our current calendar
                 this.abbreviatedDayNames = this.m_cultureData.AbbreviatedDayNames(Calendar.ID);
-                Contract.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
+                Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
             }
             return (this.abbreviatedDayNames);
         }
@@ -254,7 +254,7 @@ namespace System.Globalization {
             {
                 // Get the super short day names for our current calendar
                 this.m_superShortDayNames = this.m_cultureData.SuperShortDayNames(Calendar.ID);
-                Contract.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
+                Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
             }
             return (this.m_superShortDayNames);
         }
@@ -271,7 +271,7 @@ namespace System.Globalization {
             {
                 // Get the day names for our current calendar
                 this.dayNames = this.m_cultureData.DayNames(Calendar.ID);
-                Contract.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
+                Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
             }
             return (this.dayNames);
         }
@@ -288,7 +288,7 @@ namespace System.Globalization {
             {
                 // Get the month names for our current calendar
                 this.abbreviatedMonthNames = this.m_cultureData.AbbreviatedMonthNames(Calendar.ID);
-                Contract.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
+                Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
                     "[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year");
             }
             return (this.abbreviatedMonthNames);
@@ -307,7 +307,7 @@ namespace System.Globalization {
             {
                 // Get the month names for our current calendar
                 this.monthNames = this.m_cultureData.MonthNames(Calendar.ID);
-                Contract.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
+                Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
                     "[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year");
             }
 
@@ -335,16 +335,12 @@ namespace System.Globalization {
             // m_isDefaultCalendar is set in the setter of Calendar below.
             this.Calendar = cal;
         }
-
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-#endif
         private void InitializeOverridableProperties(CultureData cultureData, int calendarID)
         {
             // Silverlight 2.0 never took a snapshot of the user's overridable properties
             // This has a substantial performance impact so skip when CoreCLR
             Contract.Requires(cultureData != null);
-            Contract.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0");
+            Debug.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0");
 
             if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; }
             if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; }
@@ -355,19 +351,19 @@ namespace System.Globalization {
             if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarID); }
 
             this.allLongTimePatterns = this.m_cultureData.LongTimes;
-            Contract.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
+            Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
 
             this.allShortTimePatterns = this.m_cultureData.ShortTimes;
-            Contract.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
+            Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
 
             this.allLongDatePatterns = cultureData.LongDates(calendarID);
-            Contract.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
+            Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
 
             this.allShortDatePatterns = cultureData.ShortDates(calendarID);
-            Contract.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
+            Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
 
             this.allYearMonthPatterns = cultureData.YearMonths(calendarID);
-            Contract.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
+            Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
         }
 
 #region Serialization
@@ -446,11 +442,6 @@ namespace System.Globalization {
             // make sure the m_name is initialized.
             m_name = this.CultureName;
 
-#if !FEATURE_CORECLR
-            if (s_calendarNativeNames == null)
-                s_calendarNativeNames = new Hashtable();
-#endif // FEATURE_CORECLR
-
             // Important to initialize these fields otherwise we may run into exception when deserializing on Whidbey
             // because Whidbey try to initialize some of these fields using calendar data which could be null values 
             // and then we get exceptions.  So we call the accessors to force the caches to get loaded.
@@ -549,18 +540,14 @@ namespace System.Globalization {
 
         public  String AMDesignator
          {
-#if FEATURE_CORECLR
-            [System.Security.SecuritySafeCritical]  // auto-generated
-#endif
             get
             {
-#if FEATURE_CORECLR
                 if (this.amDesignator == null)
                 {
                     this.amDesignator = this.m_cultureData.SAM1159;
                 }
-#endif
-                Contract.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
+
+                Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
                 return (this.amDesignator);
             }
 
@@ -584,7 +571,7 @@ namespace System.Globalization {
             get {
                 Contract.Ensures(Contract.Result<Calendar>() != null);
                 
-                Contract.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
+                Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
                 return (this.calendar);
             }
 
@@ -820,7 +807,7 @@ namespace System.Globalization {
             {
                 if (this.m_abbrevEnglishEraNames == null)
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
                     this.m_abbrevEnglishEraNames = this.m_cultureData.AbbreviatedEnglishEraNames(Calendar.ID);
                 }
                 return (this.m_abbrevEnglishEraNames);
@@ -834,13 +821,12 @@ namespace System.Globalization {
         {
             get
             {
-#if FEATURE_CORECLR
                 if (this.dateSeparator == null)
                 {
                     this.dateSeparator = this.m_cultureData.DateSeparator(Calendar.ID);
                 }
-#endif
-                Contract.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
+
+                Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
                 return (this.dateSeparator);
             }
 
@@ -864,14 +850,12 @@ namespace System.Globalization {
         {
             get
             {
-#if FEATURE_CORECLR
                 if (this.firstDayOfWeek == -1)
                 {
                     this.firstDayOfWeek = this.m_cultureData.IFIRSTDAYOFWEEK;
                 }
-#endif
-                Contract.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
-                
+
+                Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
                 return ((DayOfWeek)this.firstDayOfWeek);
             }
 
@@ -893,13 +877,12 @@ namespace System.Globalization {
         {
             get
             {
-#if FEATURE_CORECLR
                 if (this.calendarWeekRule == -1)
                 {
                     this.calendarWeekRule = this.m_cultureData.IFIRSTWEEKOFYEAR;
                 }
-#endif
-                Contract.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
+
+                Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
                 return ((CalendarWeekRule)this.calendarWeekRule);
             }
 
@@ -1030,10 +1013,10 @@ namespace System.Globalization {
             {
                 if (this.monthDayPattern == null) 
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
                     this.monthDayPattern = this.m_cultureData.MonthDay(Calendar.ID);
                 }
-                Contract.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
+                Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
                 return (this.monthDayPattern);
             }
 
@@ -1053,18 +1036,14 @@ namespace System.Globalization {
 
         public  String PMDesignator
         {
-#if FEATURE_CORECLR
-            [System.Security.SecuritySafeCritical]  // auto-generated
-#endif
             get
             {
-#if FEATURE_CORECLR
                 if (this.pmDesignator == null)
                 {
                     this.pmDesignator = this.m_cultureData.SPM2359;
                 }
-#endif
-                Contract.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
+
+                Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
                 return (this.pmDesignator);
             }
 
@@ -1280,13 +1259,12 @@ namespace System.Globalization {
         {
             get
             {
-#if FEATURE_CORECLR
                 if (timeSeparator == null)
                 {
                     timeSeparator = this.m_cultureData.TimeSeparator;
                 }
-#endif
-                Contract.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
+
+                Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
                 return (timeSeparator);
             }
 
@@ -1563,7 +1541,7 @@ namespace System.Globalization {
                 if (this.m_genitiveAbbreviatedMonthNames == null)
                 {
                     this.m_genitiveAbbreviatedMonthNames = this.m_cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID);
-                    Contract.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
+                    Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
                         "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year");
                 }
                 return (this.m_genitiveAbbreviatedMonthNames);
@@ -1572,7 +1550,7 @@ namespace System.Globalization {
             if (this.genitiveMonthNames == null)
             {
                 this.genitiveMonthNames = this.m_cultureData.GenitiveMonthNames(this.Calendar.ID);
-                Contract.Assert(this.genitiveMonthNames.Length == 13,
+                Debug.Assert(this.genitiveMonthNames.Length == 13,
                     "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year");
             }
             return (this.genitiveMonthNames);
@@ -1588,9 +1566,9 @@ namespace System.Globalization {
         internal String[] internalGetLeapYearMonthNames(/*bool abbreviated*/) {
             if (this.leapYearMonthNames == null)
             {
-                Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
+                Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
                 this.leapYearMonthNames = this.m_cultureData.LeapYearMonthNames(Calendar.ID);
-                Contract.Assert(this.leapYearMonthNames.Length == 13,
+                Debug.Assert(this.leapYearMonthNames.Length == 13,
                     "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names");
             }
             return (leapYearMonthNames);
@@ -1783,9 +1761,9 @@ namespace System.Globalization {
         // The resulting [] can get returned to the calling app, so clone it.
         private static string[] GetMergedPatterns(string [] patterns, string defaultPattern)
         {
-            Contract.Assert(patterns != null && patterns.Length > 0,
+            Debug.Assert(patterns != null && patterns.Length > 0,
                             "[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern");
-            Contract.Assert(defaultPattern != null, 
+            Debug.Assert(defaultPattern != null, 
                             "[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string");
 
             // If the default happens to be the first in the list just return (a cloned) copy
@@ -1882,9 +1860,9 @@ namespace System.Globalization {
             {
                 if (this.allYearMonthPatterns == null)
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");                    
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");                    
                     this.allYearMonthPatterns = this.m_cultureData.YearMonths(this.Calendar.ID);
-                    Contract.Assert(this.allYearMonthPatterns.Length > 0,
+                    Debug.Assert(this.allYearMonthPatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns");
                 }
 
@@ -1901,9 +1879,9 @@ namespace System.Globalization {
             {
                 if (allShortDatePatterns == null)
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
                     this.allShortDatePatterns = this.m_cultureData.ShortDates(this.Calendar.ID);
-                    Contract.Assert(this.allShortDatePatterns.Length > 0,
+                    Debug.Assert(this.allShortDatePatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns");
                 }
 
@@ -1919,9 +1897,9 @@ namespace System.Globalization {
             {
                 if (allLongDatePatterns == null)
                 {
-                    Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
+                    Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
                     this.allLongDatePatterns = this.m_cultureData.LongDates(this.Calendar.ID);
-                    Contract.Assert(this.allLongDatePatterns.Length > 0,
+                    Debug.Assert(this.allLongDatePatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns");
                 }
 
@@ -1938,7 +1916,7 @@ namespace System.Globalization {
                 if (this.allShortTimePatterns == null)
                 {
                     this.allShortTimePatterns = this.m_cultureData.ShortTimes;
-                    Contract.Assert(this.allShortTimePatterns.Length > 0,
+                    Debug.Assert(this.allShortTimePatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns");
                 }
                 
@@ -1955,7 +1933,7 @@ namespace System.Globalization {
                 if (this.allLongTimePatterns == null)
                 {
                     this.allLongTimePatterns = this.m_cultureData.LongTimes;
-                    Contract.Assert(this.allLongTimePatterns.Length > 0,
+                    Debug.Assert(this.allLongTimePatterns.Length > 0,
                         "[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns");
                 }
                 
@@ -2384,7 +2362,6 @@ namespace System.Globalization {
             formatFlags = DateTimeFormatFlags.NotInitialized;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal TokenHashValue[] CreateTokenHashTable() {
             TokenHashValue[] temp = m_dtfiTokenHash;
             if (temp == null) {
@@ -2677,7 +2654,7 @@ namespace System.Globalization {
             } while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber));
 
             // When we are here, we are either at the end of the string, or we find a valid Hebrew number.
-            Contract.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
+            Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
                 "Invalid returned state from HebrewNumber.ParseByChar()");
 
             if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber) {
@@ -2698,13 +2675,12 @@ namespace System.Globalization {
             return (ch >= '\x0590' && ch <= '\x05ff');
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool Tokenize(TokenType TokenMask, out TokenType tokenType, out int tokenValue, ref __DTString str) {
             tokenType = TokenType.UnknownToken;
             tokenValue = 0;
 
             TokenHashValue value;
-            Contract.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
+            Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
 
             char ch = str.m_current;
             bool isLetter = Char.IsLetter(ch);
@@ -2813,7 +2789,7 @@ namespace System.Globalization {
                 }
                 previousNode = temp;
             } ;
-            Contract.Assert(false, "The hashtable is full.  This should not happen.");
+            Debug.Assert(false, "The hashtable is full.  This should not happen.");
         }
 
         void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue) {
@@ -2884,7 +2860,7 @@ namespace System.Globalization {
                 hashcode += hashProbe;
                 if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
             } while (i < TOKEN_HASH_SIZE);
-            Contract.Assert(false, "The hashtable is full.  This should not happen.");
+            Debug.Assert(false, "The hashtable is full.  This should not happen.");
         }
     }   // class DateTimeFormatInfo
 
index 40cbabc..4555bb2 100644 (file)
@@ -498,9 +498,6 @@ namespace System.Globalization
         //
         ////////////////////////////////////////////////////////////////////////////
         
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) {
             // Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix.
             String[] datePatterns = dtfi.GetAllDateTimePatterns('D');
index e2b0c95..363747c 100644 (file)
@@ -35,16 +35,6 @@ namespace System {
 
         internal static MatchNumberDelegate m_hebrewNumberParser = new MatchNumberDelegate(DateTimeParse.MatchHebrewDigits);
 
-#if !FEATURE_CORECLR
-        [SecuritySafeCritical]
-        internal static bool GetAmPmParseFlag()
-        {
-            return DateTime.EnableAmPmParseAdjustment();
-        }
-
-        internal static bool enableAmPmParseAdjustment = GetAmPmParseFlag();
-#endif
-
         internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) {
             DateTimeResult result = new DateTimeResult();       // The buffer to store the parsing result.
             result.Init();
@@ -114,7 +104,7 @@ namespace System {
                 return false;
             }
 
-            Contract.Assert(dtfi != null, "dtfi == null");
+            Debug.Assert(dtfi != null, "dtfi == null");
 
             return DoStrictParse(s, format, style, dtfi, ref result);
         }
@@ -196,7 +186,7 @@ namespace System {
                 return false;
             }
 
-            Contract.Assert(dtfi != null, "dtfi == null");
+            Debug.Assert(dtfi != null, "dtfi == null");
 
             //
             // Do a loop through the provided formats and see if we can parse succesfully in
@@ -546,8 +536,8 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                 // Wrong number of digits
                 return false;
             }
-            Contract.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99");
-            Contract.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99");
+            Debug.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99");
+            Debug.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99");
             if (minuteOffset < 0 || minuteOffset >= 60) {
                 return false;
             }
@@ -591,7 +581,6 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
         // This is the lexer. Check the character at the current index, and put the found token in dtok and
         // some raw date/time information in raw.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static Boolean Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, ref DateTimeRawInfo raw, ref DateTimeResult result, ref DateTimeFormatInfo dtfi, DateTimeStyles styles)
         {
 
@@ -761,11 +750,7 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                                 raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM);
                                 dtok.dtt = DTT.NumAmpm;
                                 // Fix AM/PM parsing case, e.g. "1/10 5 AM"
-                                if (dps == DS.D_NN 
-#if !FEATURE_CORECLR
-                                    && enableAmPmParseAdjustment
-#endif
-                                )
+                                if (dps == DS.D_NN)
                                 {
                                     if (!ProcessTerminaltState(DS.DX_NN, ref result, ref styles, ref raw, dtfi))
                                     {
@@ -1076,16 +1061,6 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                         return (false);
                     }
 
-#if !FEATURE_CORECLR                    
-                    // If DateTimeParseIgnorePunctuation is defined, we want to have the V1.1 behavior of just
-                    // ignoring any unrecognized punctuation and moving on to the next character
-                    if (Environment.GetCompatibilityFlag(CompatibilityFlag.DateTimeParseIgnorePunctuation) && ((result.flags & ParseFlags.CaptureOffset) == 0)) {
-                        str.GetNext();
-                        LexTraceExit("0210 (success)", dps);
-                        return true;
-                    }
-#endif // FEATURE_CORECLR
-                    
                     if ((str.m_current == '-' || str.m_current == '+') && ((result.flags & ParseFlags.TimeZoneUsed) == 0)) {
                         Int32 originalIndex = str.Index;
                         if (ParseTimeZone(ref str, ref result.timeZoneOffset)) {
@@ -1096,7 +1071,7 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                         else {
                             // Time zone parse attempt failed. Fall through to punctuation handling.
                             str.Index = originalIndex;
-                        }                                                
+                        }
                     }
                     
                     // Visual Basic implements string to date conversions on top of DateTime.Parse:
@@ -1104,7 +1079,7 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                     //
                     if (VerifyValidPunctuation(ref str)) {
                         LexTraceExit("0230 (success)", dps);
-                        return true;                                
+                        return true;
                     }
 
                     result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
@@ -1936,7 +1911,7 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
 
         private static Boolean GetTimeOfNN(DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw)
         {
-            Contract.Assert(raw.numCount >= 2, "raw.numCount >= 2");
+            Debug.Assert(raw.numCount >= 2, "raw.numCount >= 2");
             if ((result.flags & ParseFlags.HaveTime) != 0) {
                 // Multiple times in the input string
                 result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
@@ -1956,7 +1931,7 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                 result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
                 return false;
             }
-            Contract.Assert(raw.numCount >= 3, "raw.numCount >= 3");
+            Debug.Assert(raw.numCount >= 3, "raw.numCount >= 3");
             result.Hour = raw.GetNumber(0);
             result.Minute   = raw.GetNumber(1);
             result.Second   = raw.GetNumber(2);
@@ -2316,7 +2291,6 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
         //
         // This is the real method to do the parsing work.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool TryParse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, ref DateTimeResult result) {
             if (s == null) {
                 result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
@@ -2327,7 +2301,7 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                 return false;
             }
 
-            Contract.Assert(dtfi != null, "dtfi == null");
+            Debug.Assert(dtfi != null, "dtfi == null");
 
 #if _LOGGING
             DTFITrace(dtfi);
@@ -2548,17 +2522,15 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                 // no adjustment is required in most cases
                 return DateTimeOffsetTimeZonePostProcessing(ref result, styles);
             }
-#if FEATURE_CORECLR // on CoreCLR DateTime is also restricted to +- 14:00, just like DateTimeOffset
             else {
                 Int64 offsetTicks = result.timeZoneOffset.Ticks;
-            
+
                 // the DateTime offset must be within +- 14:00 hours.
                 if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset) {
                     result.SetFailure(ParseFailureKind.Format, "Format_OffsetOutOfRange", null);
                     return false;
                 }
             }
-#endif // FEATURE_CORECLR
 
             // The flags AssumeUniveral and AssumeLocal only apply when the input does not have a time zone
             if ((result.flags & ParseFlags.TimeZoneUsed) == 0) {
@@ -2592,7 +2564,7 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                 }
                 else {
                     // No time zone and no Assume flags, so DateTimeKind.Unspecified is fine
-                    Contract.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified");
+                    Debug.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified");
                     return true;
                 }
             }
@@ -2882,9 +2854,9 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
         }
 
         internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int result) {
-            Contract.Assert(minDigitLen > 0, "minDigitLen > 0");
-            Contract.Assert(maxDigitLen < 9, "maxDigitLen < 9");
-            Contract.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen");
+            Debug.Assert(minDigitLen > 0, "minDigitLen > 0");
+            Debug.Assert(maxDigitLen < 9, "maxDigitLen < 9");
+            Debug.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen");
             result = 0;
             int startingIndex = str.Index;
             int tokenLength = 0;
@@ -4151,7 +4123,7 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
                 case ParseFailureKind.FormatBadDateTimeCalendar:
                     return new FormatException(Environment.GetResourceString(result.failureMessageID, result.calendar));
                 default:
-                    Contract.Assert(false, "Unkown DateTimeParseFailure: " + result);
+                    Debug.Assert(false, "Unkown DateTimeParseFailure: " + result);
                     return null;
 
             }
@@ -4373,7 +4345,7 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
         }
 
         internal bool Advance(int count) {
-            Contract.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len");
+            Debug.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len");
             Index += count;
             if (Index < len) {
                 m_current = Value[Index];
@@ -4384,7 +4356,6 @@ new DS[] { DS.ERROR, DS.TX_NNN,  DS.TX_NNN,  DS.TX_NNN,  DS.ERROR,   DS.ERROR,
 
 
         // Used by DateTime.Parse() to get the next token.
-        [System.Security.SecurityCritical]  // auto-generated
         internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi) {
             tokenValue = 0;
             if (Index >= len) {
@@ -4464,7 +4435,6 @@ Start:
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBeforeSeparator, out char charBeforeSeparator) {
             indexBeforeSeparator = Index;
             charBeforeSeparator = m_current;
@@ -4668,7 +4638,7 @@ Start:
         // Get the current character.
         //
         internal char GetChar() {
-            Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
+            Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
             return (Value[Index]);
         }
 
@@ -4676,8 +4646,8 @@ Start:
         // Convert the current character to a digit, and return it.
         //
         internal int GetDigit() {
-            Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
-            Contract.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
+            Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
+            Debug.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
             return (Value[Index] - '0');
         }
 
@@ -4810,7 +4780,7 @@ Start:
                         return sub;
                     }
                     int number = ch - '0';
-                    Contract.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
+                    Debug.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
                     sub.value = sub.value * 10 + number;
                 }
                 else {
@@ -4829,8 +4799,8 @@ Start:
         }
 
         internal void ConsumeSubString(DTSubString sub) {
-            Contract.Assert(sub.index == Index, "sub.index == Index");
-            Contract.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len");
+            Debug.Assert(sub.index == Index, "sub.index == Index");
+            Debug.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len");
             Index = sub.index + sub.length;
             if (Index < len) {
                 m_current = Value[Index];
@@ -4875,7 +4845,6 @@ Start:
     //
     internal
     unsafe struct DateTimeRawInfo {
-        [SecurityCritical]
         private  int* num;
         internal int numCount;
         internal int month;
@@ -4889,7 +4858,6 @@ Start:
 
         internal bool timeZone;
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void Init(int * numberBuffer) {
             month      = -1;
             year       = -1;
@@ -4899,11 +4867,9 @@ Start:
             fraction = -1;
             num = numberBuffer;
         }
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe void AddNumber(int value) {
             num[numCount++] = value;
         }
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe int GetNumber(int index) {
             return num[index];
         }
index 728c44b..89ac780 100644 (file)
@@ -27,14 +27,12 @@ namespace System.Globalization {
         internal String m_bodyName;
         internal uint   m_flags;
     
-        [SecurityCritical]
         unsafe internal CodePageDataItem(int dataIndex) {
             m_dataIndex = dataIndex;
             m_uiFamilyCodePage = EncodingTable.codePageDataPtr[dataIndex].uiFamilyCodePage;
             m_flags = EncodingTable.codePageDataPtr[dataIndex].flags;
         }
 
-        [System.Security.SecurityCritical]
         unsafe internal static String CreateString(sbyte* pStrings, uint index)
         {
             if (pStrings[0] == '|') // |str1|str2|str3
@@ -71,7 +69,6 @@ namespace System.Globalization {
         }
 
         unsafe public String WebName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 if (m_webName==null) {
                     m_webName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 0);
@@ -87,7 +84,6 @@ namespace System.Globalization {
         }
     
         unsafe public String HeaderName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 if (m_headerName==null) {
                     m_headerName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 1);
@@ -97,7 +93,6 @@ namespace System.Globalization {
         }
     
         unsafe public String BodyName {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 if (m_bodyName==null) {
                     m_bodyName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 2);
index 1405e41..0fce2e5 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Text;
 
@@ -82,7 +83,7 @@ namespace System.Globalization
                     break;
             }
 
-            Contract.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage");
+            Debug.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage");
             return item;
         }
 
@@ -91,7 +92,7 @@ namespace System.Globalization
 #if DEBUG
         static EncodingTable()
         {
-            Contract.Assert(
+            Debug.Assert(
                 s_encodingDataTable.Count == EncodingTableCapacity,
                 string.Format(CultureInfo.InvariantCulture,
                     "EncodingTable s_encodingDataTable's initial capacity (EncodingTableCapacity) is incorrect.{0}Expected (s_encodingDataTable.Count): {1}, Actual (EncodingTableCapacity): {2}",
index 12da52e..d908a2a 100644 (file)
@@ -34,13 +34,11 @@ namespace System.Globalization
         //
         // This points to a native data table which maps an encoding name to the correct code page.        
         //
-        [SecurityCritical]
         unsafe internal static InternalEncodingDataItem *encodingDataPtr = GetEncodingData();
         //
         // This points to a native data table which stores the properties for the code page, and
         // the table is indexed by code page.
         //
-        [SecurityCritical]
         unsafe internal static InternalCodePageDataItem *codePageDataPtr = GetCodePageData();
         //
         // This caches the mapping of an encoding name to a code page.
@@ -51,14 +49,12 @@ namespace System.Globalization
         //
         private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable());
 
-        [System.Security.SecuritySafeCritical] // static constructors should be safe to call
         static EncodingTable()
         { 
         }
 
         // Find the data item by binary searching the table that we have in native.
         // nativeCompareOrdinalWC is an internal-only function.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe private static int internalGetCodePageFromName(String name) {
             int left  = 0;
             int right = lastEncodingItem;
@@ -98,7 +94,6 @@ namespace System.Globalization
         }
 
         // Return a list of all EncodingInfo objects describing all of our encodings
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static unsafe EncodingInfo[] GetEncodings()
         {
             if (lastCodePageItem == 0)
@@ -161,7 +156,6 @@ namespace System.Globalization
             return codePage;
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage) {
             CodePageDataItem dataItem;
 
@@ -198,22 +192,18 @@ namespace System.Globalization
             return null;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private unsafe static extern InternalEncodingDataItem *GetEncodingData();
         
         //
         // Return the number of encoding data items.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int GetNumEncodingItems();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private unsafe static extern InternalCodePageDataItem* GetCodePageData();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal unsafe static extern byte* nativeCreateOpenFileMapping(
             String inSectionName, int inBytesToAllocate, out IntPtr mappedFileHandle);   
@@ -228,7 +218,6 @@ namespace System.Globalization
     
     [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
     internal unsafe struct InternalEncodingDataItem {
-        [SecurityCritical]
         internal sbyte  * webName;
         internal UInt16   codePage;
     }
@@ -243,7 +232,6 @@ namespace System.Globalization
         internal UInt16   codePage;
         internal UInt16   uiFamilyCodePage;
         internal uint     flags;
-        [SecurityCritical]
         internal sbyte  * Names;
     }
 
index 4de3fd3..0810d67 100644 (file)
@@ -15,6 +15,7 @@ namespace System.Globalization {
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
     using System.IO;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     
@@ -32,10 +33,9 @@ namespace System.Globalization {
         // Instance data members and instance methods.
         //
         // ----------------------------------------------------------------------------------------------------
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static byte* GetGlobalizationResourceBytePtr(Assembly assembly, String tableName) {
-            Contract.Assert(assembly != null, "assembly can not be null.  This should be generally the "+System.CoreLib.Name+" assembly.");
-            Contract.Assert(tableName != null, "table name can not be null");
+            Debug.Assert(assembly != null, "assembly can not be null.  This should be generally the "+System.CoreLib.Name+" assembly.");
+            Debug.Assert(tableName != null, "table name can not be null");
             
             Stream stream = assembly.GetManifestResourceStream(tableName);
             UnmanagedMemoryStream bytesStream = stream as UnmanagedMemoryStream;
@@ -46,7 +46,7 @@ namespace System.Globalization {
                 }
             }
             
-            Contract.Assert(
+            Debug.Assert(
                     false, 
                     String.Format(
                         CultureInfo.CurrentCulture,
index 3772b0b..44cbdb8 100644 (file)
@@ -5,6 +5,7 @@
 namespace System.Globalization {
     using System;
     using System.Text;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     ////////////////////////////////////////////////////////////////////////////
@@ -607,7 +608,7 @@ namespace System.Globalization {
             //  is true.
             //
             NumDays -= (long)(LunarMonthLen[hebrewYearType, lunarDate.month] - lunarDate.day);
-            Contract.Assert(NumDays >= 1, "NumDays >= 1");
+            Debug.Assert(NumDays >= 1, "NumDays >= 1");
 
             // If NumDays is 1, then we are done.  Otherwise, find the correct Hebrew month
             // and day.
@@ -811,7 +812,7 @@ namespace System.Globalization {
             int hebrewYearType = GetHebrewYearType(year, era);
             CheckHebrewMonthValue(year, month, era);
 
-            Contract.Assert(hebrewYearType>= 1 && hebrewYearType <= 6,
+            Debug.Assert(hebrewYearType>= 1 && hebrewYearType <= 6,
                 "hebrewYearType should be from  1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year);
             int monthDays = LunarMonthLen[hebrewYearType, month];
             if (monthDays == 0) {
index cf05955..5517cb1 100644 (file)
@@ -6,6 +6,7 @@
 namespace System.Globalization {
     using System;
     using System.Text;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     ////////////////////////////////////////////////////////////////////////////
@@ -98,7 +99,7 @@ namespace System.Globalization {
                 Number -= 5000;
             }
 
-            Contract.Assert(Number > 0 && Number <= 999, "Number is out of range.");;
+            Debug.Assert(Number > 0 && Number <= 999, "Number is out of range.");;
 
             //
             //  Get the Hundreds.
index d19e77a..39a01e5 100644 (file)
@@ -209,7 +209,6 @@ namespace System.Globalization {
 
 
         public int HijriAdjustment {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 if (m_HijriAdvance == Int32.MinValue) {
                     // Never been set before.  Use the system value from registry.
@@ -252,7 +251,6 @@ namespace System.Globalization {
         **      "AddHijriDate+1"  =>  Add +1 days to the current calculated Hijri date.
         **      "AddHijriDate+2"  =>  Add +2 days to the current calculated Hijri date.
         ============================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated
         static int GetAdvanceHijriDate() {
 #if FEATURE_WIN32_REGISTRY
 
index 8035ff7..b161851 100644 (file)
@@ -65,6 +65,7 @@ namespace System.Globalization
     using System.Text;
     using System.Runtime.Versioning;
     using System.Runtime.InteropServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // IdnMapping class used to map names to Punycode
@@ -160,7 +161,7 @@ namespace System.Globalization
 
             // Cannot be null terminated (normalization won't help us with this one, and
             // may have returned false before checking the whole string above)
-            Contract.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now.");
+            Debug.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now.");
             if (unicode[unicode.Length - 1] <= 0x1f)
             {
                 throw new ArgumentException(
@@ -191,7 +192,6 @@ namespace System.Globalization
         }
 
 
-        [System.Security.SecuritySafeCritical]
         private String GetAsciiUsingOS(String unicode)
         {
             if (unicode.Length == 0)
@@ -294,7 +294,6 @@ namespace System.Globalization
         }
 
         
-        [System.Security.SecuritySafeCritical]
         private string GetUnicodeUsingOS(string ascii)
         {
             uint flags =  (uint)((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
@@ -509,7 +508,7 @@ namespace System.Globalization
 
         static char encode_digit(int d)
         {
-            Contract.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
+            Debug.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
             // 26-35 map to ASCII 0-9
             if (d > 25) return (char)(d - 26 + '0');
 
@@ -546,7 +545,7 @@ namespace System.Globalization
             uint k;
 
             delta = firsttime ? delta / damp : delta / 2;
-            Contract.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
+            Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
             delta += delta / numpoints;
 
             for (k = 0;  delta > ((punycodeBase - tmin) * tmax) / 2;  k += punycodeBase)
@@ -554,7 +553,7 @@ namespace System.Globalization
               delta /= punycodeBase - tmin;
             }
 
-            Contract.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
+            Debug.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
             return (int)(k + (punycodeBase - tmin + 1) * delta / (delta + skew));
         }
 
@@ -604,7 +603,7 @@ namespace System.Globalization
             {
                 // Find end of this segment
                 iNextDot = unicode.IndexOfAny(M_Dots, iAfterLastDot);
-                Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
+                Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
                 if (iNextDot < 0)
                     iNextDot = unicode.Length;
 
@@ -654,7 +653,7 @@ namespace System.Globalization
                 for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++)
                 {
                     // Can't be lonely surrogate because it would've thrown in normalization
-                    Contract.Assert(Char.IsLowSurrogate(unicode, basicCount) == false,
+                    Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false,
                         "[IdnMapping.punycode_encode]Unexpected low surrogate");
 
                     // Double check our bidi rules
@@ -738,7 +737,7 @@ namespace System.Globalization
                         /* Increase delta enough to advance the decoder's    */
                         /* <n,i> state to <m,0>, but guard against overflow: */
                         delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1));
-                        Contract.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
+                        Debug.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
                         n = m;
 
                         for (j = iAfterLastDot;  j < iNextDot;  j+= IsSupplementary(test) ? 2 : 1)
@@ -752,7 +751,7 @@ namespace System.Globalization
                             if (test < n)
                             {
                                 delta++;
-                                Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
+                                Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
                             }
 
                             if (test == n)
@@ -764,7 +763,7 @@ namespace System.Globalization
                                     int t = k <= bias ? tmin :
                                             k >= bias + tmax ? tmax : k - bias;
                                     if (q < t) break;
-                                    Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t");
+                                    Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t");
 
                                     int mod;
                                     q = Math.DivRem(q - t, punycodeBase - t, out mod);
@@ -785,7 +784,7 @@ namespace System.Globalization
                         }
                         ++delta;
                         ++n;
-                        Contract.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int");
+                        Debug.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int");
                     }
                 }
 
@@ -976,7 +975,7 @@ namespace System.Globalization
                             // decode the digit from the next char
                             int digit = decode_digit(ascii[asciiIndex++]);
 
-                            Contract.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
+                            Debug.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
                             if (digit > (maxint - i) / w)
                                 throw new ArgumentException(Environment.GetResourceString(
                                     "Argument_IdnBadPunycode"), nameof(ascii));
@@ -985,7 +984,7 @@ namespace System.Globalization
                             int t = k <= bias ? tmin :
                                     k >= bias + tmax ? tmax : k - bias;
                             if (digit < t) break;
-                            Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)");
+                            Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)");
                             if (w > maxint / (punycodeBase - t))
                                 throw new ArgumentException(Environment.GetResourceString(
                                     "Argument_IdnBadPunycode"), nameof(ascii));
@@ -997,7 +996,7 @@ namespace System.Globalization
 
                         /* i was supposed to wrap around from output.Length to 0,   */
                         /* incrementing n each time, so we'll fix that now: */
-                        Contract.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
+                        Debug.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
                             "[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment");
                         if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > maxint - n)
                             throw new ArgumentException(Environment.GetResourceString(
@@ -1158,7 +1157,6 @@ namespace System.Globalization
         private const int ERROR_INVALID_NAME = 123;
 
 
-        [System.Security.SecurityCritical]
         [SuppressUnmanagedCodeSecurityAttribute()]
         [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
         private static extern int IdnToAscii(
@@ -1172,7 +1170,6 @@ namespace System.Globalization
                                         char    [] lpASCIICharStr, 
                                         int     cchASCIIChar);
 
-        [System.Security.SecurityCritical]
         [SuppressUnmanagedCodeSecurityAttribute()]
         [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
         private static extern int IdnToUnicode(
index 07642b4..6b168ce 100644 (file)
@@ -159,7 +159,6 @@ namespace System.Globalization {
         // . is a delimiter, but the value of . doesn't matter.
         // '_' marks the space between the japanese era name, japanese abbreviated era name
         //     english name, and abbreviated english names.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static EraInfo[] GetErasFromRegistry()
         {
             // Look in the registry key and see if we can find any ranges
index bdd4dfc..a5dce46 100644 (file)
@@ -120,28 +120,8 @@ namespace System.Globalization {
         [OnSerializing]
         private void OnSerializing(StreamingContext ctx)
         {
-#if !FEATURE_CORECLR
-            // Update these legacy flags, so that 1.1/2.0 versions of the framework
-            // can still throw while parsing; even when using a de-serialized
-            // NumberFormatInfo from a 4.0+ version of the framework
-            if (numberDecimalSeparator != numberGroupSeparator) {
-                validForParseAsNumber = true;
-            } else {
-                validForParseAsNumber = false;
-            }
-
-            if ((numberDecimalSeparator != numberGroupSeparator) &&
-                (numberDecimalSeparator != currencyGroupSeparator) &&
-                (currencyDecimalSeparator != numberGroupSeparator) &&
-                (currencyDecimalSeparator != currencyGroupSeparator)) {
-                validForParseAsCurrency = true;
-            } else {
-                validForParseAsCurrency = false;
-            }
-#endif // !FEATURE_CORECLR
         }
 
-
         [OnDeserializing]
         private void OnDeserializing(StreamingContext ctx)
         {
@@ -153,7 +133,6 @@ namespace System.Globalization {
         }
 #endregion Serialization
 
-
         static private void VerifyDecimalSeparator(String decSep, String propertyName) {
             if (decSep==null) {
                 throw new ArgumentNullException(propertyName,
@@ -231,7 +210,6 @@ namespace System.Globalization {
 
         // We aren't persisting dataItem any more (since its useless & we weren't using it),
         // Ditto with m_useUserOverride.  Don't use them, we use a local copy of everything.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal NumberFormatInfo(CultureData cultureData)
         {
             if (cultureData != null)
index ff15699..e61a007 100644 (file)
@@ -4,6 +4,7 @@
 
 namespace System.Globalization {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     ////////////////////////////////////////////////////////////////////////////
@@ -185,7 +186,7 @@ namespace System.Globalization {
 
         static int MonthFromOrdinalDay(int ordinalDay)
         {
-            Contract.Assert(ordinalDay <= 366);
+            Debug.Assert(ordinalDay <= 366);
             int index = 0;
             while (ordinalDay > DaysToMonth[index])
                 index++;
@@ -195,7 +196,7 @@ namespace System.Globalization {
 
         static int DaysInPreviousMonths(int month)
         {
-            Contract.Assert(1 <= month && month <= 12);
+            Debug.Assert(1 <= month && month <= 12);
             --month; // months are one based but for calculations use 0 based
             return DaysToMonth[month];
         }
@@ -225,7 +226,7 @@ namespace System.Globalization {
 
             long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
             int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
-            Contract.Assert(y >= 1);
+            Debug.Assert(y >= 1);
 
             if (part == DatePartYear)
             {
@@ -244,16 +245,16 @@ namespace System.Globalization {
             }
 
             int m = MonthFromOrdinalDay(ordinalDay);
-            Contract.Assert(ordinalDay >= 1);
-            Contract.Assert(m >= 1 && m <= 12);
+            Debug.Assert(ordinalDay >= 1);
+            Debug.Assert(m >= 1 && m <= 12);
             if (part == DatePartMonth)
             {
                 return m;
             }
 
             int d = ordinalDay - DaysInPreviousMonths(m);
-            Contract.Assert(1 <= d);
-            Contract.Assert(d <= 31);
+            Debug.Assert(1 <= d);
+            Debug.Assert(d <= 31);
 
             //
             //  Calculate the Persian Day.
@@ -377,7 +378,7 @@ namespace System.Globalization {
             int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
             if ((month == MonthsPerYear) && !IsLeapYear(year))
             {
-                Contract.Assert(daysInMonth == 30);
+                Debug.Assert(daysInMonth == 30);
                 --daysInMonth;
             }
             return daysInMonth;
index d635458..4bed875 100644 (file)
@@ -19,6 +19,7 @@ namespace System.Globalization {
 
     using System;
     using System.Runtime.Serialization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable] 
@@ -59,7 +60,6 @@ namespace System.Globalization {
         //  In Silverlight we enforce that RegionInfos must be created with a full culture name
         //
         ////////////////////////////////////////////////////////////////////////
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public RegionInfo(String name) {
             if (name==null)
                 throw new ArgumentNullException(nameof(name));
@@ -95,7 +95,6 @@ namespace System.Globalization {
 
 #if FEATURE_USE_LCID
         // We'd rather people use the named version since this doesn't allow custom locales
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public RegionInfo(int culture)
         {
             if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region
@@ -127,28 +126,17 @@ namespace System.Globalization {
         }
 #endif
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal RegionInfo(CultureData cultureData)
         {
             this.m_cultureData = cultureData;
             this.m_name = this.m_cultureData.SREGIONNAME;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetName(string name)
         {
-#if FEATURE_CORECLR
             // Use the name of the region we found
             this.m_name = this.m_cultureData.SREGIONNAME;
-#else
-            // when creating region by culture name, we keep the region name as the culture name so regions
-            // created by custom culture names can be differentiated from built in regions.
-            this.m_name = name.Equals(this.m_cultureData.SREGIONNAME, StringComparison.OrdinalIgnoreCase) ? 
-                                this.m_cultureData.SREGIONNAME : 
-                                this.m_cultureData.CultureName;
-#endif // FEATURE_CORECLR
         }
-        
 
 #region Serialization 
         //
@@ -163,169 +151,12 @@ namespace System.Globalization {
         [OptionalField(VersionAdded = 2)]
         internal int m_dataItem = 0;
 
-#if !FEATURE_CORECLR
-        static private readonly int[] IdFromEverettRegionInfoDataItem =
-        {
-            0x3801, /*  0 */  // AE          ar-AE      Arabic (U.A.E.)
-            0x041C, /*  1 */  // AL          sq-AL      Albanian (Albania)
-            0x042B, /*  2 */  // AM          hy-AM      Armenian (Armenia)
-            0x2C0A, /*  3 */  // AR          es-AR      Spanish (Argentina)
-            0x0C07, /*  4 */  // AT          de-AT      German (Austria)
-            0x0C09, /*  5 */  // AU          en-AU      English (Australia)
-            0x042C, /*  6 */  // AZ          az-AZ-Latn Azeri (Latin) (Azerbaijan)
-        //  0x082C,     6,    // AZ          az-AZ-Cyrl Azeri (Cyrillic) (Azerbaijan)
-            0x080C, /*  7 */  // BE          fr-BE      French (Belgium)
-        //  0x0813,     7,    // BE          nl-BE      Dutch (Belgium)
-            0x0402, /*  8 */  // BG          bg-BG      Bulgarian (Bulgaria)
-            0x3C01, /*  9 */  // BH          ar-BH      Arabic (Bahrain)
-            0x083E, /* 10 */  // BN          ms-BN      Malay (Brunei Darussalam)
-            0x400A, /* 11 */  // BO          es-BO      Spanish (Bolivia)
-            0x0416, /* 12 */  // BR          pt-BR      Portuguese (Brazil)
-            0x0423, /* 13 */  // BY          be-BY      Belarusian (Belarus)
-            0x2809, /* 14 */  // BZ          en-BZ      English (Belize)
-            0x0C0C, /* 15 */  // CA          fr-CA      French (Canada)
-        //  0x1009,    15,    // CA          en-CA      English (Canada)
-            0x2409, /* 16 */  // CB          en-CB      English (Caribbean)
-            0x0807, /* 17 */  // CH          de-CH      German (Switzerland)
-        //  0x0810,    17,    // CH          it-CH      Italian (Switzerland)
-        //  0x100C,    17,    // CH          fr-CH      French (Switzerland)
-            0x340A, /* 18 */  // CL          es-CL      Spanish (Chile)
-            0x0804, /* 19 */  // CN          zh-CN      Chinese (People's Republic of China)
-            0x240A, /* 20 */  // CO          es-CO      Spanish (Colombia)
-            0x140A, /* 21 */  // CR          es-CR      Spanish (Costa Rica)
-            0x0405, /* 22 */  // CZ          cs-CZ      Czech (Czech Republic)
-            0x0407, /* 23 */  // DE          de-DE      German (Germany)
-            0x0406, /* 24 */  // DK          da-DK      Danish (Denmark)
-            0x1C0A, /* 25 */  // DO          es-DO      Spanish (Dominican Republic)
-            0x1401, /* 26 */  // DZ          ar-DZ      Arabic (Algeria)
-            0x300A, /* 27 */  // EC          es-EC      Spanish (Ecuador)
-            0x0425, /* 28 */  // EE          et-EE      Estonian (Estonia)
-            0x0C01, /* 29 */  // EG          ar-EG      Arabic (Egypt)
-            0x0403, /* 30 */  // ES          ca-ES      Catalan (Catalan)
-        //  0x042D,    30,    // ES          eu-ES      Basque (Basque)
-        //  0x0456,    30,    // ES          gl-ES      Galician (Galician)
-        //  0x0C0A,    30,    // ES          es-ES      Spanish (Spain)
-            0x040B, /* 31 */  // FI          fi-FI      Finnish (Finland)
-        //  0x081D,    31,    // FI          sv-FI      Swedish (Finland)
-            0x0438, /* 32 */  // FO          fo-FO      Faroese (Faroe Islands)
-            0x040C, /* 33 */  // FR          fr-FR      French (France)
-            0x0809, /* 34 */  // GB          en-GB      English (United Kingdom)
-            0x0437, /* 35 */  // GE          ka-GE      Georgian (Georgia)
-            0x0408, /* 36 */  // GR          el-GR      Greek (Greece)
-            0x100A, /* 37 */  // GT          es-GT      Spanish (Guatemala)
-            0x0C04, /* 38 */  // HK          zh-HK      Chinese (Hong Kong S.A.R.)
-            0x480A, /* 39 */  // HN          es-HN      Spanish (Honduras)
-            0x041A, /* 40 */  // HR          hr-HR      Croatian (Croatia)
-            0x040E, /* 41 */  // HU          hu-HU      Hungarian (Hungary)
-            0x0421, /* 42 */  // ID          id-ID      Indonesian (Indonesia)
-            0x1809, /* 43 */  // IE          en-IE      English (Ireland)
-            0x040D, /* 44 */  // IL          he-IL      Hebrew (Israel)
-            0x0439, /* 45 */  // IN          hi-IN      Hindi (India)
-        //  0x0446,    45,    // IN          pa-IN      Punjabi (India)
-        //  0x0447,    45,    // IN          gu-IN      Gujarati (India)
-        //  0x0449,    45,    // IN          ta-IN      Tamil (India)
-        //  0x044A,    45,    // IN          te-IN      Telugu (India)
-        //  0x044B,    45,    // IN          kn-IN      Kannada (India)
-        //  0x044E,    45,    // IN          mr-IN      Marathi (India)
-        //  0x044F,    45,    // IN          sa-IN      Sanskrit (India)
-        //  0x0457,    45,    // IN          kok-IN     Konkani (India)
-            0x0801, /* 46 */  // IQ          ar-IQ      Arabic (Iraq)
-            0x0429, /* 47 */  // IR          fa-IR      (Iran)
-            0x040F, /* 48 */  // IS          is-IS      Icelandic (Iceland)
-            0x0410, /* 49 */  // IT          it-IT      Italian (Italy)
-            0x2009, /* 50 */  // JM          en-JM      English (Jamaica)
-            0x2C01, /* 51 */  // JO          ar-JO      Arabic (Jordan)
-            0x0411, /* 52 */  // JP          ja-JP      Japanese (Japan)
-            0x0441, /* 53 */  // KE          sw-KE      Swahili (Kenya)
-            0x0440, /* 54 */  // KG          ky-KG      Kyrgyz (Kyrgyzstan)
-            0x0412, /* 55 */  // KR          ko-KR      Korean (Korea)
-            0x3401, /* 56 */  // KW          ar-KW      Arabic (Kuwait)
-            0x043F, /* 57 */  // KZ          kk-KZ      Kazakh (Kazakhstan)
-            0x3001, /* 58 */  // LB          ar-LB      Arabic (Lebanon)
-            0x1407, /* 59 */  // LI          de-LI      German (Liechtenstein)
-            0x0427, /* 60 */  // LT          lt-LT      Lithuanian (Lithuania)
-            0x1007, /* 61 */  // LU          de-LU      German (Luxembourg)
-        //  0x140C,    61,    // LU          fr-LU      French (Luxembourg)
-            0x0426, /* 62 */  // LV          lv-LV      Latvian (Latvia)
-            0x1001, /* 63 */  // LY          ar-LY      Arabic (Libya)
-            0x1801, /* 64 */  // MA          ar-MA      Arabic (Morocco)
-            0x180C, /* 65 */  // MC          fr-MC      French (Principality of Monaco)
-            0x042F, /* 66 */  // MK          mk-MK      Macedonian (Macedonia, FYRO)
-            0x0450, /* 67 */  // MN          mn-MN      Mongolian (Mongolia)
-            0x1404, /* 68 */  // MO          zh-MO      Chinese (Macau S.A.R.)
-            0x0465, /* 69 */  // MV          div-MV     Divehi (Maldives)
-            0x080A, /* 70 */  // MX          es-MX      Spanish (Mexico)
-            0x043E, /* 71 */  // MY          ms-MY      Malay (Malaysia)
-            0x4C0A, /* 72 */  // NI          es-NI      Spanish (Nicaragua)
-            0x0413, /* 73 */  // NL          nl-NL      Dutch (Netherlands)
-            0x0414, /* 74 */  // NO          nb-NO      Norwegian (Bokm?) (Norway)
-        //  0x0814,    74,    // NO          nn-NO      Norwegian (Nynorsk) (Norway)
-            0x1409, /* 75 */  // NZ          en-NZ      English (New Zealand)
-            0x2001, /* 76 */  // OM          ar-OM      Arabic (Oman)
-            0x180A, /* 77 */  // PA          es-PA      Spanish (Panama)
-            0x280A, /* 78 */  // PE          es-PE      Spanish (Peru)
-            0x3409, /* 79 */  // PH          en-PH      English (Republic of the Philippines)
-            0x0420, /* 80 */  // PK          ur-PK      Urdu (Islamic Republic of Pakistan)
-            0x0415, /* 81 */  // PL          pl-PL      Polish (Poland)
-            0x500A, /* 82 */  // PR          es-PR      Spanish (Puerto Rico)
-            0x0816, /* 83 */  // PT          pt-PT      Portuguese (Portugal)
-            0x3C0A, /* 84 */  // PY          es-PY      Spanish (Paraguay)
-            0x4001, /* 85 */  // QA          ar-QA      Arabic (Qatar)
-            0x0418, /* 86 */  // RO          ro-RO      Romanian (Romania)
-            0x0419, /* 87 */  // RU          ru-RU      Russian (Russia)
-        //  0x0444,    87,    // RU          tt-RU      Tatar (Russia)
-            0x0401, /* 88 */  // SA          ar-SA      Arabic (Saudi Arabia)
-            0x041D, /* 89 */  // SE          sv-SE      Swedish (Sweden)
-            0x1004, /* 90 */  // SG          zh-SG      Chinese (Singapore)
-            0x0424, /* 91 */  // SI          sl-SI      Slovenian (Slovenia)
-            0x041B, /* 92 */  // SK          sk-SK      Slovak (Slovakia)
-            0x081A, /* 93 */  // SP          sr-SP-Latn Serbian (Latin) (Serbia)
-        //  0x0C1A,    93,    // SP          sr-SP-Cyrl Serbian (Cyrillic) (Serbia)
-            0x440A, /* 94 */  // SV          es-SV      Spanish (El Salvador)
-            0x045A, /* 95 */  // SY          syr-SY     Syriac (Syria)
-        //  0x2801,    95,    // SY          ar-SY      Arabic (Syria)
-            0x041E, /* 96 */  // TH          th-TH      Thai (Thailand)
-            0x1C01, /* 97 */  // TN          ar-TN      Arabic (Tunisia)
-            0x041F, /* 98 */  // TR          tr-TR      Turkish (Turkey)
-            0x2C09, /* 99 */  // TT          en-TT      English (Trinidad and Tobago)
-            0x0404, /*100 */  // TW          zh-TW      Chinese (Taiwan)
-            0x0422, /*101 */  // UA          uk-UA      Ukrainian (Ukraine)
-            0x0409, /*102 */  // US          en-US      English (United States)
-            0x380A, /*103 */  // UY          es-UY      Spanish (Uruguay)
-            0x0443, /*104 */  // UZ          uz-UZ-Latn Uzbek (Latin) (Uzbekistan)
-        //  0x0843,   104     // UZ          uz-UZ-Cyrl Uzbek (Cyrillic) (Uzbekistan)
-            0x200A, /*105*/   // VE          es-VE      Spanish (Venezuela)
-            0x042A, /*106*/   // VN          vi-VN      Vietnamese (Viet Nam)
-            0x2401, /*107*/   // YE          ar-YE      Arabic (Yemen)
-            0x0436, /*108*/   // ZA          af-ZA      Afrikaans (South Africa)
-        //  0x1C09,   108,    // ZA          en-ZA      English (South Africa)
-            0x3009, /*109*/   // ZW          en-ZW      English (Zimbabwe)
-        };
-#endif
-        [System.Security.SecurityCritical]  // auto-generated
         [OnDeserialized]
         private void OnDeserialized(StreamingContext ctx)
         {
-#if FEATURE_CORECLR
             // This won't happen anyway since CoreCLR doesn't support serialization
             this.m_cultureData = CultureData.GetCultureData(m_name, true);
-#else
-            if (m_name == null)
-            {
-                Contract.Assert(m_dataItem >= 0, "[RegionInfo.OnDeserialized] null name and invalid dataItem");
-                m_cultureId = IdFromEverettRegionInfoDataItem[m_dataItem];
-            }
 
-            if (m_cultureId == 0)
-            {
-                this.m_cultureData = CultureData.GetCultureDataForRegion(this.m_name, true);
-            }
-            else
-            {
-                this.m_cultureData = CultureData.GetCultureData(m_cultureId, true);
-            }
-                
-#endif
             if (this.m_cultureData == null)
                 throw new ArgumentException(
                     String.Format(
@@ -359,7 +190,6 @@ namespace System.Globalization {
         //
         ////////////////////////////////////////////////////////////////////////
         public static RegionInfo CurrentRegion {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 RegionInfo temp = s_currentRegionInfo;
                 if (temp == null)
@@ -383,7 +213,7 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
         public virtual String Name {
             get {
-                Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
+                Debug.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
                 return (m_name);
             }
         }
@@ -397,7 +227,6 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
         public virtual String EnglishName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return (this.m_cultureData.SENGCOUNTRY);
@@ -415,7 +244,6 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
         public virtual String DisplayName 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get 
             {
                 return (this.m_cultureData.SLOCALIZEDCOUNTRY);
@@ -434,7 +262,6 @@ namespace System.Globalization {
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual String NativeName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return (this.m_cultureData.SNATIVECOUNTRY);
@@ -450,7 +277,6 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
         public virtual String TwoLetterISORegionName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return (this.m_cultureData.SISO3166CTRYNAME);
@@ -467,7 +293,6 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
         public virtual String ThreeLetterISORegionName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return (this.m_cultureData.SISO3166CTRYNAME2);
@@ -483,7 +308,6 @@ namespace System.Globalization {
         ////////////////////////////////////////////////////////////////////////
         public virtual String ThreeLetterWindowsRegionName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return (this.m_cultureData.SABBREVCTRYNAME);
@@ -524,7 +348,6 @@ namespace System.Globalization {
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual String CurrencyEnglishName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return (this.m_cultureData.SENGLISHCURRENCY);
@@ -542,7 +365,6 @@ namespace System.Globalization {
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual String CurrencyNativeName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return (this.m_cultureData.SNATIVECURRENCY);
@@ -557,7 +379,6 @@ namespace System.Globalization {
         //
         ////////////////////////////////////////////////////////////////////////
         public virtual String CurrencySymbol {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return (this.m_cultureData.SCURRENCY);
             }
@@ -571,7 +392,6 @@ namespace System.Globalization {
         //
         ////////////////////////////////////////////////////////////////////////
         public virtual String ISOCurrencySymbol {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return (this.m_cultureData.SINTLSYMBOL);
             }
index 62207c2..9c35f48 100644 (file)
@@ -16,6 +16,7 @@ namespace System.Globalization {
     using System;
     using System.Runtime.CompilerServices;
     using System.Runtime.Serialization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [System.Runtime.InteropServices.ComVisible(true)]
@@ -126,8 +127,8 @@ namespace System.Globalization {
             byte[] key1Data = sortkey1.m_KeyData;
             byte[] key2Data = sortkey2.m_KeyData;
     
-            Contract.Assert(key1Data!=null, "key1Data!=null");
-            Contract.Assert(key2Data!=null, "key2Data!=null");
+            Debug.Assert(key1Data!=null, "key1Data!=null");
+            Debug.Assert(key2Data!=null, "key2Data!=null");
 
             if (key1Data.Length == 0) {
                 if (key2Data.Length == 0) {
index 40b2f92..d86e115 100644 (file)
@@ -17,6 +17,7 @@ namespace System.Globalization {
     using System;
     using System.Runtime.Serialization;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -206,8 +207,8 @@ namespace System.Globalization {
         
         internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
         {
-            Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
-            Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+            Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+            Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
             if (index + currentCharCount == len)
             {
                 // This is the last character/surrogate in the string.
index 5f47f5f..049ccf6 100644 (file)
@@ -15,6 +15,7 @@ using System.Runtime.Serialization;
 
 namespace System.Globalization {
     using System.Collections;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     //
@@ -43,9 +44,9 @@ namespace System.Globalization {
 
         internal TextElementEnumerator(String str, int startIndex, int strLen)
         {
-            Contract.Assert(str != null, "TextElementEnumerator(): str != null");
-            Contract.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
-            Contract.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
+            Debug.Assert(str != null, "TextElementEnumerator(): str != null");
+            Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
+            Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
             this.str = str;
             this.startIndex = startIndex;
             this.strLen = strLen;
index 4fa9f66..c8108e4 100644 (file)
@@ -24,6 +24,7 @@ namespace System.Globalization {
     using System.Runtime.Serialization;
     using System.Runtime.Versioning;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
 
@@ -106,11 +107,6 @@ namespace System.Globalization {
             this.m_cultureData = cultureData;
             this.m_cultureName = this.m_cultureData.CultureName;
             this.m_textInfoName = this.m_cultureData.STEXTINFO;
-#if !FEATURE_CORECLR
-            IntPtr handleOrigin;
-            this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin);
-            this.m_handleOrigin = handleOrigin;
-#endif
         }
 
         ////////////////////////////////////////////////////////////////////////
@@ -179,30 +175,18 @@ namespace System.Globalization {
                 // Get the text info name belonging to that culture
                 this.m_cultureData = CultureInfo.GetCultureInfo(m_cultureName).m_cultureData;
                 this.m_textInfoName = this.m_cultureData.STEXTINFO;
-#if !FEATURE_CORECLR
-                IntPtr handleOrigin;
-                this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin);
-                this.m_handleOrigin = handleOrigin;
-#endif
-            }            
+            }
         }
 
-        
         [OnDeserialized]
         private void OnDeserialized(StreamingContext ctx)
         {
             OnDeserialized();
-        }   
-        
+        }
+
         [OnSerializing]
         private void OnSerializing(StreamingContext ctx) 
-        { 
-#if !FEATURE_CORECLR
-            // Initialize the fields Whidbey expects:
-            // Whidbey expected this, so set it, but the value doesn't matter much
-            this.m_useUserOverride = false;
-#endif // FEATURE_CORECLR
-
+        {
             // Relabel our name since Whidbey expects it to be called customCultureName
             this.customCultureName = this.m_cultureName;
 
@@ -229,7 +213,6 @@ namespace System.Globalization {
             return (Invariant.GetCaseInsensitiveHashCode(s, forceRandomizedHashing, additionalEntropy));
         }
 
-        [System.Security.SecuritySafeCritical]
         internal static unsafe bool TryFastFindStringOrdinalIgnoreCase(int searchFlags, String source, int startIndex, String value, int count, ref int foundIndex)
         {
             return InternalTryFindStringOrdinalIgnoreCase(searchFlags, source, count, startIndex, value, value.Length, ref foundIndex);
@@ -237,7 +220,6 @@ namespace System.Globalization {
 
         // This function doesn't check arguments. Please do check in the caller.
         // The underlying unmanaged code will assert the sanity of arguments.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static unsafe int CompareOrdinalIgnoreCase(String str1, String str2)
         {
             // Compare the whole string and ignore case.
@@ -246,19 +228,18 @@ namespace System.Globalization {
 
         // This function doesn't check arguments. Please do check in the caller.
         // The underlying unmanaged code will assert the sanity of arguments.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static unsafe int CompareOrdinalIgnoreCaseEx(String strA, int indexA, String strB, int indexB, int lengthA, int lengthB )
         {
-            Contract.Assert(strA.Length >= indexA + lengthA,  "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA");
-            Contract.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx]  Caller should've validated strB.Length >= indexB + lengthB");
+            Debug.Assert(strA.Length >= indexA + lengthA,  "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA");
+            Debug.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx]  Caller should've validated strB.Length >= indexB + lengthB");
             return InternalCompareStringOrdinalIgnoreCase(strA, indexA, strB, indexB, lengthA, lengthB);
         }
 
         internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
         {
-            Contract.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
-            Contract.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
-            Contract.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length");
+            Debug.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
+            Debug.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
+            Debug.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length");
 
             // We return 0 if both inputs are empty strings
             if (source.Length == 0 && value.Length == 0)
@@ -285,7 +266,7 @@ namespace System.Globalization {
             for (; startIndex <= maxStartIndex; startIndex++)
             {
                 // We should always have the same or more characters left to search than our actual pattern
-                Contract.Assert(end - startIndex >= value.Length);
+                Debug.Assert(end - startIndex >= value.Length);
                 // since this is an ordinal comparison, we can assume that the lengths must match
                 if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0)
                 {
@@ -299,10 +280,10 @@ namespace System.Globalization {
 
         internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
         {
-            Contract.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
-            Contract.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
-            Contract.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0");
-            Contract.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length");
+            Debug.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
+            Debug.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
+            Debug.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0");
+            Debug.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length");
 
             // If value is Empty, the return value is startIndex
             if (value.Length == 0)
@@ -498,7 +479,6 @@ namespace System.Globalization {
 
         public virtual String ListSeparator 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get 
             {
                 if (m_listSeparator == null) {
@@ -529,7 +509,6 @@ namespace System.Globalization {
         //
         ////////////////////////////////////////////////////////////////////////
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual char ToLower(char c) 
         {
             if(IsAscii(c) && IsAsciiCasingSameAsInvariant)
@@ -539,7 +518,6 @@ namespace System.Globalization {
             return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, false));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual String ToLower(String str) 
         {
             if (str == null) { throw new ArgumentNullException(nameof(str)); }
@@ -567,7 +545,6 @@ namespace System.Globalization {
         //
         ////////////////////////////////////////////////////////////////////////
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual char ToUpper(char c) 
         {
             if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
@@ -578,7 +555,6 @@ namespace System.Globalization {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual String ToUpper(String str) 
         {
             if (str == null) { throw new ArgumentNullException(nameof(str)); }
@@ -809,7 +785,7 @@ namespace System.Globalization {
 
         private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) 
         {
-            Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+            Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
             if (charLen == 2) 
             {
                 // Surrogate pair
@@ -826,7 +802,7 @@ namespace System.Globalization {
 
         private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) 
         {
-            Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+            Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
 
             // for surrogate pairs do a simple ToUpper operation on the substring
             if (charLen == 2) 
@@ -947,13 +923,11 @@ namespace System.Globalization {
         // is not null before calling this.  Currenlty, CaseInsensitiveHashCodeProvider
         // does that.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe int GetCaseInsensitiveHashCode(String str)
         {
             return GetCaseInsensitiveHashCode(str, false, 0);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe int GetCaseInsensitiveHashCode(String str, bool forceRandomizedHashing, long additionalEntropy)
         {
             // Validate inputs
@@ -968,23 +942,19 @@ namespace System.Globalization {
         }
 
         // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseChar
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static unsafe extern char InternalChangeCaseChar(IntPtr handle, IntPtr handleOrigin, String localeName, char ch, bool isToUpper);
         
         // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseString
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static unsafe extern String InternalChangeCaseString(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool isToUpper);
 
         // Get case insensitive hash -- ComNlsInfo::InternalGetCaseInsHash
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static unsafe extern int InternalGetCaseInsHash(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool forceRandomizedHashing, long additionalEntropy);
 
         // Call ::CompareStringOrdinal -- ComNlsInfo::InternalCompareStringOrdinalIgnoreCase
         // Start at indexes and compare for length characters (or remainder of string if length == -1)
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static unsafe extern int InternalCompareStringOrdinalIgnoreCase(String string1, int index1, String string2, int index2, int length1, int length2);
@@ -992,7 +962,6 @@ namespace System.Globalization {
         // ComNlsInfo::InternalTryFindStringOrdinalIgnoreCase attempts a faster IndexOf/LastIndexOf OrdinalIgnoreCase using a kernel function.
         // Returns true if FindStringOrdinal was handled, with foundIndex set to the target's index into the source
         // Returns false when FindStringOrdinal wasn't handled
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
index 8f58623..e5e615f 100644 (file)
@@ -6,12 +6,12 @@
 namespace System.Globalization {
     using System.Text;
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Globalization;
 
     internal static class TimeSpanFormat {
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static String IntToString(int n, int digits) {
             return ParseNumbers.IntToString(n, 10, digits, '0', 0);
         }
@@ -143,7 +143,7 @@ namespace System.Globalization {
         // 
         internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi) {                      
 
-            Contract.Assert(dtfi != null, "dtfi == null");
+            Debug.Assert(dtfi != null, "dtfi == null");
 
             int day = (int)(value._ticks / TimeSpan.TicksPerDay);
             long time = value._ticks % TimeSpan.TicksPerDay;
@@ -369,7 +369,7 @@ namespace System.Globalization {
                         case '\"':
                             if (inQuote && (quote == format[i])) {
                                 /* we were in a quote and found a matching exit quote, so we are outside a quote now */
-                                Contract.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5");
+                                Debug.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5");
                                 if (field >= 0 && field <= 5) {
                                     literals[field] = sb.ToString();
                                     sb.Length = 0;
@@ -389,7 +389,7 @@ namespace System.Globalization {
                             }
                             break;
                         case '%':
-                            Contract.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+                            Debug.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                             goto default;
                         case '\\':
                             if (!inQuote) {
@@ -399,7 +399,7 @@ namespace System.Globalization {
                             goto default;
                         case 'd':
                             if (!inQuote) {
-                                Contract.Assert((field == 0 && sb.Length == 0) || field == 1,
+                                Debug.Assert((field == 0 && sb.Length == 0) || field == 1,
                                                 "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                                 field = 1; // DayHourSep
                                 dd++;
@@ -407,7 +407,7 @@ namespace System.Globalization {
                             break;
                         case 'h':
                             if (!inQuote) {
-                                Contract.Assert((field == 1 && sb.Length == 0) || field == 2,
+                                Debug.Assert((field == 1 && sb.Length == 0) || field == 2,
                                                 "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                                 field = 2; // HourMinuteSep
                                 hh++;
@@ -415,7 +415,7 @@ namespace System.Globalization {
                             break;
                         case 'm':
                             if (!inQuote) {
-                                Contract.Assert((field == 2 && sb.Length == 0) || field == 3,
+                                Debug.Assert((field == 2 && sb.Length == 0) || field == 3,
                                                 "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                                 field = 3; // MinuteSecondSep
                                 mm++;
@@ -423,7 +423,7 @@ namespace System.Globalization {
                             break;
                         case 's':
                             if (!inQuote) {
-                                Contract.Assert((field == 3 && sb.Length == 0) || field == 4,
+                                Debug.Assert((field == 3 && sb.Length == 0) || field == 4,
                                                 "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                                 field = 4; // SecondFractionSep
                                 ss++;
@@ -432,7 +432,7 @@ namespace System.Globalization {
                         case 'f':
                         case 'F':
                             if (!inQuote) {
-                                Contract.Assert((field == 4 && sb.Length == 0) || field == 5,
+                                Debug.Assert((field == 4 && sb.Length == 0) || field == 5,
                                                 "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
                                 field = 5; // End
                                 ff++;
@@ -444,14 +444,14 @@ namespace System.Globalization {
                     }
                 }
 
-                Contract.Assert(field == 5);
+                Debug.Assert(field == 5);
                 AppCompatLiteral = MinuteSecondSep + SecondFractionSep;
 
-                Contract.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
-                Contract.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
-                Contract.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
-                Contract.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
-                Contract.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+                Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+                Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+                Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+                Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+                Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
 
                 if (useInvariantFieldLengths) {
                     dd = 2;
index 41221a5..d83c5fa 100644 (file)
@@ -53,6 +53,7 @@
 namespace System.Globalization {
     using System.Text;
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Globalization;
 
@@ -126,10 +127,10 @@ namespace System.Globalization {
             }
 
             public bool IsInvalidNumber(int maxValue, int maxPrecision) {
-                Contract.Assert(ttt == TTT.Num);
-                Contract.Assert(num > -1);
-                Contract.Assert(maxValue > 0);
-                Contract.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits);
+                Debug.Assert(ttt == TTT.Num);
+                Debug.Assert(num > -1);
+                Debug.Assert(maxValue > 0);
+                Debug.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits);
 
                 if (num > maxValue)
                     return true;
@@ -163,7 +164,7 @@ namespace System.Globalization {
             }
             // used by the parsing routines that operate on standard-formats
             internal TimeSpanToken GetNextToken() {
-                Contract.Assert(m_pos > -1);
+                Debug.Assert(m_pos > -1);
 
                 TimeSpanToken tok = new TimeSpanToken();
                 char ch = CurrentChar;
@@ -374,7 +375,7 @@ namespace System.Globalization {
             private const int MaxNumericTokens = 5;
 
             internal void Init(DateTimeFormatInfo dtfi) {
-                Contract.Assert(dtfi != null);
+                Debug.Assert(dtfi != null);
 
                 lastSeenTTT = TTT.None;
                 tokenCount = 0;
@@ -416,7 +417,7 @@ namespace System.Globalization {
                 }
 
                 lastSeenTTT = tok.ttt;
-                Contract.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)");
+                Debug.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)");
                 return true;
             }
 
@@ -486,7 +487,7 @@ namespace System.Globalization {
                     return new OverflowException(Environment.GetResourceString(m_failureMessageID));
 
                 default:
-                    Contract.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure);
+                    Debug.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure);
                     return new FormatException(Environment.GetResourceString("Format_InvalidString"));
                 }
             }
@@ -1158,8 +1159,8 @@ namespace System.Globalization {
         //  Actions: Parse the TimeSpan instance using the specified format.  Used by TryParseExactTimeSpan.
         // 
         private static Boolean TryParseByFormat(String input, String format, TimeSpanStyles styles, ref TimeSpanResult result) {
-            Contract.Assert(input != null, "input != null");
-            Contract.Assert(format != null, "format != null");
+            Debug.Assert(input != null, "input != null");
+            Debug.Assert(format != null, "format != null");
 
             bool seenDD = false;      // already processed days?
             bool seenHH = false;      // already processed hours?
index 8379c88..06e7c7d 100644 (file)
@@ -4,6 +4,7 @@
 
 namespace System.Globalization {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
 
@@ -338,9 +339,9 @@ namespace System.Globalization {
         =========================ConvertHijriToGregorian============================*/
         static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg)
         {
-            Contract.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
-            Contract.Assert( HijriMonth >= 1, "Hijri month is out of range.");
-            Contract.Assert( HijriDay >= 1, "Hijri day is out of range.");
+            Debug.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
+            Debug.Assert( HijriMonth >= 1, "Hijri month is out of range.");
+            Debug.Assert( HijriDay >= 1, "Hijri day is out of range.");
             int index, b, nDays = HijriDay-1;
             DateTime dt;
             
@@ -430,7 +431,7 @@ namespace System.Globalization {
             TimeSpan ts;
             int yh1=0, mh1=0, dh1=0;
 
-            Contract.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
+            Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
 
             // Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo.
             // A Hijri year is 354 or 355 days.  Use 355 days so that we will search from a lower index.
@@ -631,7 +632,7 @@ namespace System.Globalization {
         {
             int days = 0, b;
 
-            Contract.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
+            Debug.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
 
             b = HijriYearInfo[year-MinCalendarYear].HijriMonthsLengthFlags;
 
@@ -640,7 +641,7 @@ namespace System.Globalization {
                 days += 29 + (b & 0x1);
                 b = b >> 1;
             }
-            Contract.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days.");
+            Debug.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days.");
             return days;
         }
 
index c8ee9f0..e2e36ba 100644 (file)
@@ -10,6 +10,7 @@ namespace System {
     using Microsoft.Win32;
     using System.Runtime.InteropServices;
     using System.Runtime.CompilerServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // Represents a Globally Unique Identifier.
@@ -185,7 +186,7 @@ namespace System {
             }
             internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument,
                                      string failureArgumentName, Exception innerException) {
-                Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
+                Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
                 m_failure = failure;
                 m_failureMessageID = failureMessageID;
                 m_failureMessageFormatArgument = failureMessageFormatArgument;
@@ -214,7 +215,7 @@ namespace System {
                     return m_innerException;
 
                 default:
-                    Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure);
+                    Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure);
                     return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"));
                 }
             }
@@ -752,17 +753,14 @@ namespace System {
         //
         // StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines;
 
-        [System.Security.SecuritySafeCritical]
         private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
             return StringToShort(str, null, requiredLength, flags, out result, ref parseResult);
         }
-        [System.Security.SecuritySafeCritical]
         private static unsafe bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
             fixed(int * ppos = &parsePos) {
                 return StringToShort(str, ppos, requiredLength, flags, out result, ref parseResult);
             }
         }
-        [System.Security.SecurityCritical]
         private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
             result = 0;
             int x;
@@ -771,17 +769,14 @@ namespace System {
             return retValue;
         }
 
-        [System.Security.SecuritySafeCritical]
         private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
             return StringToInt(str, null, requiredLength, flags, out result, ref parseResult);
         }
-        [System.Security.SecuritySafeCritical]
         private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
             fixed(int * ppos = &parsePos) {
                 return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult);
             }
         }
-        [System.Security.SecurityCritical]
         private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
             result = 0;
 
@@ -818,17 +813,14 @@ namespace System {
             }
             return true;
         }
-        [System.Security.SecuritySafeCritical]
         private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) {
             return StringToLong(str, null, flags, out result, ref parseResult);
         }
-        [System.Security.SecuritySafeCritical]
         private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) {
             fixed(int * ppos = &parsePos) {
                 return StringToLong(str, ppos, flags, out result, ref parseResult);
             }
         }
-        [System.Security.SecuritySafeCritical]
         private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult) {
             result = 0;
 
@@ -921,7 +913,6 @@ namespace System {
             return ToString("D",null);
         }
 
-        [System.Security.SecuritySafeCritical]
         public unsafe override int GetHashCode()
         {
             // Simply XOR all the bits of the GUID 32 bits at a time.
@@ -1143,7 +1134,6 @@ namespace System {
 
         // This will create a new guid.  Since we've now decided that constructors should 0-init,
         // we need a method that allows users to create a guid.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Guid NewGuid() {
             // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some
             // uniqueness guarantees.  It should also never return a known GUID, but it's unclear
@@ -1165,13 +1155,11 @@ namespace System {
             return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30);
         }
 
-        [System.Security.SecurityCritical]
         unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b)
         {
             return HexsToChars(guidChars, offset, a, b, false);
         }
 
-        [System.Security.SecurityCritical]
         unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex)
         {
             if (hex) {
@@ -1192,7 +1180,6 @@ namespace System {
 
         // IFormattable interface
         // We currently ignore provider
-        [System.Security.SecuritySafeCritical]
         public String ToString(String format, IFormatProvider provider)
         {
             if (format == null || format.Length == 0)
index 7e03145..902a79b 100644 (file)
@@ -20,16 +20,13 @@ namespace System
     using System.Runtime.Versioning;
     using System.Runtime.CompilerServices;
 
-    [System.Security.SecurityCritical]
     internal class AppDomainPauseManager
     {
-        [System.Security.SecurityCritical]
         public AppDomainPauseManager()
         {
             isPaused = false;
         }
 
-        [System.Security.SecurityCritical]
         static AppDomainPauseManager()
         {
         }
@@ -37,22 +34,19 @@ namespace System
         static readonly AppDomainPauseManager instance = new AppDomainPauseManager();
         internal static AppDomainPauseManager Instance
         {
-            [System.Security.SecurityCritical]
             get { return instance; }
         }
 
         // FAS: IAppDomainPauseConsumer interface implementation
         // currently there is nothing we do here as the implementation
         // of updating pause times have been moved to native CorHost2
-        [System.Security.SecurityCritical]
         public void Pausing()
         {
         }
 
-        [System.Security.SecurityCritical]
         public void Paused()
         {
-            Contract.Assert(!isPaused);
+            Debug.Assert(!isPaused);
 
             if(ResumeEvent == null)
                 ResumeEvent = new ManualResetEvent(false);
@@ -67,15 +61,13 @@ namespace System
             isPaused = true;
         }
 
-        [System.Security.SecurityCritical]
         public void Resuming()
         {
-            Contract.Assert(isPaused);
+            Debug.Assert(isPaused);
             isPaused = false;
             ResumeEvent.Set();
         }
 
-        [System.Security.SecurityCritical]
         public void Resumed()
         {
             Timer.Resume();
@@ -85,15 +77,12 @@ namespace System
 
         internal static bool IsPaused
         {
-            [System.Security.SecurityCritical]
             get { return isPaused; }
         }
 
         internal static ManualResetEvent ResumeEvent
         {
-            [System.Security.SecurityCritical]
             get; 
-            [System.Security.SecurityCritical]
             set;
         }
     }
index c7eff0f..4145a7f 100644 (file)
@@ -19,6 +19,7 @@ namespace System.IO {
     using System.Runtime;
     using System.Text;
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Security;
 
@@ -73,7 +74,7 @@ namespace System.IO {
             m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream));
             m_leaveOpen = leaveOpen;
 
-            Contract.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
+            Debug.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
         }
 
         public virtual Stream BaseStream {
@@ -173,7 +174,7 @@ namespace System.IO {
                 if (m_stream==null) __Error.FileNotOpen();
                 // read directly from MemoryStream buffer
                 MemoryStream mStream = m_stream as MemoryStream;
-                Contract.Assert(mStream != null, "m_stream as MemoryStream != null");
+                Debug.Assert(mStream != null, "m_stream as MemoryStream != null");
 
                 return mStream.InternalReadInt32();
             }
@@ -209,14 +210,12 @@ namespace System.IO {
             return ((ulong)hi) << 32 | lo;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public virtual unsafe float ReadSingle() {
             FillBuffer(4);
             uint tmpBuffer = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
             return *((float*)&tmpBuffer);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public virtual unsafe double ReadDouble() {
             FillBuffer(8);
             uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
@@ -294,7 +293,6 @@ namespace System.IO {
             return StringBuilderCache.GetStringAndRelease(sb);
         }
 
-        [SecuritySafeCritical]
         public virtual int Read(char[] buffer, int index, int count) {
             if (buffer==null) {
                 throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
@@ -319,11 +317,10 @@ namespace System.IO {
             return InternalReadChars(buffer, index, count);
         }
 
-        [SecurityCritical]
         private int InternalReadChars(char[] buffer, int index, int count) {
             Contract.Requires(buffer != null);
             Contract.Requires(index >= 0 && count >= 0);
-            Contract.Assert(m_stream != null);
+            Debug.Assert(m_stream != null);
 
             int numBytes = 0;
             int charsRemaining = count;
@@ -355,7 +352,7 @@ namespace System.IO {
                 if (m_isMemoryStream)
                 {
                     MemoryStream mStream = m_stream as MemoryStream;
-                    Contract.Assert(mStream != null, "m_stream as MemoryStream != null");
+                    Debug.Assert(mStream != null, "m_stream as MemoryStream != null");
 
                     position = mStream.InternalGetPosition();
                     numBytes = mStream.InternalEmulateRead(numBytes);
@@ -371,7 +368,7 @@ namespace System.IO {
                     return (count - charsRemaining);
                 }
 
-                Contract.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
+                Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
 
                 checked
                 {
@@ -398,7 +395,7 @@ namespace System.IO {
             }
 
             // this should never fail
-            Contract.Assert(charsRemaining >= 0, "We read too many characters.");
+            Debug.Assert(charsRemaining >= 0, "We read too many characters.");
 
             // we may have read fewer than the number of characters requested if end of stream reached 
             // or if the encoding makes the char count too big for the buffer (e.g. fallback sequence)
@@ -447,7 +444,7 @@ namespace System.IO {
                     return -1;
                 }
 
-                Contract.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
+                Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
 
                 try {
 
@@ -464,7 +461,7 @@ namespace System.IO {
                     throw;
                 }
 
-                Contract.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
+                Debug.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
                 //                Console.WriteLine("That became: " + charsRead + " characters.");
             }
             if (charsRead == 0)
@@ -472,7 +469,6 @@ namespace System.IO {
             return m_singleChar[0];
         }
 
-        [SecuritySafeCritical]
         public virtual char[] ReadChars(int count) {
             if (count<0) {
                 throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
index ed3ae5b..f99b4d3 100644 (file)
@@ -17,6 +17,7 @@ using System;
 using System.Runtime;
 using System.Runtime.Serialization;
 using System.Text;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.IO {
@@ -25,7 +26,7 @@ namespace System.IO {
     // give unique encodings.
     //
     [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public class BinaryWriter : IDisposable
     {
         public static readonly BinaryWriter Null = new BinaryWriter();
@@ -38,16 +39,6 @@ namespace System.IO {
         [OptionalField]  // New in .NET FX 4.5.  False is the right default value.
         private bool _leaveOpen;
 
-#if !FEATURE_CORECLR
-        // This field should never have been serialized and has not been used since before v2.0.
-        // However, this type is serializable, and we need to keep the field name around when deserializing.
-        // Also, we'll make .NET FX 4.5 not break if it's missing.
-#pragma warning disable 169
-        [OptionalField]
-        private char[] _tmpOneCharBuffer;
-#pragma warning restore 169
-#endif
-
         // Perf optimization stuff
         private byte[] _largeByteBuffer;  // temp space for writing chars.
         private int _maxChars;   // max # of chars we can put in _largeByteBuffer
@@ -187,13 +178,12 @@ namespace System.IO {
         // advanced by two.
         // Note this method cannot handle surrogates properly in UTF-8.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual void Write(char ch) {
             if (Char.IsSurrogate(ch))
                 throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar"));
             Contract.EndContractBlock();
 
-            Contract.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
+            Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
             int numBytes = 0;
             fixed(byte * pBytes = _buffer) {
                 numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true);
@@ -231,7 +221,6 @@ namespace System.IO {
         // Writes a double to this stream. The current position of the stream is
         // advanced by eight.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual void Write(double value)
         {
             ulong TmpValue = *(ulong *)&value;
@@ -334,7 +323,6 @@ namespace System.IO {
         // Writes a float to this stream. The current position of the stream is
         // advanced by four.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual void Write(float value)
         {
             uint TmpValue = *(uint *)&value;
@@ -351,7 +339,6 @@ namespace System.IO {
         // a four-byte unsigned integer, and then writes that many characters 
         // to the stream.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe virtual void Write(String value) 
         {
             if (value==null)
@@ -368,7 +355,7 @@ namespace System.IO {
 
             if (len <= _largeByteBuffer.Length)
             {
-                //Contract.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers!  encoding type: "+_encoding.GetType().Name);
+                //Debug.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers!  encoding type: "+_encoding.GetType().Name);
                 _encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
                 OutStream.Write(_largeByteBuffer, 0, len);
             }
@@ -403,14 +390,14 @@ namespace System.IO {
                     }
 #if _DEBUG
                     totalBytes += byteLen;
-                    Contract.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
+                    Debug.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
 #endif
                     OutStream.Write(_largeByteBuffer, 0, byteLen);
                     charStart += charCount;
                     numLeft -= charCount;
                 }
 #if _DEBUG
-                Contract.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
+                Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
 #endif
             }
         }
index e4b41eb..5eb3fc8 100644 (file)
 **
 ===========================================================*/
 
-using System;
-using System.Collections;
 using System.Collections.Generic;
 using System.Security;
 using System.Security.Permissions;
 using Microsoft.Win32;
 using Microsoft.Win32.SafeHandles;
-using System.Text;
 using System.Runtime.InteropServices;
-using System.Globalization;
-using System.Runtime.Versioning;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
-using System.Threading;
 
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
-
-namespace System.IO {
+namespace System.IO
+{
     [ComVisible(true)]
     public static class Directory {
         public static DirectoryInfo GetParent(String path)
@@ -53,7 +45,6 @@ namespace System.IO {
             return new DirectoryInfo(s);
         }
 
-        [System.Security.SecuritySafeCritical]
         public static DirectoryInfo CreateDirectory(String path) {
             if (path == null)
                 throw new ArgumentNullException(nameof(path));
@@ -64,7 +55,6 @@ namespace System.IO {
             return InternalCreateDirectoryHelper(path, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static DirectoryInfo UnsafeCreateDirectory(String path)
         {
             if (path == null)
@@ -76,7 +66,6 @@ namespace System.IO {
             return InternalCreateDirectoryHelper(path, false);
         }
 
-        [System.Security.SecurityCritical] 
         internal static DirectoryInfo InternalCreateDirectoryHelper(String path, bool checkHost)
         {
             Contract.Requires(path != null);
@@ -90,45 +79,17 @@ namespace System.IO {
             // a demand at every level.
             String demandDir = GetDemandDir(fullPath, true);
 
-#if FEATURE_CORECLR
             if (checkHost)
             {
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandDir);
                 state.EnsureState(); // do the check on the AppDomainManager to make sure this is allowed  
             }
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false);
-#endif
 
             InternalCreateDirectory(fullPath, path, null, checkHost);
 
             return new DirectoryInfo(fullPath, false);
         }
 
-#if FEATURE_MACL
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public static DirectoryInfo CreateDirectory(String path, DirectorySecurity directorySecurity) {
-            if (path==null)
-                throw new ArgumentNullException(nameof(path));
-            if (path.Length == 0)
-                throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
-            Contract.EndContractBlock();
-            
-            String fullPath = Path.GetFullPathInternal(path);
-
-            // You need read access to the directory to be returned back and write access to all the directories 
-            // that you need to create. If we fail any security checks we will not create any directories at all.
-            // We attempt to create directories only after all the security checks have passed. This is avoid doing
-            // a demand at every level.
-            String demandDir = GetDemandDir(fullPath, true); 
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false );
-
-            InternalCreateDirectory(fullPath, path, directorySecurity);
-            
-            return new DirectoryInfo(fullPath, false);
-        }
-#endif // FEATURE_MACL
-
         // Input to this method should already be fullpath. This method will ensure that we append 
         // the trailing slash only when appropriate and when thisDirOnly is specified append a "." 
         // at the end of the path to indicate that the demand is only for the fullpath and not 
@@ -160,13 +121,8 @@ namespace System.IO {
         }
 
 
-        [System.Security.SecuritySafeCritical]
         internal unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, bool checkHost)
         {
-#if FEATURE_MACL
-            DirectorySecurity dirSecurity = (DirectorySecurity)dirSecurityObj;
-#endif // FEATURE_MACL
-
             int length = fullPath.Length;
 
             // We need to trim the trailing slash or the code will try to create 2 directories of the same name.
@@ -215,15 +171,7 @@ namespace System.IO {
 
             int count = stackDir.Count;
 
-            if (stackDir.Count != 0
-#if FEATURE_CAS_POLICY
-                // All demands in full trust domains are no-ops, so skip
-                //
-                // The full path went through validity checks by being passed through FileIOPermissions already.
-                // As a sub string of the full path can't fail the checks if the full path passes.
-                && !CodeAccessSecurityEngine.QuickCheckForAllDemands()
-#endif
-            )
+            if (stackDir.Count != 0)
             {
                 String[] securityList = new String[stackDir.Count];
                 stackDir.CopyTo(securityList, 0);
@@ -231,11 +179,6 @@ namespace System.IO {
                     securityList[j] += "\\."; // leaf will never have a slash at the end
 
                 // Security check for all directories not present only.
-#if FEATURE_MACL
-                AccessControlActions control = (dirSecurity == null) ? AccessControlActions.None : AccessControlActions.Change;
-                FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, control, securityList, false, false);
-#else
-#if FEATURE_CORECLR
                 if (checkHost)
                 {
                     foreach (String demandPath in securityList) 
@@ -244,27 +187,11 @@ namespace System.IO {
                         state.EnsureState();
                     }
                 }
-#else
-                FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, securityList, false, false);
-#endif
-#endif //FEATURE_MACL
             }
 
             // If we were passed a DirectorySecurity, convert it to a security
             // descriptor and set it in he call to CreateDirectory.
             Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
-#if FEATURE_MACL
-            if (dirSecurity != null) {
-                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
-                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
-                // For ACL's, get the security descriptor from the FileSecurity.
-                byte[] sd = dirSecurity.GetSecurityDescriptorBinaryForm();
-                byte * bytesOnStack = stackalloc byte[sd.Length];
-                Buffer.Memcpy(bytesOnStack, 0, sd, 0, sd.Length);
-                secAttrs.pSecurityDescriptor = bytesOnStack;
-            }
-#endif
 
             bool r = true;
             int firstError = 0;
@@ -294,15 +221,11 @@ namespace System.IO {
                             firstError = currentError;
                             // Give the user a nice error message, but don't leak path information.
                             try {
-#if FEATURE_CORECLR
                                 if (checkHost)
                                 {
                                     FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, GetDemandDir(name, true));
                                     state.EnsureState();
                                 }
-#else
-                                FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, GetDemandDir(name, true));
-#endif // FEATURE_CORECLR
                                 errorString = name;
                             }
                             catch(SecurityException) {}
@@ -335,19 +258,16 @@ namespace System.IO {
         // Your application must have Read permission to the directory's
         // contents.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool Exists(String path)
         {
             return InternalExistsHelper(path, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static bool UnsafeExists(String path)
         {
             return InternalExistsHelper(path, false);
         }
 
-        [System.Security.SecurityCritical]
         internal static bool InternalExistsHelper(String path, bool checkHost) {
             try
             {
@@ -361,16 +281,11 @@ namespace System.IO {
                 String fullPath = Path.GetFullPath(path);
                 String demandPath = GetDemandDir(fullPath, true);
 
-#if FEATURE_CORECLR
                 if (checkHost)
                 {
                     FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandPath);
                     state.EnsureState();
                 }
-#else
-                FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandPath, false, false);
-#endif
-
 
                 return InternalExists(fullPath);
             }
@@ -380,14 +295,13 @@ namespace System.IO {
             catch (IOException) { }
             catch (UnauthorizedAccessException)
             {
-                Contract.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only.");
+                Debug.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only.");
             }
             return false;
         }
 
         // Determine whether path describes an existing directory
         // on disk, avoiding security checks.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool InternalExists(String path) {
             int lastError = Win32Native.ERROR_SUCCESS;
             return InternalExists(path, out lastError);
@@ -395,7 +309,6 @@ namespace System.IO {
 
         // Determine whether path describes an existing directory
         // on disk, avoiding security checks.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool InternalExists(String path, out int lastError) {
             Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
             lastError = File.FillAttributeInfo(path, ref data, false, true);
@@ -404,27 +317,6 @@ namespace System.IO {
                     && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0);
         }
 
-#if !FEATURE_CORECLR
-        public static void SetCreationTime(String path,DateTime creationTime)
-        {
-            SetCreationTimeUtc(path, creationTime.ToUniversalTime());
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public unsafe static void SetCreationTimeUtc(String path,DateTime creationTimeUtc)
-        {
-            using (SafeFileHandle handle = Directory.OpenHandle(path)) {
-                Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc());
-                bool r = Win32Native.SetFileTime(handle, &fileTime, null, null);
-                if (!r)
-                {
-                    int errorCode = Marshal.GetLastWin32Error();
-                    __Error.WinIOError(errorCode, path);
-                }
-            }
-        }
-#endif // !FEATURE_CORECLR
-
         public static DateTime GetCreationTime(String path)
         {
             return File.GetCreationTime(path);
@@ -435,27 +327,6 @@ namespace System.IO {
             return File.GetCreationTimeUtc(path);
         }
 
-#if !FEATURE_CORECLR
-        public static void SetLastWriteTime(String path,DateTime lastWriteTime)
-        {
-            SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime());
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public unsafe static void SetLastWriteTimeUtc(String path,DateTime lastWriteTimeUtc)
-        {
-            using (SafeFileHandle handle = Directory.OpenHandle(path)) {
-                Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc());
-                bool r = Win32Native.SetFileTime(handle,  null, null, &fileTime);
-                if (!r)
-                {
-                    int errorCode = Marshal.GetLastWin32Error();
-                    __Error.WinIOError(errorCode, path);
-                }
-            }
-        }
-#endif // !FEATURE_CORECLR
-
         public static DateTime GetLastWriteTime(String path)
         {
             return File.GetLastWriteTime(path);
@@ -466,27 +337,6 @@ namespace System.IO {
             return File.GetLastWriteTimeUtc(path);
         }
 
-#if !FEATURE_CORECLR
-        public static void SetLastAccessTime(String path,DateTime lastAccessTime)
-        {
-            SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime());
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public unsafe static void SetLastAccessTimeUtc(String path,DateTime lastAccessTimeUtc)
-        {
-            using (SafeFileHandle handle = Directory.OpenHandle(path)) {
-                Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc());
-                bool r = Win32Native.SetFileTime(handle,  null, &fileTime, null);
-                if (!r)
-                {
-                    int errorCode = Marshal.GetLastWin32Error();
-                    __Error.WinIOError(errorCode, path);
-                }
-            }
-        }
-#endif // !FEATURE_CORECLR
-
         public static DateTime GetLastAccessTime(String path)
         {
             return File.GetLastAccessTime(path);
@@ -495,31 +345,8 @@ namespace System.IO {
         public static DateTime GetLastAccessTimeUtc(String path)
         {
             return File.GetLastAccessTimeUtc(path);
-        }       
-#if FEATURE_MACL
-        public static DirectorySecurity GetAccessControl(String path)
-        {
-            return new DirectorySecurity(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
         }
 
-        public static DirectorySecurity GetAccessControl(String path, AccessControlSections includeSections)
-        {
-            return new DirectorySecurity(path, includeSections);
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public static void SetAccessControl(String path, DirectorySecurity directorySecurity)
-        {
-            if (directorySecurity == null)
-                throw new ArgumentNullException(nameof(directorySecurity));
-            Contract.EndContractBlock();
-
-            String fullPath = Path.GetFullPathInternal(path);
-            directorySecurity.Persist(fullPath);
-        }
-#endif
-
         // Returns an array of filenames in the DirectoryInfo specified by path
         public static String[] GetFiles(String path)
         {
@@ -572,7 +399,6 @@ namespace System.IO {
             return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static String[] UnsafeGetFiles(String path, String searchPattern, SearchOption searchOption)
         {
             Contract.Requires(path != null);
@@ -635,7 +461,6 @@ namespace System.IO {
             return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static String[] UnsafeGetDirectories(String path, String searchPattern, SearchOption searchOption)
         {
             Contract.Requires(path != null);
@@ -888,7 +713,6 @@ namespace System.IO {
         // 
         // Your application must have System Info permission.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String[] GetLogicalDrives()
         {
             Contract.Ensures(Contract.Result<String[]>() != null);
@@ -920,7 +744,6 @@ namespace System.IO {
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]
         public static String GetDirectoryRoot(String path) {
             if (path==null)
                 throw new ArgumentNullException(nameof(path));
@@ -930,13 +753,9 @@ namespace System.IO {
             string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath));
             string demandPath = GetDemandDir(root, true);
 
-#if FEATURE_CORECLR
             FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, path, demandPath);
             state.EnsureState();
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandPath, false, false);
-#endif
-                     
+
             return root;
         }
 
@@ -952,19 +771,16 @@ namespace System.IO {
         **Arguments: The current DirectoryInfo to which to switch to the setter.
         **Exceptions: 
         ==============================================================================*/
-        [System.Security.SecuritySafeCritical]
         public static String GetCurrentDirectory()
         {
             return InternalGetCurrentDirectory(true);
         }
 
-        [System.Security.SecurityCritical]
         internal static String UnsafeGetCurrentDirectory()
         {
             return InternalGetCurrentDirectory(false);
         }
 
-        [System.Security.SecuritySafeCritical]
         private static string InternalGetCurrentDirectory(bool checkHost)
         {
             string currentDirectory = NewGetCurrentDirectory();
@@ -978,7 +794,6 @@ namespace System.IO {
             return currentDirectory;
         }
 
-        [System.Security.SecurityCritical]
         private static string NewGetCurrentDirectory()
         {
             // Start with a buffer the size of MAX_PATH
@@ -1006,7 +821,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecurityCritical] // auto-generated
         public static void SetCurrentDirectory(String path)
         {
             if (path==null)
@@ -1036,17 +850,14 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         public static void Move(String sourceDirName,String destDirName) {
             InternalMove(sourceDirName, destDirName, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static void UnsafeMove(String sourceDirName,String destDirName) {
             InternalMove(sourceDirName, destDirName, false);
         }
 
-        [System.Security.SecurityCritical]
         private static void InternalMove(String sourceDirName,String destDirName,bool checkHost) {
             if (sourceDirName==null)
                 throw new ArgumentNullException(nameof(sourceDirName));
@@ -1071,17 +882,12 @@ namespace System.IO {
             if (PathInternal.IsDirectoryTooLong(destPath))
                 throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
 
-#if FEATURE_CORECLR
             if (checkHost) {
                 FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceDirName, sourcePath);
                 FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, destPath);
                 sourceState.EnsureState();
                 destState.EnsureState();
             }
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, sourcePath, false, false);
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, destPath, false, false);
-#endif
 
             if (String.Compare(sourcePath, destPath, StringComparison.OrdinalIgnoreCase) == 0)
                 throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent"));
@@ -1106,21 +912,18 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         public static void Delete(String path)
         {
             String fullPath = Path.GetFullPath(path);
             Delete(fullPath, path, false, true);
         }
 
-        [System.Security.SecuritySafeCritical]
         public static void Delete(String path, bool recursive)
         {
             String fullPath = Path.GetFullPath(path);
             Delete(fullPath, path, recursive, true);
         }
 
-        [System.Security.SecurityCritical] 
         internal static void UnsafeDelete(String path, bool recursive)
         {
             String fullPath = Path.GetFullPath(path);
@@ -1129,7 +932,6 @@ namespace System.IO {
 
         // Called from DirectoryInfo as well.  FullPath is fully qualified,
         // while the user path is used for feedback in exceptions.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void Delete(String fullPath, String userPath, bool recursive, bool checkHost)
         {
             String demandPath;
@@ -1137,17 +939,12 @@ namespace System.IO {
             // If not recursive, do permission check only on this directory
             // else check for the whole directory structure rooted below 
             demandPath = GetDemandDir(fullPath, !recursive);
-            
-#if FEATURE_CORECLR
+
             if (checkHost) 
             {
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, userPath, demandPath);
                 state.EnsureState();
             }
-#else
-            // Make sure we have write permission to this directory
-            new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandPath }, false, false ).Demand();
-#endif
 
             // Do not recursively delete through reparse points.  Perhaps in a 
             // future version we will add a new flag to control this behavior, 
@@ -1171,7 +968,6 @@ namespace System.IO {
         // Note that fullPath is fully qualified, while userPath may be 
         // relative.  Use userPath for all exception messages to avoid leaking
         // fully qualified path information.
-        [System.Security.SecurityCritical]  // auto-generated
         private static void DeleteHelper(String fullPath, String userPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
         {
             bool r;
@@ -1309,39 +1105,7 @@ namespace System.IO {
             }
         }
 
-#if !FEATURE_CORECLR
-        // WinNT only. Win9x this code will not work.
-        [System.Security.SecurityCritical]  // auto-generated
-        private static SafeFileHandle OpenHandle(String path)
-        {
-            String fullPath = Path.GetFullPathInternal(path);
-            String root = Path.GetPathRoot(fullPath);
-            if (root == fullPath && root[1] == Path.VolumeSeparatorChar)
-                throw new ArgumentException(Environment.GetResourceString("Arg_PathIsVolume"));
-
-#if !FEATURE_CORECLR
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, GetDemandDir(fullPath, true), false, false);
-#endif
-
-            SafeFileHandle handle = Win32Native.SafeCreateFile (
-                fullPath,
-                GENERIC_WRITE,
-                (FileShare) (FILE_SHARE_WRITE|FILE_SHARE_DELETE),
-                null,
-                FileMode.Open,
-                FILE_FLAG_BACKUP_SEMANTICS,
-                IntPtr.Zero
-            );
-
-            if (handle.IsInvalid) {
-                int hr = Marshal.GetLastWin32Error();
-                __Error.WinIOError(hr, fullPath);
-            }
-            return handle;
-        }
-#endif // !FEATURE_CORECLR
-
-        private const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;    
+        private const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
         private const int GENERIC_WRITE = unchecked((int)0x40000000);
         private const int FILE_SHARE_WRITE = 0x00000002;
         private const int FILE_SHARE_DELETE = 0x00000004;
index d29ab57..22adc4f 100644 (file)
@@ -19,9 +19,6 @@ using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Security;
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
 using System.Security.Permissions;
 using Microsoft.Win32;
 using System.Text;
@@ -29,25 +26,24 @@ using System.Runtime.InteropServices;
 using System.Globalization;
 using System.Runtime.Serialization;
 using System.Runtime.Versioning;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
-namespace System.IO {
+namespace System.IO
+{
     [Serializable]
     [ComVisible(true)]
-    public sealed class DirectoryInfo : FileSystemInfo {
+    public sealed class DirectoryInfo : FileSystemInfo
+    {
         private String[] demandDir;
 
-#if FEATURE_CORECLR
-         // Migrating InheritanceDemands requires this default ctor, so we can annotate it.
+        // Migrating InheritanceDemands requires this default ctor, so we can annotate it.
 #if FEATURE_CORESYSTEM
-        [System.Security.SecurityCritical]
 #else
-        [System.Security.SecuritySafeCritical]
 #endif //FEATURE_CORESYSTEM
         private DirectoryInfo(){}
 
 
-        [System.Security.SecurityCritical]
         public static DirectoryInfo UnsafeCreateDirectoryInfo(String path)
         {
             if (path == null)
@@ -58,9 +54,7 @@ namespace System.IO {
             di.Init(path, false);
             return di;
         }
-#endif
 
-        [System.Security.SecuritySafeCritical]
         public DirectoryInfo(String path)
         {
             if (path==null)
@@ -70,7 +64,6 @@ namespace System.IO {
             Init(path, true);
         }
 
-        [System.Security.SecurityCritical]
         private void Init(String path, bool checkHost)
         {
             // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead
@@ -87,26 +80,22 @@ namespace System.IO {
             String fullPath = Path.GetFullPath(path);
 
             demandDir = new String[] {Directory.GetDemandDir(fullPath, true)};
-#if FEATURE_CORECLR
+
             if (checkHost)
             {
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, OriginalPath, fullPath);
                 state.EnsureState();
             }
-#else
-            new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand();
-#endif
 
             FullPath = fullPath;
             DisplayPath = GetDisplayName(OriginalPath, FullPath);
         }
 
 #if FEATURE_CORESYSTEM
-        [System.Security.SecuritySafeCritical]
 #endif //FEATURE_CORESYSTEM
         internal DirectoryInfo(String fullPath, bool junk)
         {
-            Contract.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
+            Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
             // Fast path when we know a DirectoryInfo exists.
             OriginalPath = Path.GetFileName(fullPath);
 
@@ -115,31 +104,21 @@ namespace System.IO {
             demandDir = new String[] {Directory.GetDemandDir(fullPath, true)};
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private DirectoryInfo(SerializationInfo info, StreamingContext context) : base(info, context)
         {
-#if !FEATURE_CORECLR
-            demandDir = new String[] {Directory.GetDemandDir(FullPath, true)};
-            new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand();
-#endif
             DisplayPath = GetDisplayName(OriginalPath, FullPath);
         }
 
-        public override String Name {
+        public override String Name
+        {
             get 
             {
-#if FEATURE_CORECLR
                 // DisplayPath is dir name for coreclr
                 return DisplayPath;
-#else
-                // Return just dir name
-                return GetDirName(FullPath);
-#endif
             }
         }
 
         public DirectoryInfo Parent {
-            [System.Security.SecuritySafeCritical]
             get {
                 String parentName;
                 // FullPath might be either "c:\bar" or "c:\bar\".  Handle 
@@ -151,20 +130,14 @@ namespace System.IO {
                 if (parentName==null)
                     return null;
                 DirectoryInfo dir = new DirectoryInfo(parentName,false);
-#if FEATURE_CORECLR
+
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery | FileSecurityStateAccess.Read, String.Empty, dir.demandDir[0]);
                 state.EnsureState();
-#else
-                new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, dir.demandDir, false, false).Demand();
-#endif
+
                 return dir;
             }
         }
 
-      
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-#endif
         public DirectoryInfo CreateSubdirectory(String path) {
             if (path == null)
                 throw new ArgumentNullException(nameof(path));
@@ -173,16 +146,6 @@ namespace System.IO {
             return CreateSubdirectory(path, null);
         }
 
-#if FEATURE_MACL
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public DirectoryInfo CreateSubdirectory(String path, DirectorySecurity directorySecurity)
-        {
-            return CreateSubdirectoryHelper(path, directorySecurity);
-        }
-#else  // FEATURE_MACL
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public DirectoryInfo CreateSubdirectory(String path, Object directorySecurity)
         {
             if (path == null)
@@ -191,9 +154,7 @@ namespace System.IO {
 
             return CreateSubdirectoryHelper(path, directorySecurity);
         }
-#endif // FEATURE_MACL
 
-        [System.Security.SecurityCritical]  // auto-generated
         private DirectoryInfo CreateSubdirectoryHelper(String path, Object directorySecurity)
         {
             Contract.Requires(path != null);
@@ -208,12 +169,8 @@ namespace System.IO {
 
             // Ensure we have permission to create this subdirectory.
             String demandDirForCreation = Directory.GetDemandDir(fullPath, true);
-#if FEATURE_CORECLR
             FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, OriginalPath, demandDirForCreation);
             state.EnsureState();
-#else
-            new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandDirForCreation }, false, false).Demand();
-#endif
 
             Directory.InternalCreateDirectory(fullPath, path, directorySecurity);
 
@@ -226,20 +183,12 @@ namespace System.IO {
             Directory.InternalCreateDirectory(FullPath, OriginalPath, null, true);
         }
 
-#if FEATURE_MACL
-        public void Create(DirectorySecurity directorySecurity)
-        {
-            Directory.InternalCreateDirectory(FullPath, OriginalPath, directorySecurity, true);
-        }
-#endif
-
         // Tests if the given path refers to an existing DirectoryInfo on disk.
         // 
         // Your application must have Read permission to the directory's
         // contents.
         //
         public override bool Exists {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 try
@@ -257,23 +206,6 @@ namespace System.IO {
                 }
             }
         }
-      
-#if FEATURE_MACL
-        public DirectorySecurity GetAccessControl()
-        {
-            return Directory.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
-        }
-
-        public DirectorySecurity GetAccessControl(AccessControlSections includeSections)
-        {
-            return Directory.GetAccessControl(FullPath, includeSections);
-        }
-
-        public void SetAccessControl(DirectorySecurity directorySecurity)
-        {
-            Directory.SetAccessControl(FullPath, directorySecurity);
-        }
-#endif
 
         // Returns an array of Files in the current DirectoryInfo matching the 
         // given search criteria (ie, "*.txt").
@@ -515,7 +447,6 @@ namespace System.IO {
         //
 
         public DirectoryInfo Root {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 String demandPath;
@@ -523,30 +454,23 @@ namespace System.IO {
                 String rootPath = FullPath.Substring(0, rootLength);
                 demandPath = Directory.GetDemandDir(rootPath, true);
 
-#if FEATURE_CORECLR
                 FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPath);
                 sourceState.EnsureState();
-#else
-                new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { demandPath }, false, false).Demand();
-#endif
+
                 return new DirectoryInfo(rootPath);
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         public void MoveTo(String destDirName) {
             if (destDirName==null)
                 throw new ArgumentNullException(nameof(destDirName));
             if (destDirName.Length==0)
                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destDirName));
             Contract.EndContractBlock();
-            
-#if FEATURE_CORECLR
+
             FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, Directory.GetDemandDir(FullPath, true));
             sourceState.EnsureState();
-#else
-            new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandDir, false, false).Demand();
-#endif
+
             String fullDestDirName = Path.GetFullPath(destDirName);
             String demandPath;
             if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar))
@@ -560,13 +484,9 @@ namespace System.IO {
             // had the ability to read the file contents in the old location,
             // but you technically also need read permissions to the new 
             // location as well, and write is not a true superset of read.
-#if FEATURE_CORECLR
             FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, demandPath);
             destState.EnsureState();
-#else
-            new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandPath).Demand();
-#endif
-            
+
             String fullSourcePath;
             if (FullPath.EndsWith(Path.DirectorySeparatorChar))
                 fullSourcePath = FullPath;
@@ -605,13 +525,11 @@ namespace System.IO {
             _dataInitialised = -1;
         }
 
-        [System.Security.SecuritySafeCritical]
         public override void Delete()
         {
             Directory.Delete(FullPath, OriginalPath, false, true);
         }
 
-        [System.Security.SecuritySafeCritical]
         public void Delete(bool recursive)
         {
             Directory.Delete(FullPath, OriginalPath, recursive, true);
@@ -625,8 +543,8 @@ namespace System.IO {
 
         private static String GetDisplayName(String originalPath, String fullPath)
         {
-            Contract.Assert(originalPath != null);
-            Contract.Assert(fullPath != null);
+            Debug.Assert(originalPath != null);
+            Debug.Assert(fullPath != null);
 
             String displayName = "";
 
@@ -637,18 +555,14 @@ namespace System.IO {
             }
             else 
             {
-#if FEATURE_CORECLR
                 displayName = GetDirName(fullPath);
-#else
-                displayName = originalPath;
-#endif
             }
             return displayName;
         }
 
         private static String GetDirName(String fullPath)
         {
-            Contract.Assert(fullPath != null);
+            Debug.Assert(fullPath != null);
 
             String dirName = null;
             if (fullPath.Length > 3)
index efb322b..174811d 100644 (file)
@@ -53,7 +53,6 @@ namespace System.IO
 
         private const String NameField = "_name";  // For serialization
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public DriveInfo(String driveName) 
         {
             if (driveName == null)
@@ -88,7 +87,6 @@ namespace System.IO
             new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPath).Demand();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private DriveInfo(SerializationInfo info, StreamingContext context)
         {
             // Need to add in a security check here once it has been spec'ed.
@@ -104,7 +102,6 @@ namespace System.IO
         }
 
         public DriveType DriveType {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { 
                 // GetDriveType can't fail
                 return (DriveType) Win32Native.GetDriveType(Name);
@@ -112,7 +109,6 @@ namespace System.IO
         }
 
         public String DriveFormat {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 const int volNameLen = 50;
                 StringBuilder volumeName = new StringBuilder(volNameLen);
@@ -136,14 +132,12 @@ namespace System.IO
         }
 
         public bool IsReady {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return Directory.InternalExists(Name);
             }
         }
 
         public long AvailableFreeSpace {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { 
                 long userBytes, totalBytes, freeBytes;
                 int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
@@ -160,7 +154,6 @@ namespace System.IO
         }
 
         public long TotalFreeSpace {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { 
                 long userBytes, totalBytes, freeBytes;
                 int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
@@ -177,7 +170,6 @@ namespace System.IO
         }
 
         public long TotalSize {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { 
                 // Don't cache this, to handle variable sized floppy drives
                 // or other various removable media drives.
@@ -213,7 +205,6 @@ namespace System.IO
 
         // Null is a valid volume label.
         public String VolumeLabel {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 // NTFS uses a limit of 32 characters for the volume label,
                 // as of Windows Server 2003.
@@ -240,7 +231,6 @@ namespace System.IO
                 }
                 return volumeName.ToString();
             }
-            [System.Security.SecuritySafeCritical]  // auto-generated
             set {
                 String demandPath = _name + '.';
                 new FileIOPermission(FileIOPermissionAccess.Write, demandPath).Demand();
@@ -269,7 +259,6 @@ namespace System.IO
 
 #if FEATURE_SERIALIZATION
         /// <internalonly/>
-        [System.Security.SecurityCritical]
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // No need for an additional security check - everything is public.
index ce70220..826766d 100644 (file)
 **
 ===========================================================*/
 
-using System;
 using System.Security.Permissions;
-using PermissionSet = System.Security.PermissionSet;
 using Win32Native = Microsoft.Win32.Win32Native;
 using System.Runtime.InteropServices;
 using System.Security;
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
 using System.Text;
 using Microsoft.Win32.SafeHandles;
 using System.Collections.Generic;
-using System.Globalization;
-using System.Runtime.Versioning;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
-    
-namespace System.IO {    
+
+namespace System.IO
+{
     // Class for creating FileStream objects, and some basic file management
     // routines such as Delete, etc.
     [ComVisible(true)]
@@ -114,7 +109,6 @@ namespace System.IO {
             InternalCopy(sourceFileName, destFileName, overwrite, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static void UnsafeCopy(String sourceFileName, String destFileName, bool overwrite) {
             if (sourceFileName == null)
                 throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
@@ -132,8 +126,8 @@ namespace System.IO {
         /// <devdoc>
         ///    Note: This returns the fully qualified name of the destination file.
         /// </devdoc>
-        [System.Security.SecuritySafeCritical]
-        internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) {
+        internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost)
+        {
             Contract.Requires(sourceFileName != null);
             Contract.Requires(destFileName != null);
             Contract.Requires(sourceFileName.Length > 0);
@@ -141,19 +135,14 @@ namespace System.IO {
 
             String fullSourceFileName = Path.GetFullPath(sourceFileName);
             String fullDestFileName = Path.GetFullPath(destFileName);
-            
-#if FEATURE_CORECLR
+
             if (checkHost) {
                 FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
                 FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
                 sourceState.EnsureState();
                 destState.EnsureState();
             }
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullSourceFileName, false, false);
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
-#endif
-       
+
             bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite);
             if (!r) {
                 // Save Win32 error because subsequent checks will overwrite this HRESULT.
@@ -161,16 +150,6 @@ namespace System.IO {
                 String fileName = destFileName;
 
                 if (errorCode != Win32Native.ERROR_FILE_EXISTS) {
-#if !FEATURE_CORECLR
-                    // For a number of error codes (sharing violation, path 
-                    // not found, etc) we don't know if the problem was with
-                    // the source or dest file.  Try reading the source file.
-                    using(SafeFileHandle handle = Win32Native.UnsafeCreateFile(fullSourceFileName, GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) {
-                        if (handle.IsInvalid)
-                            fileName = sourceFileName;
-                    }
-#endif // !FEATURE_CORECLR
-
                     if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
                         if (Directory.InternalExists(fullDestFileName))
                             throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName);
@@ -213,13 +192,6 @@ namespace System.IO {
                                   FileShare.None, bufferSize, options);
         }
 
-#if FEATURE_MACL
-        public static FileStream Create(String path, int bufferSize, FileOptions options, FileSecurity fileSecurity) {
-            return new FileStream(path, FileMode.Create, FileSystemRights.Read | FileSystemRights.Write,
-                                  FileShare.None, bufferSize, options, fileSecurity);
-        }
-#endif
-
         // Deletes a file. The file specified by the designated path is deleted.
         // If the file does not exist, Delete succeeds without throwing
         // an exception.
@@ -229,7 +201,6 @@ namespace System.IO {
         // 
         // Your application must have Delete permission to the target file.
         // 
-        [System.Security.SecuritySafeCritical]
         public static void Delete(String path) {
             if (path == null)
                 throw new ArgumentNullException(nameof(path));
@@ -238,7 +209,6 @@ namespace System.IO {
             InternalDelete(path, true);
         }
 
-        [System.Security.SecurityCritical] 
         internal static void UnsafeDelete(String path)
         {
             if (path == null)
@@ -248,22 +218,16 @@ namespace System.IO {
             InternalDelete(path, false);
         }
 
-        [System.Security.SecurityCritical] 
         internal static void InternalDelete(String path, bool checkHost)
         {
             String fullPath = Path.GetFullPath(path);
 
-#if FEATURE_CORECLR
             if (checkHost)
             {
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath);
                 state.EnsureState();
             }
-#else
-            // For security check, path should be resolved to an absolute path.
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false);
 
-#endif
             bool r = Win32Native.DeleteFile(fullPath);
             if (!r) {
                 int hr = Marshal.GetLastWin32Error();
@@ -275,7 +239,6 @@ namespace System.IO {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void Decrypt(String path)
         {
             if (path == null)
@@ -299,7 +262,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void Encrypt(String path)
         {
             if (path == null)
@@ -330,19 +292,16 @@ namespace System.IO {
         //
         // Your application must have Read permission for the target directory.
         // 
-        [System.Security.SecuritySafeCritical]
         public static bool Exists(String path)
         {
             return InternalExistsHelper(path, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static bool UnsafeExists(String path)
         {
             return InternalExistsHelper(path, false);
         }
 
-        [System.Security.SecurityCritical]
         private static bool InternalExistsHelper(String path, bool checkHost) 
         {
             try
@@ -356,21 +315,17 @@ namespace System.IO {
                 // After normalizing, check whether path ends in directory separator.
                 // Otherwise, FillAttributeInfo removes it and we may return a false positive.
                 // GetFullPath should never return null
-                Contract.Assert(path != null, "File.Exists: GetFullPath returned null");
+                Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
                 if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
                 {
                     return false;
                 }
 
-#if FEATURE_CORECLR
                 if (checkHost)
                 {
                     FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, path);
                     state.EnsureState();
                 }
-#else
-                FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, path, false, false);
-#endif
 
                 return InternalExists(path);
             }
@@ -383,7 +338,6 @@ namespace System.IO {
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool InternalExists(String path) {
             Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
             int dataInitialised = FillAttributeInfo(path, ref data, false, true);
@@ -404,53 +358,25 @@ namespace System.IO {
             return new FileStream(path, mode, access, share);
         }
 
-#if !FEATURE_CORECLR
-        public static void SetCreationTime(String path, DateTime creationTime)
-        {
-            SetCreationTimeUtc(path, creationTime.ToUniversalTime());
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public unsafe static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
-        {
-            SafeFileHandle handle;
-            using(OpenFile(path, FileAccess.Write, out handle)) {
-                Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc());
-                bool r = Win32Native.SetFileTime(handle, &fileTime, null, null);
-                if (!r)
-                {
-                     int errorCode = Marshal.GetLastWin32Error();
-                    __Error.WinIOError(errorCode, path);
-                }
-            }
-        }
-#endif // !FEATURE_CORECLR
-
-        [System.Security.SecuritySafeCritical]
         public static DateTime GetCreationTime(String path)
         {
             return InternalGetCreationTimeUtc(path, true).ToLocalTime();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static DateTime GetCreationTimeUtc(String path)
         {
             return InternalGetCreationTimeUtc(path, false); // this API isn't exposed in Silverlight
         }
 
-        [System.Security.SecurityCritical]
         private static DateTime InternalGetCreationTimeUtc(String path, bool checkHost)
         {
             String fullPath = Path.GetFullPath(path);
-#if FEATURE_CORECLR
+
             if (checkHost) 
             {
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
                 state.EnsureState();
             }
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
 
             Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
             int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
@@ -461,53 +387,25 @@ namespace System.IO {
             return DateTime.FromFileTimeUtc(dt);
         }
 
-#if !FEATURE_CORECLR
-        public static void SetLastAccessTime(String path, DateTime lastAccessTime)
-        {
-            SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime());
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public unsafe static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
-        {
-            SafeFileHandle handle;
-            using(OpenFile(path, FileAccess.Write, out handle)) {
-                Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc());
-                bool r = Win32Native.SetFileTime(handle, null, &fileTime,  null);
-                if (!r)
-                {
-                     int errorCode = Marshal.GetLastWin32Error();
-                    __Error.WinIOError(errorCode, path);
-                }
-            }
-        }
-#endif // FEATURE_CORECLR
-
-        [System.Security.SecuritySafeCritical]
         public static DateTime GetLastAccessTime(String path)
         {
             return InternalGetLastAccessTimeUtc(path, true).ToLocalTime();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static DateTime GetLastAccessTimeUtc(String path)
         {
             return InternalGetLastAccessTimeUtc(path, false); // this API isn't exposed in Silverlight
         }
 
-        [System.Security.SecurityCritical]
         private static DateTime InternalGetLastAccessTimeUtc(String path, bool checkHost)
-        {       
+        {
             String fullPath = Path.GetFullPath(path);
-#if FEATURE_CORECLR
+
             if (checkHost) 
             {
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
                 state.EnsureState();
             }
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
 
             Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
             int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
@@ -518,53 +416,25 @@ namespace System.IO {
             return DateTime.FromFileTimeUtc(dt);
         }
 
-#if !FEATURE_CORECLR
-        public static void SetLastWriteTime(String path, DateTime lastWriteTime)
-        {
-            SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime());
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public unsafe static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
-        {
-            SafeFileHandle handle;
-            using(OpenFile(path, FileAccess.Write, out handle)) {
-                Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc());
-                bool r = Win32Native.SetFileTime(handle, null, null, &fileTime);
-                if (!r)
-                {
-                     int errorCode = Marshal.GetLastWin32Error();
-                    __Error.WinIOError(errorCode, path);
-                }
-            }
-        }
-#endif // !FEATURE_CORECLR
-
-        [System.Security.SecuritySafeCritical]
         public static DateTime GetLastWriteTime(String path)
         {
             return InternalGetLastWriteTimeUtc(path, true).ToLocalTime();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static DateTime GetLastWriteTimeUtc(String path)
         {
             return InternalGetLastWriteTimeUtc(path, false); // this API isn't exposed in Silverlight
         }
 
-        [System.Security.SecurityCritical]
         private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost)
         {
             String fullPath = Path.GetFullPath(path);
-#if FEATURE_CORECLR
+
             if (checkHost)
             {
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
                 state.EnsureState();
             }
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
 
             Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
             int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
@@ -575,16 +445,12 @@ namespace System.IO {
             return DateTime.FromFileTimeUtc(dt);
         }
 
-        [System.Security.SecuritySafeCritical]
         public static FileAttributes GetAttributes(String path) 
         {
             String fullPath = Path.GetFullPath(path);
-#if FEATURE_CORECLR
+
             FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
             state.EnsureState();
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
 
             Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
             int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true);
@@ -594,17 +460,9 @@ namespace System.IO {
             return (FileAttributes) data.fileAttributes;
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] 
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public static void SetAttributes(String path, FileAttributes fileAttributes) 
         {
             String fullPath = Path.GetFullPath(path);
-#if !FEATURE_CORECLR
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false);
-#endif
             bool r = Win32Native.SetFileAttributes(fullPath, (int) fileAttributes);
             if (!r) {
                 int hr = Marshal.GetLastWin32Error();
@@ -614,31 +472,6 @@ namespace System.IO {
             }
         }
 
-#if FEATURE_MACL
-        public static FileSecurity GetAccessControl(String path)
-        {
-            return GetAccessControl(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
-        }
-
-        public static FileSecurity GetAccessControl(String path, AccessControlSections includeSections)
-        {
-            // Appropriate security check should be done for us by FileSecurity.
-            return new FileSecurity(path, includeSections);
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public static void SetAccessControl(String path, FileSecurity fileSecurity)
-        {
-            if (fileSecurity == null)
-                throw new ArgumentNullException(nameof(fileSecurity));
-            Contract.EndContractBlock();
-
-            String fullPath = Path.GetFullPath(path);
-            // Appropriate security check should be done for us by FileSecurity.
-            fileSecurity.Persist(fullPath);
-        }
-#endif
-
         public static FileStream OpenRead(String path) {
             return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
         }
@@ -649,7 +482,6 @@ namespace System.IO {
                                   FileAccess.Write, FileShare.None);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String ReadAllText(String path)
         {
             if (path == null)
@@ -661,7 +493,6 @@ namespace System.IO {
             return InternalReadAllText(path, Encoding.UTF8, true);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String ReadAllText(String path, Encoding encoding)
         {
             if (path == null)
@@ -675,7 +506,6 @@ namespace System.IO {
             return InternalReadAllText(path, encoding, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static String UnsafeReadAllText(String path)
         {
             if (path == null)
@@ -687,7 +517,6 @@ namespace System.IO {
             return InternalReadAllText(path, Encoding.UTF8, false);
         }
 
-        [System.Security.SecurityCritical]
         private static String InternalReadAllText(String path, Encoding encoding, bool checkHost)
         {
             Contract.Requires(path != null);
@@ -698,7 +527,6 @@ namespace System.IO {
                 return sr.ReadToEnd();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void WriteAllText(String path, String contents)
         {
             if (path == null)
@@ -710,7 +538,6 @@ namespace System.IO {
             InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, true);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void WriteAllText(String path, String contents, Encoding encoding)
         {
             if (path == null)
@@ -724,7 +551,6 @@ namespace System.IO {
             InternalWriteAllText(path, contents, encoding, true);
         }
         
-        [System.Security.SecurityCritical]
         internal static void UnsafeWriteAllText(String path, String contents)
         {
             if (path == null)
@@ -736,7 +562,6 @@ namespace System.IO {
             InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, false);
         }
 
-        [System.Security.SecurityCritical]
         private static void InternalWriteAllText(String path, String contents, Encoding encoding, bool checkHost)
         {
             Contract.Requires(path != null);
@@ -747,20 +572,17 @@ namespace System.IO {
                 sw.Write(contents);
         } 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static byte[] ReadAllBytes(String path)
         {
             return InternalReadAllBytes(path, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static byte[] UnsafeReadAllBytes(String path)
         {
             return InternalReadAllBytes(path, false);
         }
 
         
-        [System.Security.SecurityCritical]
         private static byte[] InternalReadAllBytes(String path, bool checkHost)
         {
             byte[] bytes;
@@ -784,7 +606,6 @@ namespace System.IO {
             return bytes;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void WriteAllBytes(String path, byte[] bytes)
         {
             if (path == null)
@@ -798,7 +619,6 @@ namespace System.IO {
             InternalWriteAllBytes(path, bytes, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static void UnsafeWriteAllBytes(String path, byte[] bytes)
         {
             if (path == null)
@@ -812,7 +632,6 @@ namespace System.IO {
             InternalWriteAllBytes(path, bytes, false);
         }
 
-        [System.Security.SecurityCritical]
         private static void InternalWriteAllBytes(String path, byte[] bytes, bool checkHost)
         {
             Contract.Requires(path != null);
@@ -1030,17 +849,14 @@ namespace System.IO {
         // sourceFileName and Write 
         // permissions to destFileName.
         // 
-        [System.Security.SecuritySafeCritical]
         public static void Move(String sourceFileName, String destFileName) {
             InternalMove(sourceFileName, destFileName, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static void UnsafeMove(String sourceFileName, String destFileName) {
             InternalMove(sourceFileName, destFileName, false);
         }
 
-        [System.Security.SecurityCritical]
         private static void InternalMove(String sourceFileName, String destFileName, bool checkHost) {
             if (sourceFileName == null)
                 throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
@@ -1055,17 +871,12 @@ namespace System.IO {
             String fullSourceFileName = Path.GetFullPath(sourceFileName);
             String fullDestFileName = Path.GetFullPath(destFileName);
 
-#if FEATURE_CORECLR
             if (checkHost) {
                 FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
                 FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
                 sourceState.EnsureState();
                 destState.EnsureState();
             }
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, fullSourceFileName, false, false);
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
-#endif
 
             if (!InternalExists(fullSourceFileName))
                 __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName);
@@ -1099,7 +910,6 @@ namespace System.IO {
             InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
         }
 
-        [System.Security.SecuritySafeCritical]
         private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
         {
             Contract.Requires(sourceFileName != null);
@@ -1113,19 +923,12 @@ namespace System.IO {
             if (destinationBackupFileName != null)
                 fullBackupPath = Path.GetFullPath(destinationBackupFileName);
 
-#if FEATURE_CORECLR
             FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, sourceFileName, fullSrcPath);
             FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationFileName, fullDestPath);
             FileSecurityState backupState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationBackupFileName, fullBackupPath);
             sourceState.EnsureState();
             destState.EnsureState();
             backupState.EnsureState();
-#else
-            FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullSrcPath, fullDestPath});
-            if (destinationBackupFileName != null)
-                perm.AddPathList(FileIOPermissionAccess.Write, fullBackupPath);
-            perm.Demand();
-#endif
 
             int flags = Win32Native.REPLACEFILE_WRITE_THROUGH;
             if (ignoreMetadataErrors)
@@ -1139,7 +942,6 @@ namespace System.IO {
 
         // Returns 0 on success, otherwise a Win32 error code.  Note that
         // classes should use -1 as the uninitialized state for dataInitialized.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
         {
             int dataInitialised = 0;
@@ -1185,7 +987,7 @@ namespace System.IO {
                         catch {
                             // if we're already returning an error, don't throw another one. 
                             if (!error) {
-                                Contract.Assert(false, "File::FillAttributeInfo - FindClose failed!");
+                                Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!");
                                 __Error.WinIOError();
                             }
                         }
@@ -1236,35 +1038,8 @@ namespace System.IO {
             return dataInitialised;
         }
 
-#if !FEATURE_CORECLR
-        [System.Security.SecurityCritical]  // auto-generated
-        private static FileStream OpenFile(String path, FileAccess access, out SafeFileHandle handle)
-        {
-            FileStream fs = new FileStream(path, FileMode.Open, access, FileShare.ReadWrite, 1);
-            handle = fs.SafeFileHandle;
-
-            if (handle.IsInvalid) {
-                // Return a meaningful error, using the RELATIVE path to
-                // the file to avoid returning extra information to the caller.
-            
-                // NT5 oddity - when trying to open "C:\" as a FileStream,
-                // we usually get ERROR_PATH_NOT_FOUND from the OS.  We should
-                // probably be consistent w/ every other directory.
-                int hr = Marshal.GetLastWin32Error();
-                String FullPath = Path.GetFullPath(path);
-                if (hr==__Error.ERROR_PATH_NOT_FOUND && FullPath.Equals(Directory.GetDirectoryRoot(FullPath)))
-                    hr = __Error.ERROR_ACCESS_DENIED;
-
-
-                __Error.WinIOError(hr, path);
-            }
-            return fs;
-        }
-#endif // !FEATURE_CORECLR
-
-
-         // Defined in WinError.h
+        // Defined in WinError.h
         private const int ERROR_INVALID_PARAMETER = 87;
-        private const int ERROR_ACCESS_DENIED = 0x5;     
+        private const int ERROR_ACCESS_DENIED = 0x5;
     }
 }
index 19d5f22..51ef597 100644 (file)
 ===========================================================*/
 using System;
 
-namespace System.IO {
+namespace System.IO
+{
     // File attributes for use with the FileEnumerator class.
     // These constants correspond to the constants in WinNT.h.
-    // 
-[Serializable]
+    [Serializable]
     [Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public enum FileAttributes
     {
         // From WinNT.h (FILE_ATTRIBUTE_XXX)
@@ -35,17 +35,5 @@ namespace System.IO {
         Offline = 0x1000,
         NotContentIndexed = 0x2000,
         Encrypted = 0x4000,
-
-#if !FEATURE_CORECLR
-#if FEATURE_COMINTEROP
-        [System.Runtime.InteropServices.ComVisible(false)]        
-#endif // FEATURE_COMINTEROP
-        IntegrityStream = 0x8000,
-        
-#if FEATURE_COMINTEROP
-        [System.Runtime.InteropServices.ComVisible(false)]        
-#endif // FEATURE_COMINTEROP
-        NoScrubData = 0x20000,
-#endif
     }
 }
index 60a7b35..7e00a80 100644 (file)
@@ -15,9 +15,6 @@
 ===========================================================*/
 
 using System;
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
 using System.Security.Permissions;
 using PermissionSet = System.Security.PermissionSet;
 using Win32Native = Microsoft.Win32.Win32Native;
@@ -26,9 +23,11 @@ using System.Text;
 using System.Runtime.Serialization;
 using System.Globalization;
 using System.Runtime.Versioning;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
-namespace System.IO {    
+namespace System.IO
+{
     // Class for creating FileStream objects, and some basic file management
     // routines such as Delete, etc.
     [Serializable]
@@ -37,16 +36,12 @@ namespace System.IO {
     {
         private String _name;
 
-#if FEATURE_CORECLR
         // Migrating InheritanceDemands requires this default ctor, so we can annotate it.
 #if FEATURE_CORESYSTEM
-        [System.Security.SecurityCritical]
 #else
-        [System.Security.SecuritySafeCritical]
 #endif //FEATURE_CORESYSTEM
         private FileInfo(){}
 
-        [System.Security.SecurityCritical]
         public static FileInfo UnsafeCreateFileInfo(String fileName)
         {
             if (fileName == null)
@@ -57,9 +52,7 @@ namespace System.IO {
             fi.Init(fileName, false);
             return fi;
         }
-#endif
 
-        [System.Security.SecuritySafeCritical]
         public FileInfo(String fileName)
         {
             if (fileName == null)
@@ -69,21 +62,17 @@ namespace System.IO {
             Init(fileName, true);
         }
 
-        [System.Security.SecurityCritical]
         private void Init(String fileName, bool checkHost)
         {
             OriginalPath = fileName;
             // Must fully qualify the path for the security check
             String fullPath = Path.GetFullPath(fileName);
-#if FEATURE_CORECLR
+
             if (checkHost)
             {
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, fileName, fullPath);
                 state.EnsureState();
             }
-#else
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
 
             _name = Path.GetFileName(fileName);
             FullPath = fullPath;
@@ -92,30 +81,20 @@ namespace System.IO {
 
         private String GetDisplayPath(String originalPath)
         {
-#if FEATURE_CORECLR
             return Path.GetFileName(originalPath);
-#else
-            return originalPath;
-#endif
-
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private FileInfo(SerializationInfo info, StreamingContext context) : base(info, context)
         {
-#if !FEATURE_CORECLR
-            new FileIOPermission(FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand();
-#endif
             _name = Path.GetFileName(OriginalPath);
             DisplayPath = GetDisplayPath(OriginalPath);
         }
 
 #if FEATURE_CORESYSTEM
-        [System.Security.SecuritySafeCritical]
 #endif //FEATURE_CORESYSTEM
         internal FileInfo(String fullPath, bool ignoreThis)
         {
-            Contract.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
+            Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
             _name = Path.GetFileName(fullPath);
             OriginalPath = _name;
             FullPath = fullPath;
@@ -125,10 +104,8 @@ namespace System.IO {
         public override String Name {
             get { return _name; }
         }
-    
-   
+
         public long Length {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 if (_dataInitialised == -1)
                     Refresh();
@@ -146,18 +123,13 @@ namespace System.IO {
         /* Returns the name of the directory that the file is in */
         public String DirectoryName
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 String directoryName = Path.GetDirectoryName(FullPath);
                 if (directoryName != null)
                 {
-#if FEATURE_CORECLR
                     FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, DisplayPath, FullPath);
                     state.EnsureState();
-#else
-                    new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { directoryName }, false, false).Demand();
-#endif
                 }
                 return directoryName;
             }
@@ -171,7 +143,7 @@ namespace System.IO {
                 String dirName = DirectoryName;
                 if (dirName == null)
                     return null;
-                return new DirectoryInfo(dirName);    
+                return new DirectoryInfo(dirName);
             }
         } 
 
@@ -187,24 +159,6 @@ namespace System.IO {
             }
         }
 
-#if FEATURE_MACL
-        public FileSecurity GetAccessControl()
-        {
-            return File.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
-        }
-
-        public FileSecurity GetAccessControl(AccessControlSections includeSections)
-        {
-            return File.GetAccessControl(FullPath, includeSections);
-        }
-
-        public void SetAccessControl(FileSecurity fileSecurity)
-        {
-            File.SetAccessControl(FullPath, fileSecurity);
-        }
-#endif
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StreamReader OpenText()
         {
             return new StreamReader(FullPath, Encoding.UTF8, true, StreamReader.DefaultBufferSize, false);
@@ -276,16 +230,10 @@ namespace System.IO {
         // 
         // Your application must have Delete permission to the target file.
         // 
-        [System.Security.SecuritySafeCritical]
         public override void Delete()
         {
-#if FEATURE_CORECLR
             FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath);
             state.EnsureState();
-#else
-            // For security check, path should be resolved to an absolute path.
-            new FileIOPermission(FileIOPermissionAccess.Write, new String[] { FullPath }, false, false).Demand();
-#endif
 
             bool r = Win32Native.DeleteFile(FullPath);
             if (!r) {
@@ -315,7 +263,6 @@ namespace System.IO {
         //
         // Your application must have Read permission for the target directory.
         public override bool Exists {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 try {
                     if (_dataInitialised == -1)
@@ -335,9 +282,6 @@ namespace System.IO {
             }
         }
 
-        
-      
-      
         // User must explicitly specify opening a new file or appending to one.
         public FileStream Open(FileMode mode) {
             return Open(mode, FileAccess.ReadWrite, FileShare.None);
@@ -351,27 +295,17 @@ namespace System.IO {
             return new FileStream(FullPath, mode, access, share);
         }
 
-        
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#endif
         public FileStream OpenRead()
         {
             return new FileStream(FullPath, FileMode.Open, FileAccess.Read,
                                   FileShare.Read, 4096, false);
         }
 
-
         public FileStream OpenWrite() {
             return new FileStream(FullPath, FileMode.OpenOrCreate, 
                                   FileAccess.Write, FileShare.None);
         }
 
-      
-
-       
-        
-
         // Moves a given file to a new location and potentially a new file name.
         // This method does work across volumes.
         //
@@ -380,7 +314,6 @@ namespace System.IO {
         // sourceFileName and Write 
         // permissions to destFileName.
         // 
-        [System.Security.SecuritySafeCritical]
         public void MoveTo(String destFileName) {
             if (destFileName==null)
                 throw new ArgumentNullException(nameof(destFileName));
@@ -389,16 +322,12 @@ namespace System.IO {
             Contract.EndContractBlock();
 
             string fullDestFileName = Path.GetFullPath(destFileName);
-#if FEATURE_CORECLR
+
             FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath);
             FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
             sourceState.EnsureState();
             destState.EnsureState();
-#else
-            new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand();
-            FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
-#endif
-       
+
             if (!Win32Native.MoveFile(FullPath, fullDestFileName))
                 __Error.WinIOError();
             FullPath = fullDestFileName;
index 508082e..2b56c00 100644 (file)
@@ -135,11 +135,9 @@ namespace System.IO {
         }
 
         public String FusionLog {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return _fusionLog; }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             // Serialize data for our base classes.  base will verify info != null.
             base.GetObjectData(info, context);
@@ -156,7 +154,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static String FormatFileLoadExceptionMessage(String fileName,
             int hResult)
         {
@@ -169,12 +166,10 @@ namespace System.IO {
             return String.Format(CultureInfo.CurrentCulture, format, fileName, message);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetFileLoadExceptionMessage(int hResult, StringHandleOnStack retString);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetMessageForHR(int hresult, StringHandleOnStack retString);
index 67230f9..8cc75f8 100644 (file)
@@ -136,11 +136,9 @@ namespace System.IO {
         }
 
         public String FusionLog {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return _fusionLog; }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             // Serialize data for our base classes.  base will verify info != null.
             base.GetObjectData(info, context);
index f5a3f63..d10681f 100644 (file)
@@ -22,7 +22,6 @@ using System.Security.Permissions;
 
 namespace System.IO
 {
-    [SecurityCritical]
     [System.Runtime.CompilerServices.FriendAccessAllowed]
     internal class FileSecurityState : SecurityState
     {
@@ -35,7 +34,6 @@ namespace System.IO
         private String m_canonicalizedPath;
 
         // default ctor needed for security rule consistency
-        [SecurityCritical]
         private FileSecurityState()
         {
         }
@@ -88,9 +86,6 @@ namespace System.IO
             }
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public override void EnsureState()
         {
             // this is the case for empty string machine name, etc
index 21e355d..e3ad368 100644 (file)
@@ -23,6 +23,7 @@ using System.Text;
 using System.Runtime.InteropServices;
 using System.Globalization;
 using System.Runtime.Versioning;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Threading;
 
@@ -168,7 +169,6 @@ namespace System.IO
         private List<Directory.SearchData> searchStack;
         private Directory.SearchData searchData;
         private String searchCriteria;
-        [System.Security.SecurityCritical]
         SafeFindHandle _hnd = null;
         bool needsParentPathDiscoveryDemand;
 
@@ -187,7 +187,6 @@ namespace System.IO
         private int oldMode;
         private bool _checkHost;
 
-        [System.Security.SecuritySafeCritical]
         internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler<TSource> resultHandler, bool checkHost)
         {
             Contract.Requires(path != null);
@@ -223,7 +222,7 @@ namespace System.IO
                 // Do a demand on the combined path so that we can fail early in case of deny
                 demandPaths[1] = Directory.GetDemandDir(normalizedSearchPath, true);
                 _checkHost = checkHost;
-#if FEATURE_CORECLR
+
                 if (checkHost)
                 {
                     FileSecurityState state1 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[0]);
@@ -231,9 +230,6 @@ namespace System.IO
                     FileSecurityState state2 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[1]);
                     state2.EnsureState();
                 }
-#else
-                new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand();
-#endif
 
                 // normalize search criteria
                 searchCriteria = GetNormalizedSearchCriteria(fullSearchString, normalizedSearchPath);
@@ -254,10 +250,9 @@ namespace System.IO
 
         }
 
-        [System.Security.SecurityCritical]
         private void CommonInit()
         {
-            Contract.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized");
+            Debug.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized");
 
             // Execute searchCriteria against the current directory
             String searchPath = Path.Combine(searchData.fullPath, searchCriteria);
@@ -307,7 +302,6 @@ namespace System.IO
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         private FileSystemEnumerableIterator(String fullPath, String normalizedSearchPath, String searchCriteria, String userPath, SearchOption searchOption, SearchResultHandler<TSource> resultHandler, bool checkHost)
         {
             this.fullPath = fullPath;
@@ -329,7 +323,7 @@ namespace System.IO
                 // For filters like foo\*.cs we need to verify if the directory foo is not denied access.
                 // Do a demand on the combined path so that we can fail early in case of deny
                 demandPaths[1] = Directory.GetDemandDir(normalizedSearchPath, true);
-#if FEATURE_CORECLR
+
                 if (checkHost) 
                 {
                     FileSecurityState state1 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[0]);
@@ -337,9 +331,7 @@ namespace System.IO
                     FileSecurityState state2 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[1]);
                     state2.EnsureState();
                 }
-#else
-                new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand();
-#endif
+
                 searchData = new Directory.SearchData(normalizedSearchPath, userPath, searchOption);
                 CommonInit();
             }
@@ -354,7 +346,6 @@ namespace System.IO
             return new FileSystemEnumerableIterator<TSource>(fullPath, normalizedSearchPath, searchCriteria, userPath, searchOption, _resultHandler, _checkHost);
         }
 
-        [System.Security.SecuritySafeCritical]
         protected override void Dispose(bool disposing)
         {
             try
@@ -371,7 +362,6 @@ namespace System.IO
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         public override bool MoveNext()
         {
             Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
@@ -404,12 +394,12 @@ namespace System.IO
                     }
                 case STATE_SEARCH_NEXT_DIR:
                     {
-                        Contract.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly");
+                        Debug.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly");
                         // Traverse directory structure. We need to get '*'
                         while (searchStack.Count > 0)
                         {
                             searchData = searchStack[0];
-                            Contract.Assert((searchData.fullPath != null), "fullpath can't be null!");
+                            Debug.Assert((searchData.fullPath != null), "fullpath can't be null!");
                             searchStack.RemoveAt(0);
 
                             // Traverse the subdirs
@@ -506,7 +496,6 @@ namespace System.IO
             return false;
         }
 
-        [System.Security.SecurityCritical]
         private SearchResult CreateSearchResult(Directory.SearchData localSearchData, Win32Native.WIN32_FIND_DATA findData)
         {
             String userPathFinal = Path.Combine(localSearchData.userPath, findData.cFileName);
@@ -514,14 +503,12 @@ namespace System.IO
             return new SearchResult(fullPathFinal, userPathFinal, findData);
         }
 
-        [System.Security.SecurityCritical]
         private void HandleError(int hr, String path)
         {
             Dispose();
             __Error.WinIOError(hr, path);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddSearchableDirsToStack(Directory.SearchData localSearchData)
         {
             Contract.Requires(localSearchData != null);
@@ -578,20 +565,13 @@ namespace System.IO
             }
         }
 
-        [System.Security.SecurityCritical]
         internal void DoDemand(String fullPathToDemand)
         {
-#if FEATURE_CORECLR
             if(_checkHost) {
                 String demandDir = Directory.GetDemandDir(fullPathToDemand, true);
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir);
                 state.EnsureState();
             }
-#else
-            String demandDir = Directory.GetDemandDir(fullPathToDemand, true);
-            String[] demandPaths = new String[] { demandDir };
-            new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand();
-#endif
         }
 
         private static String NormalizeSearchPattern(String searchPattern)
@@ -626,7 +606,7 @@ namespace System.IO
             }
             else
             {
-                Contract.Assert(fullSearchString.Length > fullPathMod.Length);
+                Debug.Assert(fullSearchString.Length > fullPathMod.Length);
                 searchCriteria = fullSearchString.Substring(fullPathMod.Length + 1);
             }
             return searchCriteria;
@@ -653,10 +633,8 @@ namespace System.IO
     internal abstract class SearchResultHandler<TSource>
     {
 
-        [System.Security.SecurityCritical]
         internal abstract bool IsResultIncluded(SearchResult result);
 
-        [System.Security.SecurityCritical]
         internal abstract TSource CreateObject(SearchResult result);
 
     }
@@ -672,16 +650,14 @@ namespace System.IO
             _includeDirs = includeDirs;
         }
 
-        [System.Security.SecurityCritical]
         internal override bool IsResultIncluded(SearchResult result)
         {
             bool includeFile = _includeFiles && FileSystemEnumerableHelpers.IsFile(result.FindData);
             bool includeDir = _includeDirs && FileSystemEnumerableHelpers.IsDir(result.FindData);
-            Contract.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
+            Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
             return (includeFile || includeDir);
         }
 
-        [System.Security.SecurityCritical]
         internal override String CreateObject(SearchResult result)
         {
             return result.UserPath;
@@ -690,23 +666,18 @@ namespace System.IO
 
     internal class FileInfoResultHandler : SearchResultHandler<FileInfo>
     {
-        [System.Security.SecurityCritical]
         internal override bool IsResultIncluded(SearchResult result)
         {
             return FileSystemEnumerableHelpers.IsFile(result.FindData);
         }
 
-        [System.Security.SecurityCritical]
         internal override FileInfo CreateObject(SearchResult result)
         {
             String name = result.FullPath;
-#if FEATURE_CORECLR
+
             FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name);
             state.EnsureState();
-#else
-            String[] names = new String[] { name };
-            new FileIOPermission(FileIOPermissionAccess.Read, names, false, false).Demand();
-#endif
+
             FileInfo fi = new FileInfo(name, false);
             fi.InitializeFrom(result.FindData);
             return fi;
@@ -715,25 +686,19 @@ namespace System.IO
 
     internal class DirectoryInfoResultHandler : SearchResultHandler<DirectoryInfo>
     {
-        [System.Security.SecurityCritical]
         internal override bool IsResultIncluded(SearchResult result)
         {
             return FileSystemEnumerableHelpers.IsDir(result.FindData);
         }
 
-        [System.Security.SecurityCritical]
         internal override DirectoryInfo CreateObject(SearchResult result)
         {
             String name = result.FullPath;
             String permissionName = name + "\\.";
-            
-#if FEATURE_CORECLR
+
             FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, permissionName);
             state.EnsureState();
-#else
-            String[] permissionNames = new String[] { permissionName };
-            new FileIOPermission(FileIOPermissionAccess.Read, permissionNames, false, false).Demand();
-#endif
+
             DirectoryInfo di = new DirectoryInfo(name, false);
             di.InitializeFrom(result.FindData);
             return di;
@@ -743,17 +708,15 @@ namespace System.IO
     internal class FileSystemInfoResultHandler : SearchResultHandler<FileSystemInfo>
     {
 
-        [System.Security.SecurityCritical]
         internal override bool IsResultIncluded(SearchResult result)
         {
             bool includeFile = FileSystemEnumerableHelpers.IsFile(result.FindData);
             bool includeDir = FileSystemEnumerableHelpers.IsDir(result.FindData);
-            Contract.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
+            Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
 
             return (includeDir || includeFile);
         }
 
-        [System.Security.SecurityCritical]
         internal override FileSystemInfo CreateObject(SearchResult result)
         {
             bool isFile = FileSystemEnumerableHelpers.IsFile(result.FindData);
@@ -764,29 +727,21 @@ namespace System.IO
                 String name = result.FullPath;
                 String permissionName = name + "\\.";
 
-#if FEATURE_CORECLR
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, permissionName);
                 state.EnsureState();
-#else
-                String[] permissionNames = new String[] { permissionName };
-                new FileIOPermission(FileIOPermissionAccess.Read, permissionNames, false, false).Demand();
-#endif
+
                 DirectoryInfo di = new DirectoryInfo(name, false);
                 di.InitializeFrom(result.FindData);
                 return di;
             }
             else
             {
-                Contract.Assert(isFile);
+                Debug.Assert(isFile);
                 String name = result.FullPath;
 
-#if FEATURE_CORECLR
                 FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name);
                 state.EnsureState();
-#else
-                String[] names = new String[] { name };
-                new FileIOPermission(FileIOPermissionAccess.Read, names, false, false).Demand();
-#endif
+
                 FileInfo fi = new FileInfo(name, false);
                 fi.InitializeFrom(result.FindData);
                 return fi;
@@ -799,10 +754,8 @@ namespace System.IO
     {
         private String fullPath;     // fully-qualifed path
         private String userPath;     // user-specified path
-        [System.Security.SecurityCritical]
         private Win32Native.WIN32_FIND_DATA findData;
 
-        [System.Security.SecurityCritical]
         internal SearchResult(String fullPath, String userPath, Win32Native.WIN32_FIND_DATA findData)
         {
             Contract.Requires(fullPath != null);
@@ -825,7 +778,6 @@ namespace System.IO
 
         internal Win32Native.WIN32_FIND_DATA FindData
         {
-            [System.Security.SecurityCritical]
             get { return findData; }
         }
 
@@ -833,7 +785,6 @@ namespace System.IO
 
     internal static class FileSystemEnumerableHelpers
     {
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDir(Win32Native.WIN32_FIND_DATA data)
         {
             // Don't add "." nor ".."
@@ -841,7 +792,6 @@ namespace System.IO
                                                 && !data.cFileName.Equals(".") && !data.cFileName.Equals("..");
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsFile(Win32Native.WIN32_FIND_DATA data)
         {
             return 0 == (data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY);
index fe39b2d..be2189c 100644 (file)
@@ -2,17 +2,6 @@
 // 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;
 using System.Collections;
 using System.Security;
@@ -24,17 +13,14 @@ using System.Runtime.Serialization;
 using System.Runtime.Versioning;
 using System.Diagnostics.Contracts;
 
-namespace System.IO {
+namespace System.IO
+{
 #if FEATURE_SERIALIZATION
     [Serializable]
 #endif
-#if !FEATURE_CORECLR
-    [FileIOPermissionAttribute(SecurityAction.InheritanceDemand,Unrestricted=true)]
-#endif
     [ComVisible(true)]
     public abstract class FileSystemInfo : MarshalByRefObject, ISerializable {
         
-        [System.Security.SecurityCritical] // auto-generated
         internal Win32Native.WIN32_FILE_ATTRIBUTE_DATA _data; // Cache the file information
         internal int _dataInitialised = -1; // We use this field in conjunction with the Refresh methods, if we succeed
                                             // we store a zero, on failure we store the HResult in it so that we can
@@ -47,13 +33,9 @@ namespace System.IO {
         protected String OriginalPath;      // path passed in by the user
         private String _displayPath = "";   // path that can be displayed to the user
 
-#if FEATURE_CORECLR
 #if FEATURE_CORESYSTEM
-        [System.Security.SecurityCritical]
 #else
-        [System.Security.SecuritySafeCritical]
 #endif //FEATURE_CORESYSTEM
-#endif
         protected FileSystemInfo()
         {
         }
@@ -73,7 +55,6 @@ namespace System.IO {
             _dataInitialised = -1;
         }
 
-        [System.Security.SecurityCritical]
         internal void InitializeFrom(Win32Native.WIN32_FIND_DATA findData)
         {
             _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
@@ -83,7 +64,6 @@ namespace System.IO {
 
         // Full path of the direcory/file
         public virtual String FullName {
-            [System.Security.SecuritySafeCritical]
             get 
             {
                 String demandDir;
@@ -91,19 +71,15 @@ namespace System.IO {
                     demandDir = Directory.GetDemandDir(FullPath, true);
                 else
                     demandDir = FullPath;
-#if FEATURE_CORECLR
+
                 FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir);
                 sourceState.EnsureState();
-#else
-                new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand();
-#endif
                 return FullPath;
             }
         }
 
         internal virtual String UnsafeGetFullName
         {
-            [System.Security.SecurityCritical]
             get
             {
                 String demandDir;
@@ -111,9 +87,6 @@ namespace System.IO {
                     demandDir = Directory.GetDemandDir(FullPath, true);
                 else
                     demandDir = FullPath;
-#if !FEATURE_CORECLR
-                new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand();
-#endif
                 return FullPath;
             }
         }
@@ -156,23 +129,15 @@ namespace System.IO {
                     // depends on the security check in get_CreationTimeUtc
                     return CreationTimeUtc.ToLocalTime();
             }
-#if !FEATURE_CORECLR
-            set
-            {
-                CreationTimeUtc = value.ToUniversalTime();
-            }
-#endif // !FEATURE_CORECLR
         }
 
         [ComVisible(false)]
        public DateTime CreationTimeUtc {
-           [System.Security.SecuritySafeCritical]
             get {
-#if FEATURE_CORECLR
                 // get_CreationTime also depends on this security check
                 FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
                 sourceState.EnsureState();
-#endif
+
                 if (_dataInitialised == -1) {
                     _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
                     Refresh();
@@ -185,18 +150,8 @@ namespace System.IO {
                 return DateTime.FromFileTimeUtc(fileTime);
                 
             }
-#if !FEATURE_CORECLR
-            set {
-                if (this is DirectoryInfo)
-                    Directory.SetCreationTimeUtc(FullPath,value);
-                else
-                    File.SetCreationTimeUtc(FullPath,value);
-                _dataInitialised = -1;
-            }
-#endif // !FEATURE_CORECLR
         }
 
-
         public DateTime LastAccessTime
         {
            get {
@@ -210,13 +165,11 @@ namespace System.IO {
 
         [ComVisible(false)]
         public DateTime LastAccessTimeUtc {
-            [System.Security.SecuritySafeCritical]
             get {
-#if FEATURE_CORECLR
                 // get_LastAccessTime also depends on this security check
                 FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
                 sourceState.EnsureState();
-#endif
+
                 if (_dataInitialised == -1) {
                     _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
                     Refresh();
@@ -231,13 +184,6 @@ namespace System.IO {
             }
 
             set {
-#if !FEATURE_CORECLR
-                if (this is DirectoryInfo)
-                    Directory.SetLastAccessTimeUtc(FullPath,value);
-                else
-                    File.SetLastAccessTimeUtc(FullPath,value);
-                _dataInitialised = -1;
-#endif // !FEATURE_CORECLR
             }
         }
 
@@ -255,13 +201,10 @@ namespace System.IO {
 
         [ComVisible(false)]
         public DateTime LastWriteTimeUtc {
-            [System.Security.SecuritySafeCritical]
             get {
-#if FEATURE_CORECLR
                 // get_LastWriteTime also depends on this security check
                 FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
                 sourceState.EnsureState();
-#endif
                 if (_dataInitialised == -1) {
                     _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
                     Refresh();
@@ -276,30 +219,20 @@ namespace System.IO {
             }
 
             set {
-#if !FEATURE_CORECLR
-                if (this is DirectoryInfo)
-                    Directory.SetLastWriteTimeUtc(FullPath,value);
-                else
-                    File.SetLastWriteTimeUtc(FullPath,value);
-                _dataInitialised = -1;
-#endif // !FEATURE_CORECLR
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Refresh()
         {
             _dataInitialised = File.FillAttributeInfo(FullPath, ref _data, false, false);
         }
 
         public FileAttributes Attributes {
-            [System.Security.SecuritySafeCritical]
             get
             {
-#if FEATURE_CORECLR
                 FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
                 sourceState.EnsureState();
-#endif
+
                 if (_dataInitialised == -1) {
                     _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
                     Refresh(); // Call refresh to intialise the data
@@ -310,15 +243,8 @@ namespace System.IO {
 
                 return (FileAttributes) _data.fileAttributes;
             }
-#if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-#else
-            [System.Security.SecuritySafeCritical]
-#endif
+
             set {
-#if !FEATURE_CORECLR
-                new FileIOPermission(FileIOPermissionAccess.Write, FullPath).Demand();
-#endif
                 bool r = Win32Native.SetFileAttributes(FullPath, (int) value);
                 if (!r) {
                     int hr = Marshal.GetLastWin32Error();
@@ -337,14 +263,9 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ComVisible(false)]
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
         {
-#if !FEATURE_CORECLR
-            new FileIOPermission(FileIOPermissionAccess.PathDiscovery, FullPath).Demand();
-#endif
-
             info.AddValue("OriginalPath", OriginalPath, typeof(String));
             info.AddValue("FullPath", FullPath, typeof(String));
         }
index 137c8a6..bdddc83 100644 (file)
@@ -19,6 +19,7 @@ using System;
 using System.Runtime;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Threading;
 using System.Threading.Tasks;
@@ -180,7 +181,6 @@ namespace System.IO {
         public override void Flush() {
         }
 
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public override Task FlushAsync(CancellationToken cancellationToken) {
 
@@ -259,7 +259,7 @@ namespace System.IO {
             if (n > count) n = count;
             if (n < 0) n = 0;
 
-            Contract.Assert(_position + n >= 0, "_position + n >= 0");  // len is less than 2^31 -1.
+            Debug.Assert(_position + n >= 0, "_position + n >= 0");  // len is less than 2^31 -1.
             _position += n;
             return n;
         }
@@ -342,7 +342,7 @@ namespace System.IO {
             if (n <= 0)
                 return 0;
 
-            Contract.Assert(_position + n >= 0, "_position + n >= 0");  // len is less than 2^31 -1.
+            Debug.Assert(_position + n >= 0, "_position + n >= 0");  // len is less than 2^31 -1.
 
             if (n <= 8)
             {
@@ -357,7 +357,6 @@ namespace System.IO {
             return n;
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
         {
@@ -379,7 +378,7 @@ namespace System.IO {
             {
                 int n = Read(buffer, offset, count);
                 var t = _lastReadTask;
-                Contract.Assert(t == null || t.Status == TaskStatus.RanToCompletion, 
+                Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion, 
                     "Expected that a stored last task completed successfully");
                 return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
             }
@@ -504,7 +503,7 @@ namespace System.IO {
                 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
             }
 
-            Contract.Assert(_position >= 0, "_position >= 0");
+            Debug.Assert(_position >= 0, "_position >= 0");
             return _position;
         }
         
@@ -527,7 +526,7 @@ namespace System.IO {
             EnsureWriteable();
 
             // Origin wasn't publicly exposed above.
-            Contract.Assert(MemStreamMaxLength == Int32.MaxValue);  // Check parameter validation logic in this method if this fails.
+            Debug.Assert(MemStreamMaxLength == Int32.MaxValue);  // Check parameter validation logic in this method if this fails.
             if (value > (Int32.MaxValue - _origin)) {
                 throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
             }
@@ -590,7 +589,6 @@ namespace System.IO {
 
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
         {
index 4fd54f5..890669f 100644 (file)
@@ -15,6 +15,7 @@
 ===========================================================*/
 using System;
 using System.Runtime.InteropServices;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.IO {
@@ -24,13 +25,11 @@ namespace System.IO {
         private GCHandle _pinningHandle;
 
         // The new inheritance model requires a Critical default ctor since base (UnmanagedMemoryStream) has one
-        [System.Security.SecurityCritical]
         private PinnedBufferMemoryStream():base(){}
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal PinnedBufferMemoryStream(byte[] array)
         {
-            Contract.Assert(array != null, "Array can't be null");
+            Debug.Assert(array != null, "Array can't be null");
 
             int len = array.Length;
             // Handle 0 length byte arrays specially.
@@ -52,7 +51,6 @@ namespace System.IO {
             Dispose(false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected override void Dispose(bool disposing)
         {
             if (_isOpen) {
index 4b52e87..3cdfad6 100644 (file)
 **
 ===========================================================*/
 using System;
-#if FEATURE_CORECLR
 using System.Buffers;
-#endif
 using System.Threading;
 using System.Threading.Tasks;
-
 using System.Runtime;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
 using System.Runtime.ExceptionServices;
 using System.Security;
 using System.Security.Permissions;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Reflection;
 
@@ -111,13 +109,11 @@ namespace System.IO {
             }
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public Task CopyToAsync(Stream destination)
         {
             int bufferSize = _DefaultCopyBufferSize;
 
-#if FEATURE_CORECLR
             if (CanSeek)
             {
                 long length = Length;
@@ -146,19 +142,16 @@ namespace System.IO {
                         bufferSize = (int)Math.Min(bufferSize, remaining);
                 }
             }
-#endif // FEATURE_CORECLR
-            
+
             return CopyToAsync(destination, bufferSize);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public Task CopyToAsync(Stream destination, Int32 bufferSize)
         {
             return CopyToAsync(destination, bufferSize, CancellationToken.None);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
         {
@@ -174,7 +167,6 @@ namespace System.IO {
             Contract.Requires(CanRead);
             Contract.Requires(destination.CanWrite);
 
-#if FEATURE_CORECLR
             byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
             bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine
             try
@@ -192,15 +184,6 @@ namespace System.IO {
                 Array.Clear(buffer, 0, bufferSize); // clear only the most we used
                 ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
             }
-#else
-            byte[] buffer = new byte[bufferSize];
-            while (true)
-            {
-                int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
-                if (bytesRead == 0) break;
-                await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
-            }
-#endif
         }
 
         // Reads the bytes from the current stream and writes the bytes to
@@ -210,7 +193,6 @@ namespace System.IO {
         {
             int bufferSize = _DefaultCopyBufferSize;
 
-#if FEATURE_CORECLR
             if (CanSeek)
             {
                 long length = Length;
@@ -229,8 +211,7 @@ namespace System.IO {
                         bufferSize = (int)Math.Min(bufferSize, remaining);
                 }
             }
-#endif // FEATURE_CORECLR
-            
+
             CopyTo(destination, bufferSize);
         }
 
@@ -238,7 +219,6 @@ namespace System.IO {
         {
             StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
 
-#if FEATURE_CORECLR
             byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
             int highwaterMark = 0;
             try
@@ -255,14 +235,6 @@ namespace System.IO {
                 Array.Clear(buffer, 0, highwaterMark); // clear only the most we used
                 ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
             }
-#else
-            byte[] buffer = new byte[bufferSize];
-            int read;
-            while ((read = Read(buffer, 0, buffer.Length)) != 0)
-            {
-                destination.Write(buffer, 0, read);
-            }
-#endif
         }
 
         // Stream used to require that all cleanup logic went into Close(),
@@ -306,14 +278,12 @@ namespace System.IO {
 
         public abstract void Flush();
 
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public Task FlushAsync()
         {
             return FlushAsync(CancellationToken.None);
         }
 
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public virtual Task FlushAsync(CancellationToken cancellationToken)
         {
@@ -328,14 +298,12 @@ namespace System.IO {
             return new ManualResetEvent(false);
         }
 
-        [HostProtection(ExternalThreading=true)]
         public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
         {
             Contract.Ensures(Contract.Result<IAsyncResult>() != null);
             return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
         }
 
-        [HostProtection(ExternalThreading = true)]
         internal IAsyncResult BeginReadInternal(
             byte[] buffer, int offset, int count, AsyncCallback callback, Object state, 
             bool serializeAsynchronously, bool apm)
@@ -367,7 +335,7 @@ namespace System.IO {
                 // As we're currently inside of it, we can get the current task
                 // and grab the parameters from it.
                 var thisTask = Task.InternalCurrent as ReadWriteTask;
-                Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
+                Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
 
                 try
                 {
@@ -430,14 +398,12 @@ namespace System.IO {
             }
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
         {
             return ReadAsync(buffer, offset, count, CancellationToken.None);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
         {
@@ -448,7 +414,6 @@ namespace System.IO {
                         : BeginEndReadAsync(buffer, offset, count);
         }
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern bool HasOverriddenBeginEndRead();
 
@@ -477,14 +442,12 @@ namespace System.IO {
 
 
 
-        [HostProtection(ExternalThreading=true)]
         public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
         {
             Contract.Ensures(Contract.Result<IAsyncResult>() != null);
             return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
         }
 
-        [HostProtection(ExternalThreading = true)]
         internal IAsyncResult BeginWriteInternal(
             byte[] buffer, int offset, int count, AsyncCallback callback, Object state, 
             bool serializeAsynchronously, bool apm)
@@ -516,7 +479,7 @@ namespace System.IO {
                 // As we're currently inside of it, we can get the current task
                 // and grab the parameters from it.
                 var thisTask = Task.InternalCurrent as ReadWriteTask;
-                Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
+                Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
 
                 try
                 {
@@ -549,20 +512,20 @@ namespace System.IO {
 
         private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
         {
-            Contract.Assert(readWriteTask != null);  // Should be Contract.Requires, but CCRewrite is doing a poor job with
+            Debug.Assert(readWriteTask != null);  // Should be Contract.Requires, but CCRewrite is doing a poor job with
                                                      // preconditions in async methods that await.  
-            Contract.Assert(asyncWaiter != null);    // Ditto
+            Debug.Assert(asyncWaiter != null);    // Ditto
 
             // If the wait has already completed, run the task.
             if (asyncWaiter.IsCompleted)
             {
-                Contract.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
+                Debug.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
                 RunReadWriteTask(readWriteTask);
             }                
             else  // Otherwise, wait for our turn, and then run the task.
             {
                 asyncWaiter.ContinueWith((t, state) => {
-                    Contract.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
+                    Debug.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
                     var rwt = (ReadWriteTask)state;
                     rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
                 }, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
@@ -572,7 +535,7 @@ namespace System.IO {
         private void RunReadWriteTask(ReadWriteTask readWriteTask)
         {
             Contract.Requires(readWriteTask != null);
-            Contract.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
+            Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
 
             // Schedule the task.  ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
             // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
@@ -586,7 +549,7 @@ namespace System.IO {
         private void FinishTrackingAsyncOperation()
         {
              _activeReadWriteTask = null;
-            Contract.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
+            Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
             _asyncActiveSemaphore.Release();
         }
 
@@ -613,7 +576,7 @@ namespace System.IO {
             try 
             {
                 writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
-                Contract.Assert(writeTask.Status == TaskStatus.RanToCompletion);
+                Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
             }
             finally
             {
@@ -654,7 +617,6 @@ namespace System.IO {
                 _buffer = null;
             }
 
-            [SecuritySafeCritical] // necessary for EC.Capture
             [MethodImpl(MethodImplOptions.NoInlining)]
             public ReadWriteTask(
                 bool isRead,
@@ -692,7 +654,6 @@ namespace System.IO {
                 }
             }
 
-            [SecurityCritical] // necessary for CoreCLR
             private static void InvokeAsyncCallback(object completedTask)
             {
                 var rwc = (ReadWriteTask)completedTask;
@@ -701,10 +662,8 @@ namespace System.IO {
                 callback(rwc);
             }
 
-            [SecurityCritical] // necessary for CoreCLR
             private static ContextCallback s_invokeAsyncCallback;
             
-            [SecuritySafeCritical] // necessary for ExecutionContext.Run
             void ITaskCompletionAction.Invoke(Task completingTask)
             {
                 // Get the ExecutionContext.  If there is none, just run the callback
@@ -731,7 +690,6 @@ namespace System.IO {
             bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public Task WriteAsync(Byte[] buffer, int offset, int count)
         {
@@ -740,7 +698,6 @@ namespace System.IO {
 
 
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
         {
@@ -751,7 +708,6 @@ namespace System.IO {
                         : BeginEndWriteAsync(buffer, offset, count);
         }
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern bool HasOverriddenBeginEndWrite();
 
@@ -813,7 +769,6 @@ namespace System.IO {
             Write(oneByteArray, 0, 1);
         }
 
-        [HostProtection(Synchronization=true)]
         public static Stream Synchronized(Stream stream) 
         {
             if (stream==null)
@@ -959,7 +914,6 @@ namespace System.IO {
                     Task.CompletedTask;
             }
 
-            [HostProtection(ExternalThreading = true)]
             public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
             {
                 if (!CanRead) __Error.ReadNotSupported();
@@ -976,7 +930,6 @@ namespace System.IO {
                 return BlockingEndRead(asyncResult);
             }
 
-            [HostProtection(ExternalThreading = true)]
             public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
             {
                 if (!CanWrite) __Error.WriteNotSupported();
@@ -1248,7 +1201,6 @@ namespace System.IO {
                     return _stream.ReadByte();
             }
         
-            [HostProtection(ExternalThreading=true)]
             public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
             {
                 bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
@@ -1302,7 +1254,6 @@ namespace System.IO {
                     _stream.WriteByte(b);
             }
         
-            [HostProtection(ExternalThreading=true)]
             public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
             {
                 bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
index 3b55805..33cca92 100644 (file)
@@ -18,6 +18,7 @@ using System;
 using System.Text;
 using System.Runtime.InteropServices;
 using System.Runtime.Versioning;
+using System.Diagnostics;
 using System.Diagnostics.CodeAnalysis;
 using System.Diagnostics.Contracts;
 using System.Security.Permissions;
@@ -187,12 +188,10 @@ namespace System.IO
             : this(path, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize) {
         }
 
-        [System.Security.SecuritySafeCritical]
         public StreamReader(String path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
             : this(path, encoding, detectEncodingFromByteOrderMarks, bufferSize, true) {
         }
 
-        [System.Security.SecurityCritical]
         internal StreamReader(String path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool checkHost)
         {
             // Don't open a Stream before checking for invalid arguments,
@@ -434,7 +433,7 @@ namespace System.IO
         // Trims n bytes from the front of the buffer.
         private void CompressBuffer(int n)
         {
-            Contract.Assert(byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length.  Are two threads using this StreamReader at the same time?");
+            Debug.Assert(byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length.  Are two threads using this StreamReader at the same time?");
             Buffer.InternalBlockCopy(byteBuffer, n, byteBuffer, 0, byteLen - n);
             byteLen -= n;
         }
@@ -502,7 +501,7 @@ namespace System.IO
             if (!_checkPreamble) 
                 return _checkPreamble;
 
-            Contract.Assert(bytePos <= _preamble.Length, "_compressPreamble was called with the current bytePos greater than the preamble buffer length.  Are two threads using this StreamReader at the same time?");
+            Debug.Assert(bytePos <= _preamble.Length, "_compressPreamble was called with the current bytePos greater than the preamble buffer length.  Are two threads using this StreamReader at the same time?");
             int len = (byteLen >= (_preamble.Length))? (_preamble.Length - bytePos) : (byteLen  - bytePos);
 
             for(int i=0; i<len; i++, bytePos++) {
@@ -513,7 +512,7 @@ namespace System.IO
                 }
             }
 
-            Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble.  Are two threads using this StreamReader at the same time?");
+            Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble.  Are two threads using this StreamReader at the same time?");
 
             if (_checkPreamble) {
                 if (bytePos == _preamble.Length) {
@@ -568,9 +567,9 @@ namespace System.IO
                 byteLen = 0;
             do {
                 if (_checkPreamble) {
-                    Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble.  Are two threads using this StreamReader at the same time?");
+                    Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble.  Are two threads using this StreamReader at the same time?");
                     int len = stream.Read(byteBuffer, bytePos, byteBuffer.Length - bytePos);
-                    Contract.Assert(len >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
+                    Debug.Assert(len >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
 
                     if (len == 0) {
                         // EOF but we might have buffered bytes from previous 
@@ -588,9 +587,9 @@ namespace System.IO
                     byteLen += len;
                 }
                 else {
-                    Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble.  Are two threads using this StreamReader at the same time?");
+                    Debug.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble.  Are two threads using this StreamReader at the same time?");
                     byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length);
-                    Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
+                    Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
 
                     if (byteLen == 0)  // We're at EOF
                         return charLen;
@@ -650,12 +649,12 @@ namespace System.IO
             readToUserBuffer = desiredChars >= _maxCharsPerBuffer;
 
             do {
-                Contract.Assert(charsRead == 0);
+                Debug.Assert(charsRead == 0);
 
                 if (_checkPreamble) {
-                    Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble.  Are two threads using this StreamReader at the same time?");
+                    Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble.  Are two threads using this StreamReader at the same time?");
                     int len = stream.Read(byteBuffer, bytePos, byteBuffer.Length - bytePos);
-                    Contract.Assert(len >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
+                    Debug.Assert(len >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
                     
                     if (len == 0) {
                         // EOF but we might have buffered bytes from previous 
@@ -677,11 +676,11 @@ namespace System.IO
                     byteLen += len;
                 }
                 else {
-                    Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble.  Are two threads using this StreamReader at the same time?");
+                    Debug.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble.  Are two threads using this StreamReader at the same time?");
 
                     byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length);
 
-                    Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
+                    Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
                     
                     if (byteLen == 0)  // EOF
                         break;
@@ -775,7 +774,6 @@ namespace System.IO
         }
         
         #region Task based Async APIs
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public override Task<String> ReadLineAsync()
         {
@@ -856,7 +854,6 @@ namespace System.IO
             return GetStringAndReleaseSharedStringBuilder(sb);
         }
 
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public override Task<String> ReadToEndAsync()
         {
@@ -893,7 +890,6 @@ namespace System.IO
             return GetStringAndReleaseSharedStringBuilder(sb);
         }
 
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public override Task<int> ReadAsync(char[] buffer, int index, int count)
         {
@@ -957,14 +953,14 @@ namespace System.IO
                     // We break out of the loop if the stream is blocked (EOF is reached).
                     do
                     {
-                        Contract.Assert(n == 0);
+                        Debug.Assert(n == 0);
 
                         if (CheckPreamble_Prop)
                         {
-                            Contract.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble.  Are two threads using this StreamReader at the same time?");
+                            Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble.  Are two threads using this StreamReader at the same time?");
                             int tmpBytePos = BytePos_Prop;
                             int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
-                            Contract.Assert(len >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
+                            Debug.Assert(len >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
 
                             if (len == 0)
                             {
@@ -985,7 +981,7 @@ namespace System.IO
                                 }
                                         
                                 // How can part of the preamble yield any chars?
-                                Contract.Assert(n == 0);
+                                Debug.Assert(n == 0);
 
                                 IsBlocked_Prop = true;
                                 break;
@@ -997,11 +993,11 @@ namespace System.IO
                         }
                         else
                         {
-                            Contract.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble.  Are two threads using this StreamReader at the same time?");
+                            Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble.  Are two threads using this StreamReader at the same time?");
 
                             ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
 
-                            Contract.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
+                            Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
 
                             if (ByteLen_Prop == 0)  // EOF
                             {
@@ -1031,7 +1027,7 @@ namespace System.IO
                             readToUserBuffer = count >= MaxCharsPerBuffer_Prop;
                         }
 
-                        Contract.Assert(n == 0);
+                        Debug.Assert(n == 0);
 
                         CharPos_Prop = 0;
                         if (readToUserBuffer)
@@ -1039,7 +1035,7 @@ namespace System.IO
                             n += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, buffer, index + charsRead);
                                         
                             // Why did the bytes yield no chars?
-                            Contract.Assert(n > 0);
+                            Debug.Assert(n > 0);
 
                             CharLen_Prop = 0;  // StreamReader's buffer is empty.
                         }
@@ -1048,7 +1044,7 @@ namespace System.IO
                             n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, 0);
                                         
                             // Why did the bytes yield no chars?
-                            Contract.Assert(n > 0);
+                            Debug.Assert(n > 0);
 
                             CharLen_Prop += n;  // Number of chars in StreamReader's buffer.
                         }
@@ -1081,7 +1077,6 @@ namespace System.IO
             return charsRead;
         }
 
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
         {
@@ -1185,10 +1180,10 @@ namespace System.IO
                 ByteLen_Prop = 0;
             do {
                 if (CheckPreamble_Prop) {
-                    Contract.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+                    Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
                     int tmpBytePos = BytePos_Prop;
                     int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
-                    Contract.Assert(len >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
+                    Debug.Assert(len >= 0, "Stream.Read returned a negative number!  This is a bug in your stream class.");
                     
                     if (len == 0) {
                         // EOF but we might have buffered bytes from previous 
@@ -1206,9 +1201,9 @@ namespace System.IO
                     ByteLen_Prop += len;
                 }
                 else {
-                    Contract.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+                    Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
                     ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
-                    Contract.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number!  Bug in stream class.");
+                    Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number!  Bug in stream class.");
                     
                     if (ByteLen_Prop == 0)  // We're at EOF
                         return CharLen_Prop;
index 61c96e6..49415d6 100644 (file)
@@ -21,6 +21,7 @@ using System.Runtime.CompilerServices;
 using System.Runtime.Versioning;
 using System.Security.Permissions;
 using System.Runtime.Serialization;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Threading.Tasks;
@@ -143,11 +144,9 @@ namespace System.IO
             : this(path, append, encoding, DefaultBufferSize) {
         }
 
-        [System.Security.SecuritySafeCritical]
         public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) { 
         }
 
-        [System.Security.SecurityCritical]  
         internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost)
             : base(null)
         { // Ask for CurrentCulture all the time
@@ -164,7 +163,6 @@ namespace System.IO
             Init(stream, encoding, bufferSize, false);
         }
 
-        [System.Security.SecuritySafeCritical]
         private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
         {
             this.stream = streamArg;
@@ -189,7 +187,6 @@ namespace System.IO
 #endif
         }
 
-        [System.Security.SecurityCritical]  
         private static Stream CreateFile(String path, bool append, bool checkHost) {
             FileMode mode = append? FileMode.Append: FileMode.Create;
             FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read,
@@ -210,11 +207,7 @@ namespace System.IO
                 // is generally the right thing to do.
                 if (stream != null) {
                     // Note: flush on the underlying stream can throw (ex., low disk space)
-#if FEATURE_CORECLR
                     if (disposing)
-#else
-                    if (disposing || (LeaveOpen && stream is __ConsoleStream))
-#endif
                     {
                         CheckAsyncTaskInProgress();
 
@@ -343,7 +336,7 @@ namespace System.IO
                 if (charPos == charLen) Flush(false, false);
                 int n = charLen - charPos;
                 if (n > count) n = count;
-                Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress!  This is most likely a race condition in user code.");
+                Debug.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress!  This is most likely a race condition in user code.");
                 Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
                 charPos += n;
                 index += n;
@@ -369,7 +362,7 @@ namespace System.IO
                 if (charPos == charLen) Flush(false, false);
                 int n = charLen - charPos;
                 if (n > count) n = count;
-                Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress!  This is most likely a race condition in user code.");
+                Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress!  This is most likely a race condition in user code.");
                 Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
                 charPos += n;
                 index += n;
@@ -391,7 +384,7 @@ namespace System.IO
                     if (charPos == charLen) Flush(false, false);
                     int n = charLen - charPos;
                     if (n > count) n = count;
-                    Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress!  This is most likely a race condition in user code.");
+                    Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress!  This is most likely a race condition in user code.");
                     value.CopyTo(index, charBuffer, charPos, n);
                     charPos += n;
                     index += n;
@@ -402,7 +395,6 @@ namespace System.IO
         }
 
         #region Task based Async APIs
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task WriteAsync(char value)
         {
@@ -433,7 +425,7 @@ namespace System.IO
         {            
             if (charPos == charLen) {
                 await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
-                Contract.Assert(_this.charPos == 0);
+                Debug.Assert(_this.charPos == 0);
                 charPos = 0;
             }
 
@@ -446,7 +438,7 @@ namespace System.IO
                 {
                     if (charPos == charLen) {                        
                         await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
-                        Contract.Assert(_this.charPos == 0);
+                        Debug.Assert(_this.charPos == 0);
                         charPos = 0;
                     }
 
@@ -457,14 +449,13 @@ namespace System.IO
 
             if (autoFlush) {
                 await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
-                Contract.Assert(_this.charPos == 0);
+                Debug.Assert(_this.charPos == 0);
                 charPos = 0;
             }
 
             _this.CharPos_Prop = charPos;
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task WriteAsync(String value)
         {
@@ -509,7 +500,7 @@ namespace System.IO
             {
                 if (charPos == charLen) {
                     await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
-                    Contract.Assert(_this.charPos == 0);
+                    Debug.Assert(_this.charPos == 0);
                     charPos = 0;
                 }
 
@@ -517,7 +508,7 @@ namespace System.IO
                 if (n > count)
                     n = count;
 
-                Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress!  This is most likely a race condition in user code.");
+                Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress!  This is most likely a race condition in user code.");
 
                 value.CopyTo(index, charBuffer, charPos, n);
 
@@ -532,7 +523,7 @@ namespace System.IO
                 {
                     if (charPos == charLen) {
                         await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
-                        Contract.Assert(_this.charPos == 0);
+                        Debug.Assert(_this.charPos == 0);
                         charPos = 0;
                     }
 
@@ -543,14 +534,13 @@ namespace System.IO
 
             if (autoFlush) {
                 await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
-                Contract.Assert(_this.charPos == 0);
+                Debug.Assert(_this.charPos == 0);
                 charPos = 0;
             }
 
             _this.CharPos_Prop = charPos;
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task WriteAsync(char[] buffer, int index, int count)
         {
@@ -598,14 +588,14 @@ namespace System.IO
             {
                 if (charPos == charLen) {
                     await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
-                    Contract.Assert(_this.charPos == 0);
+                    Debug.Assert(_this.charPos == 0);
                     charPos = 0;
                 }
 
                 int n = charLen - charPos;
                 if (n > count) n = count;
 
-                Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress!  This is most likely a race condition in user code.");
+                Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress!  This is most likely a race condition in user code.");
 
                 Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
 
@@ -620,7 +610,7 @@ namespace System.IO
                 {
                     if (charPos == charLen) {
                         await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
-                        Contract.Assert(_this.charPos == 0);
+                        Debug.Assert(_this.charPos == 0);
                         charPos = 0;
                     }
 
@@ -631,14 +621,13 @@ namespace System.IO
 
             if (autoFlush) {
                 await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
-                Contract.Assert(_this.charPos == 0);
+                Debug.Assert(_this.charPos == 0);
                 charPos = 0;
             }
 
             _this.CharPos_Prop = charPos;
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task WriteLineAsync()
         {
@@ -661,7 +650,6 @@ namespace System.IO
         }
         
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task WriteLineAsync(char value)
         {
@@ -684,7 +672,6 @@ namespace System.IO
         }
         
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task WriteLineAsync(String value)
         {
@@ -707,7 +694,6 @@ namespace System.IO
         }
 
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task WriteLineAsync(char[] buffer, int index, int count)
         {
@@ -740,7 +726,6 @@ namespace System.IO
         }
         
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task FlushAsync()
         {
index d5e5a52..ca05fa4 100644 (file)
@@ -172,7 +172,6 @@ namespace System.IO {
         }
 
         #region Task based Async APIs
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public virtual Task<String> ReadLineAsync()
         {
@@ -183,7 +182,6 @@ namespace System.IO {
             this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
         }
 
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public async virtual Task<String> ReadToEndAsync()
         {
@@ -197,7 +195,6 @@ namespace System.IO {
             return sb.ToString();
         }
 
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
         {
@@ -228,7 +225,6 @@ namespace System.IO {
             tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
         }
 
-        [HostProtection(ExternalThreading=true)]
         [ComVisible(false)]
         public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
         {
@@ -244,7 +240,6 @@ namespace System.IO {
             return ReadBlockAsyncInternal(buffer, index, count);
          }
 
-        [HostProtection(ExternalThreading=true)]
         private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count)
         {
             Contract.Requires(buffer != null);
@@ -263,7 +258,6 @@ namespace System.IO {
         }
         #endregion
 
-        [HostProtection(Synchronization=true)]
         public static TextReader Synchronized(TextReader reader) 
         {
             if (reader==null)
index de1bb0c..5b460a5 100644 (file)
@@ -124,7 +124,6 @@ namespace System.IO {
         }
     
 
-        [HostProtection(Synchronization=true)]
         public static TextWriter Synchronized(TextWriter writer) {
             if (writer==null)
                 throw new ArgumentNullException(nameof(writer));
@@ -486,7 +485,6 @@ namespace System.IO {
         }
 
         #region Task based Async APIs
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task WriteAsync(char value)
         {
@@ -499,7 +497,6 @@ namespace System.IO {
             tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task WriteAsync(String value)
         {
@@ -512,7 +509,6 @@ namespace System.IO {
             tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public Task WriteAsync(char[] buffer)
         {
@@ -520,7 +516,6 @@ namespace System.IO {
             return WriteAsync(buffer, 0, buffer.Length);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task WriteAsync(char[] buffer, int index, int count)
         {
@@ -533,7 +528,6 @@ namespace System.IO {
             tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task WriteLineAsync(char value)
         {
@@ -546,7 +540,6 @@ namespace System.IO {
             tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task WriteLineAsync(String value)
         {
@@ -559,7 +552,6 @@ namespace System.IO {
             tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public Task WriteLineAsync(char[] buffer)
         {
@@ -567,7 +559,6 @@ namespace System.IO {
             return WriteLineAsync(buffer, 0, buffer.Length);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task WriteLineAsync(char[] buffer, int index, int count)
         {
@@ -580,14 +571,12 @@ namespace System.IO {
             tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task WriteLineAsync()
         {
             return WriteAsync(CoreNewLine);
         }
 
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public virtual Task FlushAsync()
         {
index 354e7a9..4208ebf 100644 (file)
@@ -19,6 +19,7 @@ using System.Runtime.ConstrainedExecution;
 using System.Runtime.Versioning;
 using System.Security.Permissions;
 using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.IO {
@@ -28,7 +29,6 @@ namespace System.IO {
     /// this gives better throughput; benchmarks showed about 12-15% better.
     public class UnmanagedMemoryAccessor : IDisposable {
 
-        [System.Security.SecurityCritical] // auto-generated
         private SafeBuffer _buffer;
         private Int64 _offset;
         [ContractPublicPropertyName("Capacity")]
@@ -46,20 +46,14 @@ namespace System.IO {
         // <SecurityKernel Critical="True" Ring="1">
         // <ReferencesCritical Name="Method: Initialize(SafeBuffer, Int64, Int64, FileAccess):Void" Ring="1" />
         // </SecurityKernel>
-        [System.Security.SecuritySafeCritical]
         public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity) {
             Initialize(buffer, offset, capacity, FileAccess.Read);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) {
             Initialize(buffer, offset, capacity, access);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) {
             if (buffer == null) {
                 throw new ArgumentNullException(nameof(buffer));
@@ -155,7 +149,6 @@ namespace System.IO {
             return InternalReadByte(position);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public char ReadChar(Int64 position) {
             int sizeOfType = sizeof(char);
             EnsureSafeToRead(position, sizeOfType);
@@ -192,7 +185,6 @@ namespace System.IO {
         }
 
         // See comment above.
-        [System.Security.SecuritySafeCritical]
         public Int16 ReadInt16(Int64 position) {
             int sizeOfType = sizeof(Int16);
             EnsureSafeToRead(position, sizeOfType);
@@ -229,7 +221,6 @@ namespace System.IO {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Int32 ReadInt32(Int64 position) {
             int sizeOfType = sizeof(Int32);
             EnsureSafeToRead(position, sizeOfType);
@@ -264,7 +255,6 @@ namespace System.IO {
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Int64 ReadInt64(Int64 position) {
             int sizeOfType = sizeof(Int64);
             EnsureSafeToRead(position, sizeOfType);
@@ -301,7 +291,6 @@ namespace System.IO {
             return result;
         }
 
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         private unsafe Int32 UnsafeReadInt32(byte* pointer)
         {
@@ -318,7 +307,6 @@ namespace System.IO {
 
             return result;
         }
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Decimal ReadDecimal(Int64 position) {
             const int ScaleMask = 0x00FF0000;
             const int SignMask = unchecked((int)0x80000000);
@@ -360,7 +348,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Single ReadSingle(Int64 position) {
             int sizeOfType = sizeof(Single);
             EnsureSafeToRead(position, sizeOfType);
@@ -396,7 +383,6 @@ namespace System.IO {
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Double ReadDouble(Int64 position) {
             int sizeOfType = sizeof(Double);
             EnsureSafeToRead(position, sizeOfType);
@@ -436,7 +422,6 @@ namespace System.IO {
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public SByte ReadSByte(Int64 position) {
             int sizeOfType = sizeof(SByte);
@@ -461,7 +446,6 @@ namespace System.IO {
             return result;
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public UInt16 ReadUInt16(Int64 position) {
             int sizeOfType = sizeof(UInt16);
@@ -498,7 +482,6 @@ namespace System.IO {
             return result;
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public UInt32 ReadUInt32(Int64 position) {
             int sizeOfType = sizeof(UInt32);
@@ -535,7 +518,6 @@ namespace System.IO {
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public UInt64 ReadUInt64(Int64 position) {
             int sizeOfType = sizeof(UInt64);
@@ -588,7 +570,6 @@ namespace System.IO {
         // such, it is best to use the ReadXXX methods for small standard types such as ints, longs, 
         // bools, etc.
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void Read<T>(Int64 position, out T structure) where T : struct {
             if (position < 0) {
                 throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -621,7 +602,6 @@ namespace System.IO {
         // struct that contains reference members will most likely cause the runtime to AV. This
         // is consistent with Marshal.PtrToStructure.
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public int ReadArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct {
             if (array == null) {
                 throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
@@ -695,7 +675,6 @@ namespace System.IO {
             InternalWrite(position, value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Write(Int64 position, char value) {
             int sizeOfType = sizeof(char);
             EnsureSafeToWrite(position, sizeOfType);
@@ -730,7 +709,6 @@ namespace System.IO {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Write(Int64 position, Int16 value) {
             int sizeOfType = sizeof(Int16);
             EnsureSafeToWrite(position, sizeOfType);
@@ -764,7 +742,6 @@ namespace System.IO {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Write(Int64 position, Int32 value) {
             int sizeOfType = sizeof(Int32);
             EnsureSafeToWrite(position, sizeOfType);
@@ -799,7 +776,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Write(Int64 position, Int64 value) {
             int sizeOfType = sizeof(Int64);
             EnsureSafeToWrite(position, sizeOfType);
@@ -837,7 +813,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         private unsafe void UnsafeWriteInt32(byte* pointer, Int32 value)
         {
@@ -855,7 +830,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Write(Int64 position, Decimal value) {
             int sizeOfType = sizeof(Decimal);
             EnsureSafeToWrite(position, sizeOfType);
@@ -889,7 +863,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Write(Int64 position, Single value) {
             int sizeOfType = sizeof(Single);
             EnsureSafeToWrite(position, sizeOfType);
@@ -925,7 +898,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Write(Int64 position, Double value) {
             int sizeOfType = sizeof(Double);
             EnsureSafeToWrite(position, sizeOfType);
@@ -965,7 +937,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public void Write(Int64 position, SByte value) {
             int sizeOfType = sizeof(SByte);
@@ -987,7 +958,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public void Write(Int64 position, UInt16 value) {
             int sizeOfType = sizeof(UInt16);
@@ -1021,7 +991,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public void Write(Int64 position, UInt32 value) {
             int sizeOfType = sizeof(UInt32);
@@ -1058,7 +1027,6 @@ namespace System.IO {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public void Write(Int64 position, UInt64 value) {
             int sizeOfType = sizeof(UInt64);
@@ -1103,7 +1071,6 @@ namespace System.IO {
         // though this is number is JIT and architecture dependent).   As such, it is best to use 
         // the WriteX methods for small standard types such as ints, longs, bools, etc.
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void Write<T>(Int64 position, ref T structure) where T : struct {
             if (position < 0) {
                 throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -1133,7 +1100,6 @@ namespace System.IO {
         // Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory. 
 
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void WriteArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct {
             if (array == null) {
                 throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
@@ -1165,11 +1131,10 @@ namespace System.IO {
             _buffer.WriteArray<T>((UInt64)(_offset + position), array, offset, count);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private byte InternalReadByte(Int64 position) {
-            Contract.Assert(CanRead, "UMA not readable");
-            Contract.Assert(position >= 0, "position less than 0");
-            Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
+            Debug.Assert(CanRead, "UMA not readable");
+            Debug.Assert(position >= 0, "position less than 0");
+            Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
 
             byte result;
             unsafe {
@@ -1188,11 +1153,10 @@ namespace System.IO {
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private void InternalWrite(Int64 position, byte value) {
-            Contract.Assert(CanWrite, "UMA not writable");
-            Contract.Assert(position >= 0, "position less than 0");
-            Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
+            Debug.Assert(CanWrite, "UMA not writable");
+            Debug.Assert(position >= 0, "position less than 0");
+            Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
 
             unsafe {
                 byte* pointer = null;
index 8573428..d786326 100644 (file)
@@ -19,6 +19,7 @@ using System.Runtime.InteropServices;
 using System.Security;
 using System.Security.Permissions;
 using System.Threading;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Threading.Tasks; 
 
@@ -85,9 +86,7 @@ namespace System.IO {
     {
         private const long UnmanagedMemStreamMaxLength = Int64.MaxValue;
 
-        [System.Security.SecurityCritical] // auto-generated
         private SafeBuffer _buffer;
-        [SecurityCritical]
         private unsafe byte* _mem;
         private long _length;
         private long _capacity;
@@ -100,7 +99,6 @@ namespace System.IO {
 
 
         // Needed for subclasses that need to map a file, etc.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected UnmanagedMemoryStream()
         {
             unsafe {
@@ -109,12 +107,10 @@ namespace System.IO {
             _isOpen = false;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) {
             Initialize(buffer, offset, length, FileAccess.Read, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) {
             Initialize(buffer, offset, length, access, false);
         }
@@ -122,17 +118,14 @@ namespace System.IO {
         // We must create one of these without doing a security check.  This
         // class is created while security is trying to start up.  Plus, doing
         // a Demand from Assembly.GetManifestResourceStream isn't useful.
-        [System.Security.SecurityCritical]  // auto-generated
         internal UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
             Initialize(buffer, offset, length, access, skipSecurityCheck);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) {
             Initialize(buffer, offset, length, access, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
             if (buffer == null) {
                 throw new ArgumentNullException(nameof(buffer));
@@ -185,14 +178,12 @@ namespace System.IO {
             _isOpen = true;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         public unsafe UnmanagedMemoryStream(byte* pointer, long length)
         {
             Initialize(pointer, length, length, FileAccess.Read, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access) 
         {
@@ -202,20 +193,17 @@ namespace System.IO {
         // We must create one of these without doing a security check.  This
         // class is created while security is trying to start up.  Plus, doing
         // a Demand from Assembly.GetManifestResourceStream isn't useful.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) 
         {
             Initialize(pointer, length, capacity, access, skipSecurityCheck);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) 
         {
             Initialize(pointer, length, capacity, access, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) 
         {
             if (pointer == null)
@@ -262,7 +250,6 @@ namespace System.IO {
             get { return _isOpen && (_access & FileAccess.Write) != 0; }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected override void Dispose(bool disposing)
         {
             _isOpen = false;
@@ -278,7 +265,6 @@ namespace System.IO {
             if (!_isOpen) __Error.StreamIsClosed();
         }
         
-        [HostProtection(ExternalThreading=true)] 
         [ComVisible(false)] 
         public override Task FlushAsync(CancellationToken cancellationToken) { 
         
@@ -317,7 +303,6 @@ namespace System.IO {
                 Contract.EndContractBlock();
                 return Interlocked.Read(ref _position);
             }
-            [System.Security.SecuritySafeCritical]  // auto-generated
             set {
                 if (value < 0)
                     throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -337,7 +322,6 @@ namespace System.IO {
 
         [CLSCompliant(false)]
         public unsafe byte* PositionPointer {
-            [System.Security.SecurityCritical]  // auto-generated_required
             get {
                 if (_buffer != null) {
                     throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
@@ -351,7 +335,6 @@ namespace System.IO {
                 if (!_isOpen) __Error.StreamIsClosed();
                 return ptr;
             }
-            [System.Security.SecurityCritical]  // auto-generated_required
             set {
                 if (_buffer != null)
                     throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
@@ -369,7 +352,6 @@ namespace System.IO {
         }
 
         internal unsafe byte* Pointer {
-            [System.Security.SecurityCritical]  // auto-generated
             get {
                 if (_buffer != null)
                     throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
@@ -378,7 +360,6 @@ namespace System.IO {
             }
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override int Read([In, Out] byte[] buffer, int offset, int count) {
             if (buffer==null)
                 throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
@@ -406,7 +387,7 @@ namespace System.IO {
             int nInt = (int) n; // Safe because n <= count, which is an Int32
             if (nInt < 0)
                 return 0;  // _position could be beyond EOF
-            Contract.Assert(pos + nInt >= 0, "_position + n >= 0");  // len is less than 2^63 -1.
+            Debug.Assert(pos + nInt >= 0, "_position + n >= 0");  // len is less than 2^63 -1.
 
             unsafe
             {
@@ -440,7 +421,6 @@ namespace System.IO {
             return nInt;
         }
         
-        [HostProtection(ExternalThreading = true)]
         [ComVisible(false)]
         public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {        
             if (buffer==null)
@@ -464,12 +444,11 @@ namespace System.IO {
                 
             } catch (Exception ex) { 
             
-                Contract.Assert(! (ex is OperationCanceledException));
+                Debug.Assert(! (ex is OperationCanceledException));
                 return Task.FromException<Int32>(ex); 
             } 
         } 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override int ReadByte() {
             if (!_isOpen) __Error.StreamIsClosed();
             if (!CanRead) __Error.ReadNotSupported();
@@ -533,11 +512,10 @@ namespace System.IO {
             }
 
             long finalPos = Interlocked.Read(ref _position);
-            Contract.Assert(finalPos >= 0, "_position >= 0");
+            Debug.Assert(finalPos >= 0, "_position >= 0");
             return finalPos;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override void SetLength(long value) {
             if (value < 0)
                 throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -563,7 +541,6 @@ namespace System.IO {
             } 
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override void Write(byte[] buffer, int offset, int count) {
             if (buffer==null)
                 throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
@@ -641,7 +618,6 @@ namespace System.IO {
             return;
         }
         
-        [HostProtection(ExternalThreading = true)] 
         [ComVisible(false)] 
         public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { 
         
@@ -665,13 +641,12 @@ namespace System.IO {
                 
             } catch (Exception ex) { 
             
-                Contract.Assert(! (ex is OperationCanceledException));
+                Debug.Assert(! (ex is OperationCanceledException));
                 return Task.FromException<Int32>(ex); 
             } 
         } 
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override void WriteByte(byte value) {
             if (!_isOpen) __Error.StreamIsClosed();
             if (!CanWrite) __Error.WriteNotSupported();
index 6b25b08..040ddbb 100644 (file)
@@ -106,7 +106,6 @@ namespace System.IO {
             return _unmanagedStream.Seek(offset, loc);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe override byte[] ToArray() {
             if (!_unmanagedStream._isOpen) __Error.StreamIsClosed();
             if (!_unmanagedStream.CanRead) __Error.ReadNotSupported();
index c67bc96..ad4972d 100644 (file)
@@ -74,7 +74,6 @@ namespace System.IO {
         // discovery permission to that path.  If we do not, return just the 
         // file name.  If we know it is a directory, then don't return the 
         // directory name.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static String GetDisplayablePath(String path, bool isInvalidPath)
         {
             
@@ -97,9 +96,6 @@ namespace System.IO {
             bool safeToReturn = false;
             try {
                 if (!isInvalidPath) {
-#if !FEATURE_CORECLR
-                    new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { path }, false, false).Demand();
-#endif
                     safeToReturn = true;
                 }
             }
@@ -125,7 +121,6 @@ namespace System.IO {
             return path;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static void WinIOError() {
             int errorCode = Marshal.GetLastWin32Error();
             WinIOError(errorCode, String.Empty);
@@ -136,7 +131,6 @@ namespace System.IO {
         // will determine the appropriate exception to throw dependent on your 
         // error, and depending on the error, insert a string into the message 
         // gotten from the ResourceManager.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void WinIOError(int errorCode, String maybeFullPath) {
             // This doesn't have to be perfect, but is a perf optimization.
             bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME;
@@ -195,13 +189,11 @@ namespace System.IO {
         }
 
         // An alternative to WinIOError with friendlier messages for drives
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static void WinIODriveError(String driveName) {
             int errorCode = Marshal.GetLastWin32Error();
             WinIODriveError(driveName, errorCode);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void WinIODriveError(String driveName, int errorCode)
         {
             switch (errorCode) {
index 0adc64c..f02a5f2 100644 (file)
@@ -71,13 +71,11 @@ namespace System {
         }
     
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
@@ -93,7 +91,6 @@ namespace System {
             return ToString(format, NumberFormatInfo.GetInstance(provider));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private String ToString(String format, NumberFormatInfo info) {
             Contract.Ensures(Contract.Result<String>() != null);
 
index 778a893..2da55bf 100644 (file)
@@ -77,21 +77,18 @@ namespace System {
             return m_value;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Pure]
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Pure]
         public String ToString(String format) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Pure]
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
@@ -99,7 +96,6 @@ namespace System {
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format, IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
index 0cd2558..e5fcf86 100644 (file)
@@ -76,25 +76,21 @@ namespace System {
             return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt64(m_value, null, NumberFormatInfo.CurrentInfo);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt64(m_value, format, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format, IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
index b7674af..2d66652 100644 (file)
@@ -26,13 +26,11 @@ namespace System {
     [System.Runtime.InteropServices.ComVisible(true)]
     public struct IntPtr : IEquatable<IntPtr>, ISerializable
     {
-        [SecurityCritical]
         unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior
                 
         public static readonly IntPtr Zero;
 
         // fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Pure]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal unsafe bool IsNull()
@@ -40,7 +38,6 @@ namespace System {
             return (this.m_value == null);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe IntPtr(int value)
@@ -52,7 +49,6 @@ namespace System {
 #endif
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe IntPtr(long value)
@@ -64,7 +60,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecurityCritical]
         [CLSCompliant(false)]
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         [System.Runtime.Versioning.NonVersionable]
@@ -73,7 +68,6 @@ namespace System {
             m_value = value;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe IntPtr(SerializationInfo info, StreamingContext context) {
             long l = info.GetInt64("value");
 
@@ -84,7 +78,6 @@ namespace System {
             m_value = (void *)l;
         }
 
-        [System.Security.SecurityCritical]
         unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
@@ -97,7 +90,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe override bool Equals(Object obj) {
             if (obj is IntPtr) {
                 return (m_value == ((IntPtr)obj).m_value);
@@ -105,27 +97,20 @@ namespace System {
             return false;
         }
 
-        [SecuritySafeCritical]
         unsafe bool IEquatable<IntPtr>.Equals(IntPtr other)
         {
             return m_value == other.m_value;
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe override int GetHashCode() {
-#if FEATURE_CORECLR
 #if BIT64
             long l = (long)m_value;
             return (unchecked((int)l) ^ (int)(l >> 32));
 #else // !BIT64 (32)
             return unchecked((int)m_value);
 #endif
-#else
-            return unchecked((int)((long)m_value));
-#endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe int ToInt32() {
@@ -137,7 +122,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe long ToInt64() {
@@ -148,7 +132,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe override String ToString() {
 #if BIT64
                 return ((long)m_value).ToString(CultureInfo.InvariantCulture);
@@ -157,7 +140,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe  String ToString(String format) 
         {
             Contract.Ensures(Contract.Result<String>() != null);
@@ -184,7 +166,6 @@ namespace System {
             return new IntPtr(value);
         }
 
-        [System.Security.SecurityCritical]
         [CLSCompliant(false), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         [System.Runtime.Versioning.NonVersionable]
         public static unsafe explicit operator IntPtr (void* value)
@@ -192,7 +173,6 @@ namespace System {
             return new IntPtr(value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.Versioning.NonVersionable]
         public static unsafe explicit operator void* (IntPtr value)
@@ -200,7 +180,6 @@ namespace System {
             return value.m_value;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static explicit operator int (IntPtr  value) 
         {
@@ -212,7 +191,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static explicit operator long (IntPtr  value) 
         {
@@ -223,7 +201,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool operator == (IntPtr value1, IntPtr value2) 
@@ -231,7 +208,6 @@ namespace System {
             return value1.m_value == value2.m_value;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool operator != (IntPtr value1, IntPtr value2) 
@@ -289,7 +265,6 @@ namespace System {
         }
     
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [System.Runtime.Versioning.NonVersionable]
index c6be49f..0eb2bce 100644 (file)
@@ -85,16 +85,15 @@ namespace System
             new Dictionary<Object, UInt32>();
             new Dictionary<UInt32, Object>();
             new Dictionary<Int64, Object>();
-#if FEATURE_CORECLR
+
             // to genereate mdil for Dictionary instantiation when key is user defined value type
             new Dictionary<Guid, Int32>();
-#endif
 
-        // Microsoft.Windows.Design
+            // Microsoft.Windows.Design
             new Dictionary<System.Reflection.MemberTypes, Object>();
             new EnumEqualityComparer<System.Reflection.MemberTypes>();
 
-        // Microsoft.Expression.DesignModel
+            // Microsoft.Expression.DesignModel
             new Dictionary<Object, KeyValuePair<Object,Object>>();
             new Dictionary<KeyValuePair<Object,Object>, Object>();
 
@@ -157,14 +156,12 @@ namespace System
             SZArrayHelper<CustomAttributeTypedArgument>(null);
             SZArrayHelper<CustomAttributeNamedArgument>(null);
 
-#if FEATURE_CORECLR
 #pragma warning disable 4014
             // This is necessary to generate MDIL for AsyncVoidMethodBuilder
             AsyncHelper<int>();
             AsyncHelper2<int>();
             AsyncHelper3();
 #pragma warning restore 4014
-#endif
         }
 
         static T NullableHelper<T>() where T : struct
@@ -183,7 +180,6 @@ namespace System
             oSZArrayHelper.GetEnumerator<T>();
         }
 
-#if FEATURE_CORECLR
         // System.Runtime.CompilerServices.AsyncVoidMethodBuilder
         // System.Runtime.CompilerServices.TaskAwaiter
         static async void AsyncHelper<T>()
@@ -203,7 +199,6 @@ namespace System
         {
             await Task.FromResult<string>("");
         }
-#endif
 
 #if FEATURE_COMINTEROP
 
@@ -214,7 +209,6 @@ namespace System
         // typed as matching instantiations of mscorlib copies of WinRT interfaces (IIterable<T>, IVector<T>,
         // IMap<K, V>, ...) which is necessary to generate all required IL stubs.
 
-        [SecurityCritical]
         static void CommonlyUsedWinRTRedirectedInterfaceStubs()
         {
             WinRT_IEnumerable<byte>(null, null, null);
@@ -261,7 +255,6 @@ namespace System
             WinRT_Nullable<double>();
         }
 
-        [SecurityCritical]
         static void WinRT_IEnumerable<T>(IterableToEnumerableAdapter iterableToEnumerableAdapter, EnumerableToIterableAdapter enumerableToIterableAdapter, IIterable<T> iterable)
         {
             // instantiate stubs for the one method on IEnumerable<T> and the one method on IIterable<T>
@@ -269,7 +262,6 @@ namespace System
             enumerableToIterableAdapter.First_Stub<T>();
         }
 
-        [SecurityCritical]
         static void WinRT_IList<T>(VectorToListAdapter vectorToListAdapter, VectorToCollectionAdapter vectorToCollectionAdapter, ListToVectorAdapter listToVectorAdapter, IVector<T> vector)
         {
             WinRT_IEnumerable<T>(null, null, null);
@@ -294,7 +286,6 @@ namespace System
             listToVectorAdapter.Clear<T>();
         }
 
-        [SecurityCritical]
         static void WinRT_IReadOnlyCollection<T>(VectorViewToReadOnlyCollectionAdapter vectorViewToReadOnlyCollectionAdapter)
         {
             WinRT_IEnumerable<T>(null, null, null);
@@ -303,7 +294,6 @@ namespace System
             vectorViewToReadOnlyCollectionAdapter.Count<T>();
         }
 
-        [SecurityCritical]
         static void WinRT_IReadOnlyList<T>(IVectorViewToIReadOnlyListAdapter vectorToListAdapter, IReadOnlyListToIVectorViewAdapter listToVectorAdapter, IVectorView<T> vectorView)
         {
             WinRT_IEnumerable<T>(null, null, null);
@@ -317,7 +307,6 @@ namespace System
             listToVectorAdapter.Size<T>();
         }
 
-        [SecurityCritical]
         static void WinRT_IDictionary<K, V>(MapToDictionaryAdapter mapToDictionaryAdapter, MapToCollectionAdapter mapToCollectionAdapter, DictionaryToMapAdapter dictionaryToMapAdapter, IMap<K, V> map)
         {
             WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
@@ -343,7 +332,6 @@ namespace System
             dictionaryToMapAdapter.Clear<K, V>();
         }
 
-        [SecurityCritical]
         static void WinRT_IReadOnlyDictionary<K, V>(IMapViewToIReadOnlyDictionaryAdapter mapToDictionaryAdapter, IReadOnlyDictionaryToIMapViewAdapter dictionaryToMapAdapter, IMapView<K, V> mapView, MapViewToReadOnlyCollectionAdapter mapViewToReadOnlyCollectionAdapter)
         {
             WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
@@ -364,7 +352,6 @@ namespace System
             dictionaryToMapAdapter.HasKey<K, V>(default(K));
         }
 
-        [SecurityCritical]
         static void WinRT_Nullable<T>() where T : struct
         {
             Nullable<T> nullable = new Nullable<T>();
index 2c57bc8..f334754 100644 (file)
@@ -2,16 +2,14 @@
 // 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 {
-   using  System.Runtime.Serialization;
-   using  System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
 
+namespace System
+{
    [Serializable]
    [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
-   [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
-   public class InvalidTimeZoneException : Exception {
+   public class InvalidTimeZoneException : Exception
+   {
        public InvalidTimeZoneException(String message)
            : base(message) { }
 
index 07863d1..85cbb98 100644 (file)
@@ -48,9 +48,6 @@ namespace System
     /// </remarks>
     [Serializable]
     [ComVisible(false)]
-#if !FEATURE_CORECLR
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
-#endif
     [DebuggerTypeProxy(typeof(System_LazyDebugView<>))]
     [DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")]
     public class Lazy<T>
@@ -90,7 +87,7 @@ namespace System
         // 2- Flag to m_threadSafeObj if ExecutionAndPublication mode and the value is known to be initialized
         static readonly Func<T> ALREADY_INVOKED_SENTINEL = delegate 
         {
-            Contract.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
+            Debug.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
             return default(T);
         };
 
@@ -336,18 +333,12 @@ namespace System
                     }
 
                     LazyInternalExceptionHolder exc = m_boxed as LazyInternalExceptionHolder;
-                    Contract.Assert(exc != null);
+                    Debug.Assert(exc != null);
                     exc.m_edi.Throw();
                 }
 
                 // Fall through to the slow path.
-#if !FEATURE_CORECLR
-                // We call NOCTD to abort attempts by the debugger to funceval this property (e.g. on mouseover)
-                //   (the debugger proxy is the correct way to look at state/value of this object)
-                Debugger.NotifyOfCrossThreadDependency(); 
-#endif
                 return LazyInitValue();
-               
             }
         }
 
@@ -391,7 +382,7 @@ namespace System
                     if (threadSafeObj != (object)ALREADY_INVOKED_SENTINEL)
                         Monitor.Enter(threadSafeObj, ref lockTaken);
                     else
-                        Contract.Assert(m_boxed != null);
+                        Debug.Assert(m_boxed != null);
 
                     if (m_boxed == null)
                     {
@@ -405,7 +396,7 @@ namespace System
                         if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder
                         {
                             LazyInternalExceptionHolder exHolder = m_boxed as LazyInternalExceptionHolder;
-                            Contract.Assert(exHolder != null);
+                            Debug.Assert(exHolder != null);
                             exHolder.m_edi.Throw();
                         }
                     }
@@ -416,7 +407,7 @@ namespace System
                         Monitor.Exit(threadSafeObj);
                 }
             }
-            Contract.Assert(boxed != null);
+            Debug.Assert(boxed != null);
             return boxed.m_value;
         }
 
index 3aba3db..316583e 100644 (file)
@@ -16,16 +16,13 @@ namespace System
 
     public static class Console
     {
-        [SecurityCritical]
         static SafeFileHandle _outputHandle;
 
-        [SecuritySafeCritical]
         static Console()
         {
             _outputHandle = new SafeFileHandle(Win32Native.GetStdHandle(Win32Native.STD_OUTPUT_HANDLE), false);
         }
 
-        [SecuritySafeCritical]
         public static unsafe void Write(string s)
         {
             byte[] bytes = Encoding.UTF8.GetBytes(s);
index 8b6a843..53ebda7 100644 (file)
 **
 **
 ===========================================================*/
-namespace System {
-    
-    using System;
-    using System.Security;
-    using System.Security.Permissions;
-    using System.Threading;
-    using System.Runtime.Remoting;
-#if FEATURE_REMOTING    
-    using System.Runtime.Remoting.Lifetime;
-    using System.Runtime.Remoting.Services;
-#endif
-    using System.Runtime.InteropServices;
-    using System.Reflection;
-    using System.Runtime.CompilerServices;
-    using System.Runtime.Versioning;
-    using System.Diagnostics.Contracts;
-    using CultureInfo = System.Globalization.CultureInfo;
-
+namespace System
+{
     [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class MarshalByRefObject 
     {
-#if FEATURE_REMOTING
-        private Object __identity;        
-
-        private Object Identity { get { return __identity; } set { __identity = value; } }        
-#if FEATURE_COMINTEROP
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        internal IntPtr GetComIUnknown(bool fIsBeingMarshalled)
-        {
-            IntPtr pUnk;
-            if(RemotingServices.IsTransparentProxy(this))
-            {
-                pUnk = RemotingServices.GetRealProxy(this).GetCOMIUnknown(fIsBeingMarshalled);
-            }
-            else
-            {
-                pUnk = Marshal.GetIUnknownForObject(this);
-            }
-            return pUnk;
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        internal static extern IntPtr GetComIUnknown(MarshalByRefObject o);
-#endif // FEATURE_COMINTEROP
-
-        // (1) for remote COM objects IsInstance of can't be executed on
-        // the proxies, so we need this method to be executed on the 
-        // actual object.
-        // (2) for remote objects that do not have the complete type information
-        // we intercept calls to check the type and execute it on the actual
-        // object
-        internal bool IsInstanceOfType(Type T)
-        {
-            return T.IsInstanceOfType(this);
-        }
-
-        // for remote COM Objects the late binding methods can't be
-        // executed on proxies, so we need this method to execute on
-        // the real object
-        internal Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, 
-                            Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters)
-        {
-            Type t = GetType();
-            
-            // Sanity check
-            if(!t.IsCOMObject)
-                throw new InvalidOperationException(Environment.GetResourceString("Arg_InvokeMember"));
-
-            // Call into the runtime to invoke on the COM object.
-            return t.InvokeMember(name, invokeAttr, binder, this, args, modifiers, culture, namedParameters);
-        }
-
-
-        // Returns a new cloned MBR instance that is a memberwise copy of this
-        // with the identity nulled out, so there are no identity conflicts
-        // when the cloned object is marshalled
-        protected MarshalByRefObject MemberwiseClone(bool cloneIdentity)
-        {
-            MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone();
-            // set the identity on the cloned object to null
-            if (!cloneIdentity)
-                mbr.Identity = null;
-            return mbr;
-        }
-        
-        // A helper routine to extract the identity either from the marshalbyrefobject base
-        // class if it is not a proxy, otherwise from the real proxy.
-        // A flag is set to indicate whether the object passed in is a server or a proxy
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        internal static Identity GetIdentity(MarshalByRefObject obj, out bool fServer)
-        {
-            fServer = true;
-            Identity id = null;
-
-            if(null != obj)
-            {
-                if(!RemotingServices.IsTransparentProxy(obj))
-                {
-                    id = (Identity)obj.Identity;
-                }
-                else
-                {                    
-                    // Toggle flag to indicate that we have a proxy
-                    fServer = false;
-                    id = RemotingServices.GetRealProxy(obj).IdentityObject;
-                }
-            }
-
-            return id;
-        }
-
-        // Another helper that delegates to the helper above
-        internal static Identity GetIdentity(MarshalByRefObject obj)
-        {
-            Contract.Assert(!RemotingServices.IsTransparentProxy(obj), "Use this method for server objects only");
-
-            bool fServer;            
-            return GetIdentity(obj, out fServer);
-        }
-
-       
-        internal ServerIdentity __RaceSetServerIdentity(ServerIdentity id)
-        {
-            if (__identity == null)
-            {
-                // For strictly MBR types, the TP field in the identity
-                // holds the real server
-                if (!id.IsContextBound)
-                {
-                    id.RaceSetTransparentProxy(this);
-                }
-                Interlocked.CompareExchange(ref __identity, id, null);
-            }
-            return (ServerIdentity)__identity;
-        }
-
-
-        internal void __ResetServerIdentity()
-        {
-            __identity = null;
-        }
-        
-       // This method is used return a lifetime service object which
-       // is used to control the lifetime policy to the object.
-       // For the default Lifetime service this will be an object of typoe ILease.
-       // 
-        [System.Security.SecurityCritical]  // auto-generated_required
-        public Object GetLifetimeService()
-        {
-            return LifetimeServices.GetLease(this); 
-        }
-
-       // This method is used return lifetime service object. This method
-       // can be overridden to return a LifetimeService object with properties unique to
-       // this object.
-       // For the default Lifetime service this will be an object of type ILease.
-       // 
-        [System.Security.SecurityCritical]  // auto-generated_required
-        public virtual Object InitializeLifetimeService()
-        {
-            return LifetimeServices.GetLeaseInitial(this);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated_required
-        public virtual ObjRef CreateObjRef(Type requestedType)
-        {
-            if(__identity == null)
-            {
-                throw new RemotingException(Environment.GetResourceString(
-                    "Remoting_NoIdentityEntry"));
-            }            
-            return new ObjRef(this, requestedType);
-        }
-
-        // This is for casting interop ObjRefLite's.
-        // ObjRefLite's have been deprecated. These methods are not exposed 
-        // through any user APIs and would be removed in the future
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        internal bool CanCastToXmlType(String xmlTypeName, String xmlTypeNamespace)
-        {
-            Type castType = SoapServices.GetInteropTypeFromXmlType(xmlTypeName, xmlTypeNamespace);
-            if (castType == null)
-            {
-                String typeNamespace;
-                String assemblyName;
-                if (!SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlTypeNamespace, 
-                        out typeNamespace, out assemblyName))
-                    return false;
-
-                String typeName;
-                if ((typeNamespace != null) && (typeNamespace.Length > 0))
-                    typeName = typeNamespace + "." + xmlTypeName;
-                else
-                    typeName = xmlTypeName;
-
-                try
-                {
-                    Assembly asm = Assembly.Load(assemblyName);
-                    castType = asm.GetType(typeName, false, false);
-                }
-                catch 
-                {
-                    return false;
-                }
-            }
-
-            if (castType != null)
-                return castType.IsAssignableFrom(this.GetType());
-
-            return false;
-        } // CanCastToXmlType
-
-        // helper method for calling CanCastToXmlType
-        // ObjRefLite's have been deprecated. These methods are not exposed 
-        // through any user APIs and would be removed in the future
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        internal static bool CanCastToXmlTypeHelper(RuntimeType castType, MarshalByRefObject o)
-        {
-            if (castType == null)
-                throw new ArgumentNullException(nameof(castType));
-        
-            Contract.EndContractBlock();
-            // MarshalByRefObject's can only be casted to MarshalByRefObject's or interfaces.
-            if (!castType.IsInterface && !castType.IsMarshalByRef)
-                return false;
-
-            // figure out xml type name
-            String xmlTypeName = null;
-            String xmlTypeNamespace = null;
-            if (!SoapServices.GetXmlTypeForInteropType(castType, out xmlTypeName, out xmlTypeNamespace))
-            {
-                // There's no registered interop type name, so just use the default.
-                xmlTypeName = castType.Name;
-                xmlTypeNamespace =
-                    SoapServices.CodeXmlNamespaceForClrTypeNamespace(
-                        castType.Namespace, castType.GetRuntimeAssembly().GetSimpleName());
-            }
-
-            return o.CanCastToXmlType(xmlTypeName, xmlTypeNamespace);
-        } // CanCastToXmlType
-#else
         protected MarshalByRefObject() { }
         public object GetLifetimeService()
         {
@@ -270,7 +33,5 @@ namespace System {
             MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone();
             return mbr;
         }
-#endif // FEATURE_REMOTING
-
-    }            
-} // namespace    
+    }
+}
index 9ff0a9f..3ac1f06 100644 (file)
@@ -35,16 +35,12 @@ namespace System {
       public const double PI = 3.14159265358979323846;
       public const double E  = 2.7182818284590452354;
     
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Acos(double d);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Asin(double d);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Atan(double d);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Atan2(double y,double x);
       
@@ -52,15 +48,12 @@ namespace System {
         return Decimal.Ceiling(d);
       }
 
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Ceiling(double a);      
       
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Cos (double d);
 
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Cosh(double value);
       
@@ -68,11 +61,9 @@ namespace System {
         return Decimal.Floor(d);
       }
 
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Floor(double d);
       
-      [System.Security.SecuritySafeCritical]  // auto-generated
       private static unsafe double InternalRound(double value, int digits, MidpointRounding mode) {
         if (Abs(value) < doubleRoundLimit) {
             Double power10 = roundPower10Double[digits];
@@ -92,26 +83,20 @@ namespace System {
         return value;
       }           
       
-      [System.Security.SecuritySafeCritical]  // auto-generated
       private unsafe static double InternalTruncate(double d) {
         SplitFractionDouble(&d); 
         return d;                
       }            
       
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Sin(double a);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Tan(double a);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Sinh(double value);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Tanh(double value);
 
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Round(double a);
 
@@ -153,7 +138,6 @@ namespace System {
         return Decimal.Round(d, decimals, mode);
       }
 
-      [System.Security.SecurityCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       private static unsafe extern double SplitFractionDouble(double* value);
       
@@ -165,20 +149,15 @@ namespace System {
         return InternalTruncate(d);
       }
             
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Sqrt(double d);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Log (double d);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Log10(double d);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Exp(double d);
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       public static extern double Pow(double x, double y);
             
@@ -284,7 +263,6 @@ namespace System {
           return -value;
       }
     
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       extern public static float Abs(float value);
         // This is special code to handle NaN (We need to make sure NaN's aren't 
@@ -296,7 +274,6 @@ namespace System {
         // it runs the else case, which returns +value instead of negating it. 
         //  return (value < 0) ? -value : value;
     
-      [System.Security.SecuritySafeCritical]  // auto-generated
       [MethodImplAttribute(MethodImplOptions.InternalCall)]
       extern public static double Abs(double value);
         // This is special code to handle NaN (We need to make sure NaN's aren't 
index 12d0782..fb80092 100644 (file)
@@ -34,39 +34,30 @@ namespace System {
 
         public static float Abs(float x) => Math.Abs(x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Acos(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Asin(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Atan(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Atan2(float y, float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Ceiling(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Cos(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Cosh(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Exp(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Floor(float x);
 
@@ -121,7 +112,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Log(float x);
 
@@ -150,7 +140,6 @@ namespace System {
             return Log(x) / Log(y);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Log10(float x);
 
@@ -160,11 +149,9 @@ namespace System {
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static float Min(float x, float y) => Math.Min(x, y);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Pow(float x, float y);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Round(float x);
 
@@ -208,30 +195,24 @@ namespace System {
 
         public static int Sign(float x) => Math.Sign(x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Sin(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Sinh(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Sqrt(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Tan(float x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern float Tanh(float x);
 
         public static float Truncate(float x) => InternalTruncate(x);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static unsafe float InternalRound(float x, int digits, MidpointRounding mode)
         {
             if (Abs(x) < singleRoundLimit)
@@ -260,14 +241,12 @@ namespace System {
             return x;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static float InternalTruncate(float x)
         {
             SplitFractionSingle(&x);
             return x;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static unsafe extern float SplitFractionSingle(float* x);
     }
index 4196ea8..d96d037 100644 (file)
@@ -39,7 +39,6 @@ namespace System {
     
         public override String Message
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 if (ClassName == null) {
                     return base.Message;
index 07d516d..ab773dc 100644 (file)
@@ -48,7 +48,6 @@ namespace System {
     
         public override String Message
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 if (ClassName == null) {
                     return base.Message;
@@ -62,7 +61,6 @@ namespace System {
         }
     
         // Called to format signature
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern String FormatSignature(byte [] signature);
     
@@ -82,7 +80,6 @@ namespace System {
             MemberName  = memberName;
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
index cba33ef..7943490 100644 (file)
@@ -41,7 +41,6 @@ namespace System {
     
         public override String Message
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 if (ClassName == null) {
                     return base.Message;
index f59db16..a7b244c 100644 (file)
@@ -9,6 +9,7 @@ namespace System
     using System.Runtime;
     using System.Runtime.CompilerServices;
     using System.Runtime.Serialization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Reflection.Emit;
 
@@ -20,9 +21,7 @@ namespace System
         // 1. Multicast delegate
         // 2. Secure/Wrapper delegate
         // 3. Inner delegate of secure delegate where the secure delegate security context is a collectible method
-        [System.Security.SecurityCritical]
         private Object   _invocationList;
-        [System.Security.SecurityCritical]
         private IntPtr   _invocationCount;
 
         // This constructor is called from the class generated by the
@@ -39,19 +38,16 @@ namespace System
         {
         }
 
-        [System.Security.SecuritySafeCritical]
         internal bool IsUnmanagedFunctionPtr()
         {
             return (_invocationCount == (IntPtr)(-1));
         }
 
-        [System.Security.SecuritySafeCritical]
         internal bool InvocationListLogicallyNull()
         {
             return (_invocationList == null) || (_invocationList is LoaderAllocator) || (_invocationList is DynamicResolver);
         }
 
-        [System.Security.SecurityCritical]
         public override void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             int targetIndex = 0;
@@ -101,7 +97,6 @@ namespace System
 
         // equals returns true IIF the delegate is not null and has the
         //    same target, method and invocation list as this object
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override sealed bool Equals(Object obj)
         {
             if (obj == null)
@@ -114,7 +109,7 @@ namespace System
             // Since this is a MulticastDelegate and we know
             // the types are the same, obj should also be a
             // MulticastDelegate
-            Contract.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
+            Debug.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
             var d = JitHelpers.UnsafeCast<MulticastDelegate>(obj);
 
             if (_invocationCount != (IntPtr)0) 
@@ -151,7 +146,7 @@ namespace System
                     }
                     else 
                     {
-                        Contract.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
+                        Debug.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
                         return InvocationListEquals(d);
                     }
                 }
@@ -180,10 +175,9 @@ namespace System
         }
         
         // Recursive function which will check for equality of the invocation list.
-        [System.Security.SecuritySafeCritical]
         private bool InvocationListEquals(MulticastDelegate d)
         {
-            Contract.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison");
+            Debug.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison");
             Object[] invocationList = _invocationList as Object[];
             if (d._invocationCount != _invocationCount)
                 return false;
@@ -199,7 +193,6 @@ namespace System
             return true;
         }
 
-        [System.Security.SecurityCritical]
         private bool TrySetSlot(Object[] a, int index, Object o)
         {
             if (a[index] == null && System.Threading.Interlocked.CompareExchange<Object>(ref a[index], o, null) == null)
@@ -222,7 +215,6 @@ namespace System
             return false;
         }
 
-        [System.Security.SecurityCritical]
         private MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount, bool thisIsMultiCastAlready)
         {
             // First, allocate a new multicast delegate just like this one, i.e. same type as the this object
@@ -247,18 +239,16 @@ namespace System
             return result;
         }
 
-        [System.Security.SecurityCritical]
         internal MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount)
         {
             return NewMulticastDelegate(invocationList, invocationCount, false);
         }
 
-        [System.Security.SecurityCritical]
         internal void StoreDynamicMethod(MethodInfo dynamicMethod) 
         {
             if (_invocationCount != (IntPtr)0) 
             {
-                Contract.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
+                Debug.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
                 // must be a secure/wrapper one, unwrap and save
                 MulticastDelegate d = (MulticastDelegate)_invocationList;
                 d._methodBase = dynamicMethod;
@@ -270,7 +260,6 @@ namespace System
 
         // This method will combine this delegate with the passed delegate
         //    to form a new delegate.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected override sealed Delegate CombineImpl(Delegate follow)
         {
             if ((Object)follow == null) // cast to object for a more efficient test
@@ -356,7 +345,6 @@ namespace System
             }
         }
                                        
-        [System.Security.SecurityCritical]
         private Object[] DeleteFromInvocationList(Object[] invocationList, int invocationCount, int deleteIndex, int deleteCount)
         {
             Object[] thisInvocationList = _invocationList as Object[];
@@ -390,7 +378,6 @@ namespace System
         //    look at the invocation list.)  If this is found we remove it from
         //    this list and return a new delegate.  If its not found a copy of the
         //    current list is returned.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected override sealed Delegate RemoveImpl(Delegate value)
         {
             // There is a special case were we are removing using a delegate as
@@ -464,7 +451,6 @@ namespace System
         }
 
         // This method returns the Invocation list of this multicast delegate.
-        [System.Security.SecuritySafeCritical]
         public override sealed Delegate[] GetInvocationList()
         {
             Contract.Ensures(Contract.Result<Delegate[]>() != null);
@@ -505,7 +491,6 @@ namespace System
             return !d1.Equals(d2);
         }
         
-        [System.Security.SecuritySafeCritical]
         public override sealed int GetHashCode()
         {
             if (IsUnmanagedFunctionPtr())
@@ -528,7 +513,6 @@ namespace System
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         internal override Object GetTarget()
         {
             if (_invocationCount != (IntPtr)0) 
@@ -562,7 +546,6 @@ namespace System
             return base.GetTarget();
         }
 
-        [System.Security.SecuritySafeCritical]
         protected override MethodInfo GetMethodImpl()
         {
             if (_invocationCount != (IntPtr)0 && _invocationList != null)
@@ -613,7 +596,6 @@ namespace System
             throw new ArgumentException(Environment.GetResourceString("Arg_DlgtNullInst"));
         }
 
-        [System.Security.SecurityCritical]
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorClosed(Object target, IntPtr methodPtr)
         {
@@ -623,7 +605,6 @@ namespace System
             this._methodPtr = methodPtr;
         }
 
-        [System.Security.SecurityCritical]
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorClosedStatic(Object target, IntPtr methodPtr)
         {
@@ -631,7 +612,6 @@ namespace System
             this._methodPtr = methodPtr;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorRTClosed(Object target, IntPtr methodPtr)
         {
@@ -639,7 +619,6 @@ namespace System
             this._methodPtr = AdjustTarget(target, methodPtr);
         }
 
-        [System.Security.SecurityCritical]
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk)
         {
@@ -648,7 +627,6 @@ namespace System
             this._methodPtrAux = methodPtr;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorSecureClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
         {
@@ -661,7 +639,6 @@ namespace System
             this._invocationCount = GetInvokeMethod();
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorSecureClosedStatic(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
         {
@@ -674,7 +651,6 @@ namespace System
             this._invocationCount = GetInvokeMethod();
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorSecureRTClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
         {
@@ -687,7 +663,6 @@ namespace System
             this._invocationCount = GetInvokeMethod();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorSecureOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
         {
@@ -700,7 +675,6 @@ namespace System
             this._invocationCount = GetInvokeMethod();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk)
         {
@@ -709,7 +683,6 @@ namespace System
             this._methodPtrAux = GetCallStub(methodPtr);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorSecureVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
         {
@@ -722,7 +695,6 @@ namespace System
             this._invocationCount = GetInvokeMethod();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorCollectibleClosedStatic(Object target, IntPtr methodPtr, IntPtr gchandle)
         {
@@ -731,7 +703,6 @@ namespace System
             this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorCollectibleOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle)
         {
@@ -741,7 +712,6 @@ namespace System
             this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.DebuggerNonUserCode]
         private void CtorCollectibleVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle)
         {
index d108f92..3a896ce 100644 (file)
@@ -57,7 +57,6 @@ namespace System {
             get { return _offendingNumber; }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
index a4b88a9..3412c02 100644 (file)
@@ -11,6 +11,7 @@ namespace System {
     using System.Runtime.Versioning;
     using System.Security;
     using System.Text;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // The Number class implements methods for formatting and parsing
@@ -289,38 +290,28 @@ namespace System {
         private Number() {
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern String FormatDecimal(Decimal value, String format, NumberFormatInfo info);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern String FormatDouble(double value, String format, NumberFormatInfo info);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern String FormatInt32(int value, String format, NumberFormatInfo info);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern String FormatUInt32(uint value, String format, NumberFormatInfo info);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern String FormatInt64(long value, String format, NumberFormatInfo info);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern String FormatUInt64(ulong value, String format, NumberFormatInfo info);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern String FormatSingle(float value, String format, NumberFormatInfo info);
     
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public unsafe static extern Boolean NumberBufferToDecimal(byte* number, ref Decimal value);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal unsafe static extern Boolean NumberBufferToDouble(byte* number, ref Double value);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [System.Runtime.CompilerServices.FriendAccessAllowed]
-        [System.Security.SecurityCritical]  // auto-generated
         internal static extern unsafe string FormatNumberBuffer(byte* number, string format, NumberFormatInfo info, char* allDigits);
 
         // Constants used by number parsing
@@ -350,15 +341,12 @@ namespace System {
             // Enough space for NumberMaxDigit characters plus null and 3 32 bit integers and a pointer
             public static readonly Int32 NumberBufferBytes = 12 + ((NumberMaxDigits + 1) * 2) + IntPtr.Size;
 
-            [SecurityCritical]
             private Byte * baseAddress;
-            [SecurityCritical]
             public Char * digits;
             public Int32 precision;
             public Int32 scale;
             public Boolean sign;
 
-            [System.Security.SecurityCritical]  // auto-generated
             public NumberBuffer(Byte* stackBuffer) {
                 this.baseAddress = stackBuffer;
                 this.digits = (((Char*) stackBuffer) + 6);
@@ -367,7 +355,6 @@ namespace System {
                 this.sign = false;
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             public Byte* PackForNative() {
                 Int32* baseInteger = (Int32*) baseAddress;
                 baseInteger[0] = precision;
@@ -391,7 +378,6 @@ namespace System {
             return returnValue;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static Boolean HexNumberToUInt32(ref NumberBuffer number, ref UInt32 value) {
 
             Int32 i = number.scale;
@@ -399,7 +385,7 @@ namespace System {
                 return false;
             }
             Char* p = number.digits;
-            Contract.Assert(p != null, "");
+            Debug.Assert(p != null, "");
 
             UInt32 n = 0;
             while (--i >= 0) {
@@ -418,7 +404,7 @@ namespace System {
                                 newN += (UInt32)((*p - 'A') + 10);
                             }
                             else {
-                                Contract.Assert(*p >= 'a' && *p <= 'f', "");
+                                Debug.Assert(*p >= 'a' && *p <= 'f', "");
                                 newN += (UInt32)((*p - 'a') + 10);
                             }
                         }
@@ -436,7 +422,6 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static Boolean HexNumberToUInt64(ref NumberBuffer number, ref UInt64 value) {
 
             Int32 i = number.scale;
@@ -444,7 +429,7 @@ namespace System {
                 return false;
             }
             Char* p = number.digits;
-            Contract.Assert(p != null, "");
+            Debug.Assert(p != null, "");
             
             UInt64 n = 0;
             while (--i >= 0) {
@@ -463,7 +448,7 @@ namespace System {
                                 newN += (UInt64)((*p - 'A') + 10);
                             }
                             else {
-                                Contract.Assert(*p >= 'a' && *p <= 'f', "");
+                                Debug.Assert(*p >= 'a' && *p <= 'f', "");
                                 newN += (UInt64)((*p - 'a') + 10);
                             }
                         }
@@ -485,7 +470,6 @@ namespace System {
             return (((ch) == 0x20) || ((ch) >= 0x09 && (ch) <= 0x0D));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static Boolean NumberToInt32(ref NumberBuffer number, ref Int32 value) {
 
             Int32 i = number.scale;
@@ -493,7 +477,7 @@ namespace System {
                 return false;
             }
             char * p = number.digits;
-            Contract.Assert(p != null, "");
+            Debug.Assert(p != null, "");
             Int32 n = 0;
             while (--i >= 0) {
                 if ((UInt32)n > (0x7FFFFFFF / 10)) {
@@ -519,7 +503,6 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static Boolean NumberToInt64(ref NumberBuffer number, ref Int64 value) {
 
             Int32 i = number.scale;
@@ -527,7 +510,7 @@ namespace System {
                 return false;
             }
             char* p = number.digits;
-            Contract.Assert(p != null, "");
+            Debug.Assert(p != null, "");
             Int64 n = 0;
             while (--i >= 0) {
                 if ((UInt64)n > (0x7FFFFFFFFFFFFFFF / 10)) {
@@ -553,7 +536,6 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static Boolean NumberToUInt32(ref NumberBuffer number, ref UInt32 value) {
 
             Int32 i = number.scale;
@@ -561,7 +543,7 @@ namespace System {
                 return false;
             }
             char* p = number.digits;
-            Contract.Assert(p != null, "");
+            Debug.Assert(p != null, "");
             UInt32 n = 0;
             while (--i >= 0) {
                 if (n > (0xFFFFFFFF / 10)) {
@@ -581,7 +563,6 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static Boolean NumberToUInt64(ref NumberBuffer number, ref UInt64 value) {
 
             Int32 i = number.scale;
@@ -589,7 +570,7 @@ namespace System {
                 return false;
             }
             char * p = number.digits;
-            Contract.Assert(p != null, "");
+            Debug.Assert(p != null, "");
             UInt64 n = 0;
             while (--i >= 0) {
                 if (n > (0xFFFFFFFFFFFFFFFF / 10)) {
@@ -609,15 +590,13 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe static char * MatchChars(char* p, string str) {
             fixed (char* stringPointer = str) {
                 return MatchChars(p, stringPointer);
             }
         }
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe static char * MatchChars(char* p, char* str) {
-            Contract.Assert(p != null && str != null, "");
+            Debug.Assert(p != null && str != null, "");
 
             if (*str == '\0') {
                 return null;
@@ -634,7 +613,6 @@ namespace System {
             return null;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Decimal ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt) {
 
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -649,7 +627,6 @@ namespace System {
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Double ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt) {
             if (value == null) {
                 throw new ArgumentNullException(nameof(value));
@@ -683,7 +660,6 @@ namespace System {
             return d;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Int32 ParseInt32(String s, NumberStyles style, NumberFormatInfo info) {
 
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -705,7 +681,6 @@ namespace System {
             return i;           
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Int64 ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt) {
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
             NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -726,7 +701,6 @@ namespace System {
             return i;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe static Boolean ParseNumber(ref char * str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, Boolean parseDecimal) {
 
             const Int32 StateSign = 0x0001;
@@ -903,7 +877,6 @@ namespace System {
             return false;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Single ParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt) {
             if (value == null) {
                 throw new ArgumentNullException(nameof(value));
@@ -940,7 +913,6 @@ namespace System {
             return castSingle;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static UInt32 ParseUInt32(String value, NumberStyles options, NumberFormatInfo numfmt) {
 
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -963,7 +935,6 @@ namespace System {
             return i;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static UInt64 ParseUInt64(String value, NumberStyles options, NumberFormatInfo numfmt) {
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
             NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -983,14 +954,13 @@ namespace System {
             return i;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static void StringToNumber(String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, Boolean parseDecimal) {
     
             if (str == null) {
                 throw new ArgumentNullException(nameof(String));
             }
             Contract.EndContractBlock();
-            Contract.Assert(info != null, "");
+            Debug.Assert(info != null, "");
             fixed (char* stringPointer = str) {
                 char * p = stringPointer;
                 if (!ParseNumber(ref p, options, ref number, null, info , parseDecimal) 
@@ -1010,7 +980,6 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Boolean TryParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt, out Decimal result) {
 
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -1027,7 +996,6 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Boolean TryParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt, out Double result) {
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
             NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1043,7 +1011,6 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Boolean TryParseInt32(String s, NumberStyles style, NumberFormatInfo info, out Int32 result) {
 
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -1067,7 +1034,6 @@ namespace System {
             return true;           
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Boolean TryParseInt64(String s, NumberStyles style, NumberFormatInfo info, out Int64 result) {
 
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -1091,7 +1057,6 @@ namespace System {
             return true;           
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Boolean TryParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt, out Single result) {
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
             NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1113,7 +1078,6 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Boolean TryParseUInt32(String s, NumberStyles style, NumberFormatInfo info, out UInt32 result) {
 
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -1137,7 +1101,6 @@ namespace System {
             return true;           
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Boolean TryParseUInt64(String s, NumberStyles style, NumberFormatInfo info, out UInt64 result) {
 
             Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -1165,14 +1128,13 @@ namespace System {
             return TryStringToNumber(str, options, ref number, null, numfmt, parseDecimal);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.CompilerServices.FriendAccessAllowed]
         internal unsafe static Boolean TryStringToNumber(String str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, Boolean parseDecimal) {   
 
             if (str == null) {
                 return false;
             }
-            Contract.Assert(numfmt != null, "");
+            Debug.Assert(numfmt != null, "");
 
             fixed (char* stringPointer = str) {
                 char * p = stringPointer;
index 769c5a6..d8d9a0e 100644 (file)
@@ -12,7 +12,8 @@
 ** 
 ===========================================================*/
 
-namespace System {
+namespace System
+{
     using System;
     using System.Runtime;
     using System.Runtime.InteropServices;
@@ -23,9 +24,7 @@ namespace System {
     using CultureInfo = System.Globalization.CultureInfo;
     using FieldInfo = System.Reflection.FieldInfo;
     using BindingFlags = System.Reflection.BindingFlags;
-#if FEATURE_REMOTING        
-    using RemotingException = System.Runtime.Remoting.RemotingException;    
-#endif
+
 // The Object is the root class for all object in the CLR System. Object 
 // is the super class for all other CLR objects and provide a set of methods and low level
 // services to subclasses.  These services include object synchronization and support for clone
@@ -96,7 +95,6 @@ public class Object
     
     // Returns a Type object which represent this object instance.
     // 
-    [System.Security.SecuritySafeCritical]  // auto-generated
     [Pure]
     [MethodImplAttribute(MethodImplOptions.InternalCall)]
     public extern Type GetType();
@@ -114,14 +112,12 @@ public class Object
     // so that other object may only call this method on themselves.  It is entended to
     // support the ICloneable interface.
     // 
-    [System.Security.SecuritySafeCritical]  // auto-generated
     [MethodImplAttribute(MethodImplOptions.InternalCall)]
     protected extern Object MemberwiseClone();
     
    
     // Sets the value specified in the variant on the field
     // 
-    [System.Security.SecurityCritical]  // auto-generated
     private void FieldSetter(String typeName, String fieldName, Object val)
     {
         Contract.Requires(typeName != null);
@@ -135,26 +131,21 @@ public class Object
 
         // Make sure that the value is compatible with the type
         // of field
-#if FEATURE_REMOTING        
-        System.Runtime.Remoting.Messaging.Message.CoerceArg(val, fldInfo.FieldType);    
-#else
         Type pt=fldInfo.FieldType;
         if (pt.IsByRef) 
         {
             pt = pt.GetElementType();
         }
-    
+
         if (!pt.IsInstanceOfType(val))
         {
             val = Convert.ChangeType(val, pt, CultureInfo.InvariantCulture);
         }
 
-#endif
-
-        // Set the value            
+        // Set the value
         fldInfo.SetValue(this, val);
     }
-    
+
     // Gets the value specified in the variant on the field
     // 
     private void FieldGetter(String typeName, String fieldName, ref Object val)
@@ -166,7 +157,7 @@ public class Object
         FieldInfo fldInfo = GetFieldInfo(typeName, fieldName);
 
         // Get the value
-        val = fldInfo.GetValue(this);            
+        val = fldInfo.GetValue(this);
     }
 
     // Gets the field info object given the type name and field name.
@@ -190,13 +181,7 @@ public class Object
         
         if (null == t)
         {
-#if FEATURE_REMOTING         
-            throw new RemotingException(String.Format(
-                CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadType"),
-                                              typeName));
-#else
             throw new ArgumentException();
-#endif
         }
 
         FieldInfo fldInfo = t.GetField(fieldName, BindingFlags.Public | 
@@ -204,16 +189,9 @@ public class Object
                                                   BindingFlags.IgnoreCase);
         if(null == fldInfo)
         {
-#if FEATURE_REMOTING 
-            throw new RemotingException(String.Format(
-                CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadField"),
-                                              fieldName, typeName));            
-#else
             throw new ArgumentException();
-#endif
-
         }
-        
+
         return fldInfo;
     }
 }
@@ -233,22 +211,16 @@ internal class __Canon
 // This class is used to define the name of the base class library
 internal class CoreLib
 {
-
-#if FEATURE_CORECLR
     public const string Name = "System.Private.CoreLib";
-#else
-    public const string Name = "mscorlib";
-#endif 
 
     public static string FixupCoreLibName(string strToFixup)
     {
-#if FEATURE_CORECLR                        
         if (!String.IsNullOrEmpty(strToFixup))
         {    
             strToFixup = strToFixup.Replace("mscorlib", System.CoreLib.Name);
         }
-#endif   
-        return strToFixup;              
+
+        return strToFixup;
     }
 }
 
index cf92cef..d2eca37 100644 (file)
@@ -64,7 +64,6 @@ namespace System {
             objectName = info.GetString("ObjectName");
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             base.GetObjectData(info, context);
             info.AddValue("ObjectName",ObjectName,typeof(String));
index 1ed1e32..acae95a 100644 (file)
@@ -20,7 +20,6 @@ namespace System {
     {
         // ChangeType
         // This binder uses OLEAUT to change the type of the variant.
-        [System.Security.SecuritySafeCritical] // overrides transparent member
         public override Object ChangeType(Object value, Type type, CultureInfo cultureInfo)
         {
             Variant myValue = new Variant(value);
@@ -60,24 +59,6 @@ namespace System {
                 return Enum.Parse(type, value.ToString());
             }
 
-#if !FEATURE_CORECLR
-            // Special case the convertion from DBNull.
-            if (srcType == typeof(DBNull))
-            {
-                // The requested type is a DBNull so no convertion is required.            
-                if (type == typeof(DBNull))
-                    return value;
-
-                // Visual J++ supported converting from DBNull to null so customers
-                // have requested (via a CDCR) that DBNull be convertible to null.
-                // We don't however allow this when converting to a value class, since null
-                // doesn't make sense for these, or to object since this would change existing
-                // semantics.               
-                if ((type.IsClass && type != typeof(Object)) || type.IsInterface)
-                    return null;
-            }
-#endif //!FEATURE_CORECLR
-
             // Use the OA variant lib to convert primitive types.
             try
             {
@@ -107,7 +88,5 @@ namespace System {
                 throw new COMException(Environment.GetResourceString("Interop.COM_TypeMismatch"), unchecked((int)0x80020005));
             }
         }
-        
-        
     }
 }
index 7bdb2f3..a11d4bc 100644 (file)
@@ -71,7 +71,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void GetObjectData(SerializationInfo info, StreamingContext context) {
             if( info == null ) {
                 throw new ArgumentNullException(nameof(info));
index 01c2ae3..2a375f7 100644 (file)
@@ -33,41 +33,33 @@ namespace System {
         // NATIVE METHODS
         // For comments on these methods please see $\src\vm\COMUtilNative.cpp
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static long StringToLong(System.String s, int radix, int flags) {
             return StringToLong(s,radix,flags, null);
         }
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public unsafe extern static long StringToLong(System.String s, int radix, int flags, int* currPos);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static long StringToLong(System.String s, int radix, int flags, ref int currPos) {
             fixed(int * ppos = &currPos) {
                 return StringToLong( s, radix, flags, ppos);
             }
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static int StringToInt(System.String s, int radix, int flags) {            
             return StringToInt(s,radix,flags, null);
         }
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
         public unsafe extern static int StringToInt(System.String s, int radix, int flags, int* currPos);        
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static int StringToInt(System.String s, int radix, int flags, ref int currPos) {            
             fixed(int * ppos = &currPos) {
                 return StringToInt( s, radix, flags, ppos);
             }
         }        
     
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern static String IntToString(int l, int radix, int width, char paddingChar, int flags);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern static String LongToString(long l, int radix, int width, char paddingChar, int flags);
     }
index a8b48fd..72c43c3 100644 (file)
@@ -48,7 +48,7 @@ namespace System
             // sync ctx reference identity issues where the sync ctx for one thread could be Current on another.
             // If there is no current context, we use a default instance targeting the ThreadPool.
             m_synchronizationContext = SynchronizationContext.CurrentNoFlow ?? ProgressStatics.DefaultContext;
-            Contract.Assert(m_synchronizationContext != null);
+            Debug.Assert(m_synchronizationContext != null);
             m_invokeHandlers = new SendOrPostCallback(InvokeHandlers);
         }
 
index f5146f6..677e4aa 100644 (file)
@@ -48,9 +48,6 @@ namespace System.Reflection
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_Assembly))]
     [System.Runtime.InteropServices.ComVisible(true)]
-#pragma warning disable 618
-    [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
     public abstract class Assembly : _Assembly, IEvidenceFactory, ICustomAttributeProvider, ISerializable
     {
         protected Assembly() {}
@@ -103,7 +100,6 @@ namespace System.Reflection
             return base.GetHashCode();
         }
 
-        [System.Security.SecurityCritical]
         public static Assembly LoadFrom(String assemblyFile)
         {
             if(assemblyFile == null) 
@@ -113,7 +109,6 @@ namespace System.Reflection
         }
 
         // Locate an assembly for reflection by the name of the file containing the manifest.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly ReflectionOnlyLoadFrom(String assemblyFile)
         {
@@ -132,7 +127,6 @@ namespace System.Reflection
         }
 
         // Evidence is protected in Assembly.Load()
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [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.")]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly LoadFrom(String assemblyFile,
@@ -153,7 +147,6 @@ namespace System.Reflection
         }
 
         // Evidence is protected in Assembly.Load()
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [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.")]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly LoadFrom(String assemblyFile,
@@ -175,7 +168,6 @@ namespace System.Reflection
                 ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly LoadFrom(String assemblyFile,
                                         byte[] hashValue,
@@ -184,7 +176,6 @@ namespace System.Reflection
             throw new NotSupportedException(Environment.GetResourceString("NotSupported_AssemblyLoadFromHash"));
         }
 
-        [SecurityCritical]
         public static Assembly UnsafeLoadFrom(string assemblyFile)
         {
             return LoadFrom(assemblyFile);
@@ -192,7 +183,6 @@ namespace System.Reflection
 
         // Locate an assembly by the long form of the assembly name. 
         // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890"
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly Load(String assemblyString)
         {
@@ -207,7 +197,6 @@ namespace System.Reflection
         // Calls Type.GetType for WinRT types.
         // Note: Type.GetType fails for assembly names that start with weird characters like '['. By calling it for managed types we would 
         // break AppCompat.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         internal static Type GetType_Compat(String assemblyString, String typeName)
         {
@@ -237,7 +226,6 @@ namespace System.Reflection
         // Locate an assembly for reflection by the long form of the assembly name. 
         // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890"
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly ReflectionOnlyLoad(String assemblyString)
         {
@@ -247,7 +235,6 @@ namespace System.Reflection
             return RuntimeAssembly.InternalLoad(assemblyString, null,  ref stackMark, true /*forIntrospection*/);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public static Assembly Load(String assemblyString, Evidence assemblySecurity)
@@ -261,7 +248,6 @@ namespace System.Reflection
 
         // Locate an assembly by its name. The name can be strong or
         // weak. The assembly is loaded into the domain of the caller.
-        [System.Security.SecurityCritical] // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly Load(AssemblyName assemblyRef)
         {
@@ -281,7 +267,6 @@ namespace System.Reflection
 
         // Locate an assembly by its name. The name can be strong or
         // weak. The assembly is loaded into the domain of the caller.
-        [System.Security.SecurityCritical] // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBinder)
         {
@@ -299,7 +284,6 @@ namespace System.Reflection
             return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/, ptrLoadContextBinder);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public static Assembly Load(AssemblyName assemblyRef, Evidence assemblySecurity)
@@ -311,7 +295,6 @@ namespace System.Reflection
             return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
         public static Assembly LoadWithPartialName(String partialName)
         {
@@ -323,7 +306,6 @@ namespace System.Reflection
         // Loads the assembly with a COFF based IMAGE containing
         // an emitted assembly. The assembly is loaded into the domain
         // of the caller.
-        [System.Security.SecurityCritical] // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly Load(byte[] rawAssembly)
         {
@@ -338,7 +320,6 @@ namespace System.Reflection
         // Loads the assembly for reflection with a COFF based IMAGE containing
         // an emitted assembly. The assembly is loaded into the domain
         // of the caller.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly ReflectionOnlyLoad(byte[] rawAssembly)
         {
@@ -360,7 +341,6 @@ namespace System.Reflection
         // an emitted assembly. The assembly is loaded into the domain
         // of the caller. The second parameter is the raw bytes
         // representing the symbol store that matches the assembly.
-        [System.Security.SecurityCritical] // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly Load(byte[] rawAssembly,
                                     byte[] rawSymbolStore)
@@ -380,7 +360,6 @@ namespace System.Reflection
 
         // Load an assembly from a byte array, controlling where the grant set of this assembly is
         // propigated from.
-        [SecuritySafeCritical]
         [MethodImpl(MethodImplOptions.NoInlining)]  // Due to the stack crawl mark
         public static Assembly Load(byte[] rawAssembly,
                                     byte[] rawSymbolStore,
@@ -408,7 +387,6 @@ namespace System.Reflection
 
         private static Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>();
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Assembly LoadFile(String path)
         {
             Contract.Ensures(Contract.Result<Assembly>() != null);
@@ -438,7 +416,6 @@ namespace System.Reflection
             return result;
         }
 
-        [System.Security.SecurityCritical] // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly Load(Stream assemblyStream, Stream pdbStream)
         {
@@ -448,7 +425,6 @@ namespace System.Reflection
             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
             return RuntimeAssembly.InternalLoadFromStream(assemblyStream, pdbStream, ref stackMark);
         }
-        [System.Security.SecurityCritical] // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly Load(Stream assemblyStream)
         {
@@ -462,7 +438,6 @@ namespace System.Reflection
         /*
          * Get the assembly that the current code is running from.
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable 
         public static Assembly GetExecutingAssembly()
         {
@@ -470,7 +445,6 @@ namespace System.Reflection
             return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
         }
        
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Assembly GetCallingAssembly()
         {
@@ -481,7 +455,6 @@ namespace System.Reflection
             return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
         }
        
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Assembly GetEntryAssembly() {
             AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
             if (domainManager == null)
@@ -494,12 +467,10 @@ namespace System.Reflection
 #region public methods
         public virtual event ModuleResolveEventHandler ModuleResolve
         {
-            [System.Security.SecurityCritical]  // auto-generated_required
             add
             {
                 throw new NotImplementedException();
             }
-            [System.Security.SecurityCritical]  // auto-generated_required
             remove
             {
                 throw new NotImplementedException();
@@ -508,7 +479,6 @@ namespace System.Reflection
 
         public virtual String CodeBase
         {
-            [System.Security.SecurityCritical] // auto-generated
             get
             {
                 throw new NotImplementedException();
@@ -517,20 +487,17 @@ namespace System.Reflection
 
         public virtual String EscapedCodeBase
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return AssemblyName.EscapeCodeBase(CodeBase);
             }
         }
 
-        [System.Security.SecurityCritical] // auto-generated
         public virtual AssemblyName GetName()
         {
             return GetName(false);
         }
 
-        [System.Security.SecurityCritical] // auto-generated
         public virtual AssemblyName GetName(bool copiedName)
         {
             throw new NotImplementedException();
@@ -652,7 +619,6 @@ namespace System.Reflection
 
         public bool IsFullyTrusted
         {
-            [SecuritySafeCritical]
             get
             {
                 return true;
@@ -668,7 +634,6 @@ namespace System.Reflection
         }
 
         // ISerializable implementation
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             throw new NotImplementedException();
@@ -823,7 +788,6 @@ namespace System.Reflection
 
         // Returns the file in the File table of the manifest that matches the
         // given name.  (Name should not include path.)
-        [System.Security.SecurityCritical] // auto-generated
         public virtual FileStream GetFile(String name)
         {
             throw new NotImplementedException();
@@ -834,7 +798,6 @@ namespace System.Reflection
             return GetFiles(false);
         }
 
-        [System.Security.SecurityCritical] // auto-generated
         public virtual FileStream[] GetFiles(bool getResourceModules)
         {
             throw new NotImplementedException();
@@ -867,7 +830,6 @@ namespace System.Reflection
 
         public virtual String Location
         {
-            [System.Security.SecurityCritical] // auto-generated
             get
             {
                 throw new NotImplementedException();
@@ -977,7 +939,6 @@ namespace System.Reflection
 
         private ASSEMBLY_FLAGS Flags
         {
-            [SecuritySafeCritical]
             get
             {
                 if ((m_flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED) == 0)
@@ -1007,12 +968,10 @@ namespace System.Reflection
         
         public override event ModuleResolveEventHandler ModuleResolve
         {
-            [System.Security.SecurityCritical]  // auto-generated_required
             add
             {
                 _ModuleResolve += value;
             }
-            [System.Security.SecurityCritical]  // auto-generated_required
             remove
             {
                 _ModuleResolve -= value;
@@ -1021,14 +980,12 @@ namespace System.Reflection
 
         private const String s_localFilePrefix = "file:";
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetCodeBase(RuntimeAssembly assembly, 
                                                bool copiedName, 
                                                StringHandleOnStack retString);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal String GetCodeBase(bool copiedName)
         {
             String codeBase = null;
@@ -1038,7 +995,6 @@ namespace System.Reflection
 
         public override String CodeBase
         {
-            [System.Security.SecurityCritical] // auto-generated
             get {
                 String codeBase = GetCodeBase(false);
                 VerifyCodeBaseDiscovery(codeBase);
@@ -1054,7 +1010,6 @@ namespace System.Reflection
         // If the assembly is copied before it is loaded, the codebase will be set to the
         // actual file loaded if copiedName is true. If it is false, then the original code base
         // is returned.
-        [System.Security.SecurityCritical] // auto-generated
         public override AssemblyName GetName(bool copiedName)
         {
             AssemblyName an = new AssemblyName();
@@ -1088,14 +1043,12 @@ namespace System.Reflection
             return an;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetFullName(RuntimeAssembly assembly, StringHandleOnStack retString);
 
         public override String FullName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 // If called by Object.ToString(), return val may be NULL.
                 if (m_fullname == null)
@@ -1109,14 +1062,12 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod);
            
         public override MethodInfo EntryPoint
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 IRuntimeMethodInfo methodHandle = null;
                 GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle));
@@ -1128,7 +1079,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetType(RuntimeAssembly assembly, 
@@ -1138,7 +1088,6 @@ namespace System.Reflection
                                                         ObjectHandleOnStack type,
                                                         ObjectHandleOnStack keepAlive);
         
-        [System.Security.SecuritySafeCritical]
         public override Type GetType(String name, bool throwOnError, bool ignoreCase) 
         {
             // throw on null strings regardless of the value of "throwOnError"
@@ -1153,17 +1102,14 @@ namespace System.Reflection
             return type;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal extern static void GetForwardedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes); 
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Type[] GetExportedTypes()
         {
             Type[] types = null;
@@ -1173,7 +1119,6 @@ namespace System.Reflection
 
         public override IEnumerable<TypeInfo> DefinedTypes
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 List<RuntimeType> rtTypes = new List<RuntimeType>();
@@ -1190,7 +1135,6 @@ namespace System.Reflection
         }
 
         // Load a resource based on the NameSpace of the type.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public override Stream GetManifestResourceStream(Type type, String name)
         {
@@ -1198,7 +1142,6 @@ namespace System.Reflection
             return GetManifestResourceStream(type, name, false, ref stackMark);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public override Stream GetManifestResourceStream(String name)
         {
@@ -1207,7 +1150,6 @@ namespace System.Reflection
         }
 
         // ISerializable implementation
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info==null)
@@ -1269,7 +1211,6 @@ namespace System.Reflection
             return CustomAttributeData.GetCustomAttributesInternal(this);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         internal static RuntimeAssembly InternalLoadFrom(String assemblyFile, 
                                                          Evidence securityEvidence,
@@ -1292,7 +1233,6 @@ namespace System.Reflection
         }
 
         // Wrapper function to wrap the typical use of InternalLoad.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static RuntimeAssembly InternalLoad(String assemblyString,
                                                      Evidence assemblySecurity,
                                                      ref StackCrawlMark stackMark,
@@ -1301,7 +1241,6 @@ namespace System.Reflection
             return InternalLoad(assemblyString, assemblySecurity,  ref stackMark, IntPtr.Zero, forIntrospection);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         internal static RuntimeAssembly InternalLoad(String assemblyString,
                                                      Evidence assemblySecurity,
@@ -1323,7 +1262,6 @@ namespace System.Reflection
         }
         
         // Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static AssemblyName CreateAssemblyName(
             String assemblyString, 
             bool forIntrospection, 
@@ -1349,7 +1287,6 @@ namespace System.Reflection
         }
         
         // Wrapper function to wrap the typical use of InternalLoadAssemblyName.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static RuntimeAssembly InternalLoadAssemblyName(
             AssemblyName assemblyRef,
             Evidence assemblySecurity,
@@ -1363,7 +1300,6 @@ namespace System.Reflection
             return InternalLoadAssemblyName(assemblyRef, assemblySecurity, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static RuntimeAssembly InternalLoadAssemblyName(
             AssemblyName assemblyRef, 
             Evidence assemblySecurity,
@@ -1434,7 +1370,6 @@ namespace System.Reflection
         };
 
 #if FEATURE_APPX
-        [System.Security.SecuritySafeCritical]
         internal bool IsFrameworkAssembly()
         {
             ASSEMBLY_FLAGS flags = Flags;
@@ -1449,19 +1384,16 @@ namespace System.Reflection
             return (flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION) != 0;
         }
 
-        [System.Security.SecuritySafeCritical]
         private bool IsDesignerBindingContext()
         {
             return RuntimeAssembly.nIsDesignerBindingContext(this);
         }
 
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static bool nIsDesignerBindingContext(RuntimeAssembly assembly);
 #endif
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern RuntimeAssembly _nLoad(AssemblyName fileName,
                                                      String codeBase,
@@ -1474,7 +1406,6 @@ namespace System.Reflection
                                                      bool suppressSecurityChecks,
                                                      IntPtr ptrLoadContextBinder);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static RuntimeAssembly nLoad(AssemblyName fileName,
                                              String codeBase,
                                              Evidence assemblySecurity,
@@ -1490,7 +1421,6 @@ namespace System.Reflection
                 throwOnFileNotFound, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool IsReflectionOnly(RuntimeAssembly assembly);
 
@@ -1499,7 +1429,6 @@ namespace System.Reflection
         [ComVisible(false)]
         public override bool ReflectionOnly
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return IsReflectionOnly(GetNativeHandle());
@@ -1510,7 +1439,6 @@ namespace System.Reflection
         // an emitted assembly. The assembly is loaded into the domain
         // of the caller. Currently is implemented only for  UnmanagedMemoryStream
         // (no derived classes since we are not calling Read())
-        [System.Security.SecurityCritical] // auto-generated
         internal static RuntimeAssembly InternalLoadFromStream(Stream assemblyStream, Stream pdbStream, ref StackCrawlMark stackMark)
         {
             if (assemblyStream  == null)
@@ -1560,12 +1488,10 @@ namespace System.Reflection
 
         // Returns the module in this assembly with name 'name'
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetModule(RuntimeAssembly assembly, String name, ObjectHandleOnStack retModule);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Module GetModule(String name)
         {
             Module retModule = null;
@@ -1575,7 +1501,6 @@ namespace System.Reflection
 
         // Returns the file in the File table of the manifest that matches the
         // given name.  (Name should not include path.)
-        [System.Security.SecurityCritical] // auto-generated
         public override FileStream GetFile(String name)
         {
             RuntimeModule m = (RuntimeModule)GetModule(name);
@@ -1587,7 +1512,6 @@ namespace System.Reflection
                                   FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false);
         }
 
-        [System.Security.SecurityCritical] // auto-generated
         public override FileStream[] GetFiles(bool getResourceModules)
         {
             Module[] m = GetModules(getResourceModules);
@@ -1603,23 +1527,19 @@ namespace System.Reflection
         }
 
         // Returns the names of all the resources
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern String[] GetManifestResourceNames(RuntimeAssembly assembly);
 
         // Returns the names of all the resources
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String[] GetManifestResourceNames()
         {
             return GetManifestResourceNames(GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetExecutingAssembly(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark)
         {
             RuntimeAssembly retAssembly = null;
@@ -1628,17 +1548,14 @@ namespace System.Reflection
         }
         
         // Returns the names of all the resources
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override AssemblyName[] GetReferencedAssemblies()
         {
             return GetReferencedAssemblies(GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern int GetManifestResourceInfo(RuntimeAssembly assembly,
@@ -1647,7 +1564,6 @@ namespace System.Reflection
                                                           StringHandleOnStack retFileName,
                                                           StackCrawlMarkHandle stackMark);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
         {
@@ -1666,14 +1582,12 @@ namespace System.Reflection
                                                 (ResourceLocation) location);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetLocation(RuntimeAssembly assembly, StringHandleOnStack retString);
 
         public override String Location
         {
-            [System.Security.SecurityCritical] // auto-generated
             get {
                 String location = null;
 
@@ -1686,7 +1600,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetImageRuntimeVersion(RuntimeAssembly assembly, StringHandleOnStack retString);
@@ -1696,7 +1609,6 @@ namespace System.Reflection
         [ComVisible(false)]
         public override String ImageRuntimeVersion
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get{
                 String s = null;
                 GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s));
@@ -1705,27 +1617,23 @@ namespace System.Reflection
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static bool IsGlobalAssemblyCache(RuntimeAssembly assembly);
 
         public override bool GlobalAssemblyCache
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return false;
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static Int64 GetHostContext(RuntimeAssembly assembly);
 
         public override Int64 HostContext
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return 0;
@@ -1760,7 +1668,6 @@ namespace System.Reflection
 #endif // !PLATFORM_UNIX
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal Stream GetManifestResourceStream(
             Type type,
             String name,
@@ -1788,7 +1695,6 @@ namespace System.Reflection
         }
 
         // GetResource will return a pointer to the resources in memory.
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static unsafe extern byte* GetResource(RuntimeAssembly assembly,
@@ -1797,7 +1703,6 @@ namespace System.Reflection
                                                        StackCrawlMarkHandle stackMark,
                                                        bool skipSecurityCheck);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck)
         {
             ulong length = 0;
@@ -1815,7 +1720,6 @@ namespace System.Reflection
             return null;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetVersion(RuntimeAssembly assembly, 
@@ -1824,7 +1728,6 @@ namespace System.Reflection
                                               out int buildNum,
                                               out int revNum);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal Version GetVersion()
         {
             int majorVer, minorVer, build, revision;
@@ -1832,12 +1735,10 @@ namespace System.Reflection
             return new Version (majorVer, minorVer, build, revision);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetLocale(RuntimeAssembly assembly, StringHandleOnStack retString);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal CultureInfo GetLocale()
         {
             String locale = null;
@@ -1850,19 +1751,16 @@ namespace System.Reflection
             return new CultureInfo(locale);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool FCallIsDynamic(RuntimeAssembly assembly);
 
         public override bool IsDynamic
         {
-            [SecuritySafeCritical]
             get {
                 return FCallIsDynamic(GetNativeHandle());
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void VerifyCodeBaseDiscovery(String codeBase)
         {
             if ((codeBase != null) &&
@@ -1872,12 +1770,10 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName);
 
-        [SecuritySafeCritical]
         internal String GetSimpleName()
         {
             string name = null;
@@ -1885,35 +1781,29 @@ namespace System.Reflection
             return name;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static AssemblyHashAlgorithm GetHashAlgorithm(RuntimeAssembly assembly);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private AssemblyHashAlgorithm GetHashAlgorithm()
         {
             return GetHashAlgorithm(GetNativeHandle());
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private AssemblyNameFlags GetFlags()
         {
             return GetFlags(GetNativeHandle());
         }
 
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetRawBytes(RuntimeAssembly assembly, ObjectHandleOnStack retRawBytes);
 
         // Get the raw bytes of the assembly
-        [SecuritySafeCritical]
         internal byte[] GetRawBytes()
         {
             byte[] rawBytes = null;
@@ -1922,12 +1812,10 @@ namespace System.Reflection
             return rawBytes;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal byte[] GetPublicKey()
         {
             byte[] publicKey = null;
@@ -1935,12 +1823,10 @@ namespace System.Reflection
             return publicKey;
         }
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetGrantSet(RuntimeAssembly assembly, ObjectHandleOnStack granted, ObjectHandleOnStack denied);
 
-        [SecurityCritical]
         internal void GetGrantSet(out PermissionSet newGrant, out PermissionSet newDenied)
         {
             PermissionSet granted = null, denied = null;
@@ -1948,60 +1834,51 @@ namespace System.Reflection
             newGrant = granted; newDenied = denied;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private extern static bool IsAllSecurityCritical(RuntimeAssembly assembly);
 
         // Is everything introduced by this assembly critical
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsAllSecurityCritical()
         {
             return IsAllSecurityCritical(GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private extern static bool IsAllSecuritySafeCritical(RuntimeAssembly assembly);
 
         // Is everything introduced by this assembly safe critical
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsAllSecuritySafeCritical()
         {
             return IsAllSecuritySafeCritical(GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private extern static bool IsAllPublicAreaSecuritySafeCritical(RuntimeAssembly assembly);
 
         // Is everything introduced by this assembly safe critical
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsAllPublicAreaSecuritySafeCritical()
         {
             return IsAllPublicAreaSecuritySafeCritical(GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private extern static bool IsAllSecurityTransparent(RuntimeAssembly assembly);
 
         // Is everything introduced by this assembly transparent
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsAllSecurityTransparent()
         {
             return IsAllSecurityTransparent(GetNativeHandle());
         }
 
         // This method is called by the VM.
-        [System.Security.SecurityCritical]
         private RuntimeModule OnModuleResolveEvent(String moduleName)
         {
             ModuleResolveEventHandler moduleResolve = _ModuleResolve;
@@ -2034,7 +1911,6 @@ namespace System.Reflection
             return InternalGetSatelliteAssembly(culture, version, ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable  
         internal Assembly InternalGetSatelliteAssembly(CultureInfo culture,
                                                        Version version,
@@ -2049,7 +1925,6 @@ namespace System.Reflection
             return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable  
         internal RuntimeAssembly InternalGetSatelliteAssembly(String name,
                                                               CultureInfo culture,
@@ -2084,7 +1959,6 @@ namespace System.Reflection
         }
 
         // Helper method used by InternalGetSatelliteAssembly only. Not abstracted for use elsewhere.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable  
         private RuntimeAssembly InternalProbeForSatelliteAssemblyNextToParentAssembly(AssemblyName an,
                                                                                       String name,
@@ -2192,11 +2066,9 @@ namespace System.Reflection
             return retAssembly;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern RuntimeAssembly nLoadFile(String path, Evidence evidence);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern RuntimeAssembly nLoadImage(byte[] rawAssembly,
                                                           byte[] rawSymbolStore,
@@ -2205,7 +2077,6 @@ namespace System.Reflection
                                                           bool fIntrospection,
                                                           SecurityContextSource securityContextSource);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static internal extern unsafe void nLoadFromUnmanagedArray(bool fIntrospection, 
@@ -2216,7 +2087,6 @@ namespace System.Reflection
                                                                             StackCrawlMarkHandle stackMark,
                                                                             ObjectHandleOnStack retAssembly);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetModules(RuntimeAssembly assembly, 
@@ -2224,7 +2094,6 @@ namespace System.Reflection
                                               bool getResourceModules, 
                                               ObjectHandleOnStack retModuleHandles);
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private RuntimeModule[] GetModulesInternal(bool loadIfNotFound,
                                      bool getResourceModules)
         {
@@ -2243,11 +2112,9 @@ namespace System.Reflection
             return GetModulesInternal(false, getResourceModules);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int GetToken(RuntimeAssembly assembly);
     }
index 293cc9b..48eab33 100644 (file)
@@ -104,19 +104,12 @@ namespace System.Reflection {
     
         public String CodeBase
         {
-#if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-#endif
             get { return _CodeBase; }
-#if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-#endif
             set { _CodeBase = value; }
         }
     
         public String EscapedCodeBase
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (_CodeBase == null)
@@ -190,7 +183,6 @@ namespace System.Reflection {
          * if the file contains an assembly manifest. This method causes
          * the file to be opened and closed.
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static public AssemblyName GetAssemblyName(String assemblyFile)
         {
             if(assemblyFile == null)
@@ -231,7 +223,6 @@ namespace System.Reflection {
 
         // The compressed version of the public key formed from a truncated hash.
         // Will throw a SecurityException if _PublicKey is invalid
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public byte[] GetPublicKeyToken()
         {
             if (_PublicKeyToken == null)
@@ -280,7 +271,6 @@ namespace System.Reflection {
        
         public String FullName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return nToString();
             }
@@ -296,7 +286,6 @@ namespace System.Reflection {
                 return s;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
@@ -361,7 +350,6 @@ namespace System.Reflection {
             m_siInfo = info; 
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public AssemblyName(String assemblyName)
         {
             if (assemblyName == null)
@@ -375,7 +363,6 @@ namespace System.Reflection {
             nInit();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static public bool ReferenceMatchesDefinition(AssemblyName reference,
                                                              AssemblyName definition)
         {
@@ -390,7 +377,6 @@ namespace System.Reflection {
         
         /// "parse" tells us to parse the simple name of the assembly as if it was the full name
         /// almost never the right thing to do, but needed for compat
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern bool ReferenceMatchesDefinitionInternal(AssemblyName reference,
                                                                      AssemblyName definition,
@@ -398,11 +384,9 @@ namespace System.Reflection {
 
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void nInit(out RuntimeAssembly assembly, bool forIntrospection, bool raiseResolveEvent);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void nInit()
         {
             RuntimeAssembly dummy = null;
@@ -489,19 +473,15 @@ namespace System.Reflection {
 
         // This call opens and closes the file, but does not add the
         // assembly to the domain.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern AssemblyName nGetFileInformation(String s);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern String nToString();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern byte[] nGetPublicKeyToken();
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal String EscapeCodeBase(String codebase)
         {
             if (codebase == null)
index 8b34e77..9eaf74a 100644 (file)
@@ -8,6 +8,7 @@ namespace System.Reflection
 {
     using System;
     using System.Collections.Generic;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     internal static class Associates
@@ -35,7 +36,6 @@ namespace System.Reflection
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static unsafe RuntimeMethodInfo AssignAssociates(
             int tkMethod,
             RuntimeType declaredType,
@@ -44,8 +44,8 @@ namespace System.Reflection
             if (MetadataToken.IsNullToken(tkMethod))
                 return null;
 
-            Contract.Assert(declaredType != null);
-            Contract.Assert(reflectedType != null);
+            Debug.Assert(declaredType != null);
+            Debug.Assert(reflectedType != null);
 
             bool isInherited = declaredType != reflectedType;
 
@@ -63,7 +63,7 @@ namespace System.Reflection
             }
 
             RuntimeMethodHandleInternal associateMethodHandle = ModuleHandle.ResolveMethodHandleInternalCore(RuntimeTypeHandle.GetModule(declaredType), tkMethod, genericArgumentHandles, genericArgumentCount, null, 0);
-            Contract.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token");
+            Debug.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token");
 
             if (isInherited)
             {
@@ -109,7 +109,6 @@ namespace System.Reflection
             return associateMethod;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static unsafe void AssignAssociates(
             MetadataImport scope,
             int mdPropEvent,
index e0625f8..6e4b0cc 100644 (file)
 // 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.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Security.Permissions;
-using System.Security.Policy;
-
 namespace System.Runtime.InteropServices
 {
     [GuidAttribute("BCA8B44D-AAD6-3A86-8AB7-03349F4F2DA2")]
     [CLSCompliant(false)]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [TypeLibImportClassAttribute(typeof(System.Type))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _Type
     {
-#if !FEATURE_CORECLR
-        #region IDispatch Members
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-        #endregion
-
-        #region Object Members
-        String ToString();
-        bool Equals(Object other);
-        int GetHashCode();
-        Type GetType();
-        #endregion
-
-        #region MemberInfo Members
-        MemberTypes MemberType { get; }
-        String Name { get; }
-        Type DeclaringType { get; }
-        Type ReflectedType { get; }
-        Object[] GetCustomAttributes(Type attributeType, bool inherit);
-        Object[] GetCustomAttributes(bool inherit);
-        bool IsDefined(Type attributeType, bool inherit);
-        #endregion
-
-        #region Type Members
-        Guid GUID { get; }           
-        Module Module { get; }            
-        Assembly Assembly { get; }            
-        RuntimeTypeHandle TypeHandle { get; }            
-        String FullName { get; }            
-        String Namespace { get; }            
-        String AssemblyQualifiedName { get; }            
-        int GetArrayRank();        
-        Type BaseType { get; }
-            
-        ConstructorInfo[] GetConstructors(BindingFlags bindingAttr);
-        Type GetInterface(String name, bool ignoreCase);
-        Type[] GetInterfaces();        
-        Type[] FindInterfaces(TypeFilter filter,Object filterCriteria);        
-        EventInfo GetEvent(String name,BindingFlags bindingAttr);        
-        EventInfo[] GetEvents();
-        EventInfo[] GetEvents(BindingFlags bindingAttr);
-        Type[] GetNestedTypes(BindingFlags bindingAttr);
-        Type GetNestedType(String name, BindingFlags bindingAttr);
-        MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr);        
-        MemberInfo[] GetDefaultMembers();               
-        MemberInfo[] FindMembers(MemberTypes memberType,BindingFlags bindingAttr,MemberFilter filter,Object filterCriteria);    
-        Type GetElementType();
-        bool IsSubclassOf(Type c);        
-        bool IsInstanceOfType(Object o);
-        bool IsAssignableFrom(Type c);
-        InterfaceMapping GetInterfaceMap(Type interfaceType);
-        MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers);
-        MethodInfo GetMethod(String name, BindingFlags bindingAttr);            
-        MethodInfo[] GetMethods(BindingFlags bindingAttr);    
-        FieldInfo GetField(String name, BindingFlags bindingAttr);    
-        FieldInfo[] GetFields(BindingFlags bindingAttr);        
-        PropertyInfo GetProperty(String name, BindingFlags bindingAttr);                
-        PropertyInfo GetProperty(String name,BindingFlags bindingAttr,Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers);                
-        PropertyInfo[] GetProperties(BindingFlags bindingAttr);
-        MemberInfo[] GetMember(String name, BindingFlags bindingAttr);
-        MemberInfo[] GetMembers(BindingFlags bindingAttr);        
-        Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters);
-        Type UnderlyingSystemType
-        {
-            get;
-        }       
-    
-        Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args, CultureInfo culture);   
-        Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args);   
-        ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention,  Type[] types, ParameterModifier[] modifiers);   
-        ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers);            
-        ConstructorInfo GetConstructor(Type[] types);
-        ConstructorInfo[] GetConstructors();
-        ConstructorInfo TypeInitializer
-        {
-            get;
-        }
-            
-        MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers);        
-        MethodInfo GetMethod(String name, Type[] types, ParameterModifier[] modifiers);
-        MethodInfo GetMethod(String name, Type[] types);
-        MethodInfo GetMethod(String name);                
-        MethodInfo[] GetMethods();
-        FieldInfo GetField(String name);   
-        FieldInfo[] GetFields();
-        Type GetInterface(String name);
-        EventInfo GetEvent(String name);           
-        PropertyInfo GetProperty(String name, Type returnType, Type[] types,ParameterModifier[] modifiers);                
-        PropertyInfo GetProperty(String name, Type returnType, Type[] types);                
-        PropertyInfo GetProperty(String name, Type[] types);               
-        PropertyInfo GetProperty(String name, Type returnType);
-        PropertyInfo GetProperty(String name);            
-        PropertyInfo[] GetProperties();
-        Type[] GetNestedTypes();
-        Type GetNestedType(String name);
-        MemberInfo[] GetMember(String name);
-        MemberInfo[] GetMembers();
-        TypeAttributes Attributes { get; }            
-        bool IsNotPublic { get; }            
-        bool IsPublic { get; }            
-        bool IsNestedPublic { get; }            
-        bool IsNestedPrivate { get; }            
-        bool IsNestedFamily { get; }            
-        bool IsNestedAssembly { get; }            
-        bool IsNestedFamANDAssem { get; }            
-        bool IsNestedFamORAssem { get; }            
-        bool IsAutoLayout { get; }            
-        bool IsLayoutSequential { get; }            
-        bool IsExplicitLayout { get; }            
-        bool IsClass { get; }            
-        bool IsInterface { get; }            
-        bool IsValueType { get; }            
-        bool IsAbstract { get; }            
-        bool IsSealed { get; }            
-        bool IsEnum { get; }            
-        bool IsSpecialName { get; }            
-        bool IsImport { get; }            
-        bool IsSerializable { get; }            
-        bool IsAnsiClass { get; }            
-        bool IsUnicodeClass { get; }            
-        bool IsAutoClass { get; }            
-        bool IsArray { get; }            
-        bool IsByRef { get; }            
-        bool IsPointer { get; }            
-        bool IsPrimitive { get; }            
-        bool IsCOMObject { get; }            
-        bool HasElementType { get; }            
-        bool IsContextful { get; }          
-        bool IsMarshalByRef { get; }            
-        bool Equals(Type o);
-        #endregion
-#endif
     }
 
     [GuidAttribute("17156360-2f1a-384a-bc52-fde93c215c5b")]
@@ -172,34 +29,8 @@ namespace System.Runtime.InteropServices
     [System.Runtime.InteropServices.ComVisible(true)]
     public interface _MemberInfo
     {
-#if !FEATURE_CORECLR
-        #region IDispatch Members
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-        #endregion
-
-        #region Object Members
-        String ToString();
-        bool Equals(Object other);
-        int GetHashCode();
-        Type GetType();
-        #endregion
-
-        #region MemberInfo Members
-        MemberTypes MemberType { get; }
-        String Name { get; }
-        Type DeclaringType { get; }
-        Type ReflectedType { get; }
-        Object[] GetCustomAttributes(Type attributeType, bool inherit);
-        Object[] GetCustomAttributes(bool inherit);
-        bool IsDefined(Type attributeType, bool inherit);
-        #endregion
-#endif
     }
 
-
     [GuidAttribute("6240837A-707F-3181-8E98-A36AE086766B")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
@@ -207,57 +38,8 @@ namespace System.Runtime.InteropServices
     [System.Runtime.InteropServices.ComVisible(true)]
     public interface _MethodBase
     {
-#if !FEATURE_CORECLR
-        #region IDispatch Members
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-        #endregion
-
-        #region Object Members
-        String ToString();
-        bool Equals(Object other);
-        int GetHashCode();
-        Type GetType();
-        #endregion
-
-        #region MemberInfo Members
-        MemberTypes MemberType { get; }
-        String Name { get; }
-        Type DeclaringType { get; }
-        Type ReflectedType { get; }
-        Object[] GetCustomAttributes(Type attributeType, bool inherit);
-        Object[] GetCustomAttributes(bool inherit);
-        bool IsDefined(Type attributeType, bool inherit);
-        #endregion
-
-        #region MethodBase Members
-        ParameterInfo[] GetParameters();
-        MethodImplAttributes GetMethodImplementationFlags();
-        RuntimeMethodHandle MethodHandle { get; }
-        MethodAttributes Attributes { get; }
-        CallingConventions CallingConvention { get; }
-        Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
-        bool IsPublic { get; }
-        bool IsPrivate { get; }
-        bool IsFamily { get; }
-        bool IsAssembly { get; }
-        bool IsFamilyAndAssembly { get; }
-        bool IsFamilyOrAssembly { get; }
-        bool IsStatic { get; }
-        bool IsFinal { get; }
-        bool IsVirtual { get; }
-        bool IsHideBySig { get; }
-        bool IsAbstract { get; }
-        bool IsSpecialName { get; }      
-        bool IsConstructor { get; }      
-        Object Invoke(Object obj, Object[] parameters);        
-        #endregion
-#endif
     }
 
-
     [GuidAttribute("FFCC1B5D-ECB8-38DD-9B01-3DC8ABC2AA5F")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
@@ -265,62 +47,7 @@ namespace System.Runtime.InteropServices
     [System.Runtime.InteropServices.ComVisible(true)]
     public interface _MethodInfo
     {
-#if !FEATURE_CORECLR
-        #region IDispatch Members
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-        #endregion
-
-        #region Object Members
-        String ToString();
-        bool Equals(Object other);
-        int GetHashCode();
-        Type GetType();
-        #endregion
-
-        #region MemberInfo Members
-        MemberTypes MemberType { get; }
-        String Name { get; }
-        Type DeclaringType { get; }
-        Type ReflectedType { get; }
-        Object[] GetCustomAttributes(Type attributeType, bool inherit);
-        Object[] GetCustomAttributes(bool inherit);
-        bool IsDefined(Type attributeType, bool inherit);
-        #endregion
-
-        #region MethodBase Members
-        ParameterInfo[] GetParameters();
-        MethodImplAttributes GetMethodImplementationFlags();
-        RuntimeMethodHandle MethodHandle { get; }
-        MethodAttributes Attributes { get; }
-        CallingConventions CallingConvention { get; }
-        Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
-        bool IsPublic { get; }
-        bool IsPrivate { get; }
-        bool IsFamily { get; }
-        bool IsAssembly { get; }
-        bool IsFamilyAndAssembly { get; }
-        bool IsFamilyOrAssembly { get; }
-        bool IsStatic { get; }
-        bool IsFinal { get; }
-        bool IsVirtual { get; }
-        bool IsHideBySig { get; }
-        bool IsAbstract { get; }
-        bool IsSpecialName { get; }      
-        bool IsConstructor { get; }      
-        Object Invoke(Object obj, Object[] parameters);        
-        #endregion
-
-        #region MethodInfo Members
-        Type ReturnType { get; }
-        ICustomAttributeProvider ReturnTypeCustomAttributes { get; }
-        MethodInfo GetBaseDefinition();
-        #endregion
-#endif
     }
-        
 
     [GuidAttribute("E9A19478-9646-3679-9B10-8411AE1FD57D")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
@@ -329,174 +56,26 @@ namespace System.Runtime.InteropServices
     [System.Runtime.InteropServices.ComVisible(true)]
     public interface _ConstructorInfo
     {
-#if !FEATURE_CORECLR
-        #region IDispatch Members
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-        #endregion
-
-        #region Object Members
-        String ToString();
-        bool Equals(Object other);
-        int GetHashCode();
-        Type GetType();
-        #endregion
-
-        #region MemberInfo Members
-        MemberTypes MemberType { get; }
-        String Name { get; }
-        Type DeclaringType { get; }
-        Type ReflectedType { get; }
-        Object[] GetCustomAttributes(Type attributeType, bool inherit);
-        Object[] GetCustomAttributes(bool inherit);
-        bool IsDefined(Type attributeType, bool inherit);
-        #endregion
-
-        #region MethodBase Members
-        ParameterInfo[] GetParameters();
-        MethodImplAttributes GetMethodImplementationFlags();
-        RuntimeMethodHandle MethodHandle { get; }
-        MethodAttributes Attributes { get; }
-        CallingConventions CallingConvention { get; }
-        Object Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
-        bool IsPublic { get; }
-        bool IsPrivate { get; }
-        bool IsFamily { get; }
-        bool IsAssembly { get; }
-        bool IsFamilyAndAssembly { get; }
-        bool IsFamilyOrAssembly { get; }
-        bool IsStatic { get; }
-        bool IsFinal { get; }
-        bool IsVirtual { get; }
-        bool IsHideBySig { get; }
-        bool IsAbstract { get; }
-        bool IsSpecialName { get; }      
-        bool IsConstructor { get; }      
-        Object Invoke_3(Object obj, Object[] parameters);        
-        #endregion
-
-        #region ConstructorInfo
-        Object Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
-        Object Invoke_5(Object[] parameters);
-        #endregion
-#endif
     }
 
-
     [GuidAttribute("8A7C1442-A9FB-366B-80D8-4939FFA6DBE0")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.FieldInfo))]
     [System.Runtime.InteropServices.ComVisible(true)]
     public interface _FieldInfo
-    {        
-#if !FEATURE_CORECLR
-        #region IDispatch Members
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-        #endregion
-
-        #region Object Members
-        String ToString();
-        bool Equals(Object other);
-        int GetHashCode();
-        Type GetType();
-        #endregion
-
-        #region MemberInfo Members
-        MemberTypes MemberType { get; }
-        String Name { get; }
-        Type DeclaringType { get; }
-        Type ReflectedType { get; }
-        Object[] GetCustomAttributes(Type attributeType, bool inherit);
-        Object[] GetCustomAttributes(bool inherit);
-        bool IsDefined(Type attributeType, bool inherit);
-        #endregion
-
-        #region FieldInfo Members
-        Type FieldType { get; }
-        Object GetValue(Object obj);        
-        Object GetValueDirect(TypedReference obj);                
-        void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture);        
-        void SetValueDirect(TypedReference obj,Object value);        
-        RuntimeFieldHandle FieldHandle { get; }        
-        FieldAttributes Attributes { get; }           
-        void SetValue(Object obj, Object value);
-        bool IsPublic { get; }
-        bool IsPrivate { get; }
-        bool IsFamily { get; }
-        bool IsAssembly { get; }
-        bool IsFamilyAndAssembly { get; }
-        bool IsFamilyOrAssembly { get; }
-        bool IsStatic { get; }
-        bool IsInitOnly { get; }
-        bool IsLiteral { get; }
-        bool IsNotSerialized { get; }
-        bool IsSpecialName { get; }
-        bool IsPinvokeImpl { get; }
-        #endregion
-#endif
+    {
     }
 
-    
     [GuidAttribute("F59ED4E4-E68F-3218-BD77-061AA82824BF")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.PropertyInfo))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _PropertyInfo
     {
-#if !FEATURE_CORECLR
-        #region IDispatch Members
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-        #endregion
-
-        #region Object Members
-        String ToString();
-        bool Equals(Object other);
-        int GetHashCode();
-        Type GetType();
-        #endregion
-
-        #region MemberInfo Members
-        MemberTypes MemberType { get; }
-        String Name { get; }
-        Type DeclaringType { get; }
-        Type ReflectedType { get; }
-        Object[] GetCustomAttributes(Type attributeType, bool inherit);
-        Object[] GetCustomAttributes(bool inherit);
-        bool IsDefined(Type attributeType, bool inherit);
-        #endregion
-
-        #region Property Members
-        Type PropertyType { get; }
-        Object GetValue(Object obj,Object[] index);
-        Object GetValue(Object obj,BindingFlags invokeAttr,Binder binder, Object[] index, CultureInfo culture);
-        void SetValue(Object obj, Object value, Object[] index);
-        void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
-        MethodInfo[] GetAccessors(bool nonPublic);
-        MethodInfo GetGetMethod(bool nonPublic);
-        MethodInfo GetSetMethod(bool nonPublic);
-        ParameterInfo[] GetIndexParameters();
-        PropertyAttributes Attributes { get; }
-        bool CanRead { get; }
-        bool CanWrite { get; }
-        MethodInfo[] GetAccessors();
-        MethodInfo GetGetMethod();
-        MethodInfo GetSetMethod();
-        bool IsSpecialName { get; }
-        #endregion
-#endif
     }
 
-
     [GuidAttribute("9DE59C64-D889-35A1-B897-587D74469E5B")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
@@ -504,91 +83,33 @@ namespace System.Runtime.InteropServices
     [System.Runtime.InteropServices.ComVisible(true)]
     public interface _EventInfo
     {
-#if !FEATURE_CORECLR
-        #region IDispatch Members
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-        #endregion
-
-        #region Object Members
-        String ToString();
-        bool Equals(Object other);
-        int GetHashCode();
-        Type GetType();
-        #endregion
-
-        #region MemberInfo Members
-        MemberTypes MemberType { get; }
-        String Name { get; }
-        Type DeclaringType { get; }
-        Type ReflectedType { get; }
-        Object[] GetCustomAttributes(Type attributeType, bool inherit);
-        Object[] GetCustomAttributes(bool inherit);
-        bool IsDefined(Type attributeType, bool inherit);
-        #endregion
-
-        #region EventInfo Members
-        MethodInfo GetAddMethod(bool nonPublic);
-        MethodInfo GetRemoveMethod(bool nonPublic);
-        MethodInfo GetRaiseMethod(bool nonPublic);
-        EventAttributes Attributes { get; }        
-        MethodInfo GetAddMethod();
-        MethodInfo GetRemoveMethod();
-        MethodInfo GetRaiseMethod();
-        void AddEventHandler(Object target, Delegate handler);        
-        void RemoveEventHandler(Object target, Delegate handler);        
-        Type EventHandlerType { get; }        
-        bool IsSpecialName { get; }        
-        bool IsMulticast { get; }
-        #endregion
-#endif
     }
 
     [GuidAttribute("993634C4-E47A-32CC-BE08-85F567DC27D6")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.ParameterInfo))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _ParameterInfo
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("D002E9BA-D9E3-3749-B1D3-D565A08B13E7")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Module))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _Module
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("B42B6AAC-317E-34D5-9FA9-093BB4160C50")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.AssemblyName))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _AssemblyName
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 }
 
index 07b29d7..3d927fc 100644 (file)
@@ -14,9 +14,6 @@ namespace System.Reflection
     using System.Runtime;
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.InteropServices;
-#if FEATURE_REMOTING
-    using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
     using System.Runtime.Serialization;
     using System.Security;
     using System.Security.Permissions;
@@ -28,9 +25,6 @@ namespace System.Reflection
     [Serializable]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_ConstructorInfo))]
-#pragma warning disable 618
-    [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
     [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class ConstructorInfo : MethodBase, _ConstructorInfo
     {
@@ -101,57 +95,6 @@ namespace System.Reflection
             return Invoke(BindingFlags.Default, null, parameters, null);
         }
         #endregion
-
-#if !FEATURE_CORECLR
-        #region COM Interop Support
-        Type _ConstructorInfo.GetType()
-        {
-            return base.GetType();
-        }
-        
-        Object _ConstructorInfo.Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
-        {
-            return Invoke(obj, invokeAttr, binder, parameters, culture);
-        }
-        
-        Object _ConstructorInfo.Invoke_3(Object obj, Object[] parameters)
-        {
-            return Invoke(obj, parameters);
-        }
-        
-        Object _ConstructorInfo.Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
-        {
-            return Invoke(invokeAttr, binder, parameters, culture);
-        }
-        
-        Object _ConstructorInfo.Invoke_5(Object[] parameters)
-        {
-            return Invoke(parameters);
-        }
-
-        void _ConstructorInfo.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ConstructorInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ConstructorInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        // If you implement this method, make sure to include _ConstructorInfo.Invoke in VM\DangerousAPIs.h and 
-        // include _ConstructorInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
-        void _ConstructorInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-        #endregion
-#endif
     }
 
     [Serializable]
@@ -205,7 +148,6 @@ namespace System.Reflection
 
         internal INVOCATION_FLAGS InvocationFlags
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
@@ -261,7 +203,6 @@ namespace System.Reflection
         #endregion
 
         #region Constructor
-        [System.Security.SecurityCritical]  // auto-generated
         internal RuntimeConstructorInfo(
             RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache,
             MethodAttributes methodAttributes, BindingFlags bindingFlags)
@@ -276,40 +217,9 @@ namespace System.Reflection
         }
         #endregion
 
-#if FEATURE_REMOTING
-        #region Legacy Remoting Cache
-        // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
-        // This member is currently being used by Remoting for caching remoting data. If you
-        // need to cache data here, talk to the Remoting team to work out a mechanism, so that
-        // both caching systems can happily work together.
-        private RemotingMethodCachedData m_cachedData;
-
-        internal RemotingMethodCachedData RemotingCache
-        {
-            get
-            {
-                // This grabs an internal copy of m_cachedData and uses
-                // that instead of looking at m_cachedData directly because
-                // the cache may get cleared asynchronously.  This prevents
-                // us from having to take a lock.
-                RemotingMethodCachedData cache = m_cachedData;
-                if (cache == null)
-                {
-                    cache = new RemotingMethodCachedData(this);
-                    RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
-                    if (ret != null)
-                        cache = ret;
-                }
-                return cache;
-            }
-        }
-        #endregion
-#endif //FEATURE_REMOTING
-
         #region NonPublic Methods
         RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 return new RuntimeMethodHandleInternal(m_handle);
@@ -408,7 +318,6 @@ namespace System.Reflection
             return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsDefined(Type attributeType, bool inherit)
         {
             if (attributeType == null)
@@ -433,7 +342,6 @@ namespace System.Reflection
         #region MemberInfo Overrides
         public override String Name
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return RuntimeMethodHandle.GetName(this); }
         }
 [System.Runtime.InteropServices.ComVisible(true)]
@@ -457,7 +365,6 @@ namespace System.Reflection
 
         public override int MetadataToken
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return RuntimeMethodHandle.GetMethodDef(this); }
         }
         public override Module Module
@@ -475,7 +382,6 @@ namespace System.Reflection
         // This seems to always returns System.Void.
         internal override Type GetReturnType() { return Signature.ReturnType; } 
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal override ParameterInfo[] GetParametersNoCopy()
         {
             if (m_parameters == null)
@@ -580,7 +486,6 @@ namespace System.Reflection
             throw new TargetException();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
@@ -607,27 +512,11 @@ namespace System.Reflection
 
             if (obj != null)
             {
-
-#if FEATURE_CORECLR
                 // For unverifiable code, we require the caller to be critical.
                 // Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen
                 invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
-#else // FEATURE_CORECLR
-                new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand();
-#endif // FEATURE_CORECLR
-
             }
 
-#if !FEATURE_CORECLR
-            if ((invocationFlags &(INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) 
-            {
-                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
-                    CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
-                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
-                    RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags);
-            }
-#endif // !FEATURE_CORECLR
-
             Signature sig = Signature;
 
             // get the signature
@@ -650,7 +539,6 @@ namespace System.Reflection
         }
         
 
-        [System.Security.SecuritySafeCritical] // overrides SC member
 #pragma warning disable 618
         [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)]
 #pragma warning restore 618
@@ -664,29 +552,17 @@ namespace System.Reflection
 
         public override bool IsSecurityCritical
         {
-#if FEATURE_CORECLR
             get { return true; }
-#else
-            get { return RuntimeMethodHandle.IsSecurityCritical(this); }
-#endif
         }
 
         public override bool IsSecuritySafeCritical
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
-#endif
         }
 
         public override bool IsSecurityTransparent
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
-#endif
         }
 
         public override bool ContainsGenericParameters
@@ -699,7 +575,6 @@ namespace System.Reflection
         #endregion
 
         #region ConstructorInfo Overrides
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
@@ -723,18 +598,6 @@ namespace System.Reflection
             }
 #endif
 
-#if !FEATURE_CORECLR
-            if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0) 
-            {
-                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) 
-                    CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
-                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)  != 0) 
-                    RuntimeMethodHandle.PerformSecurityCheck(null, this, m_declaringType, (uint)(m_invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE));
-                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0)
-                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-            }
-#endif // !FEATURE_CORECLR
-
             // get the signature
             Signature sig = Signature;
 
@@ -761,7 +624,6 @@ namespace System.Reflection
         #endregion
     
         #region ISerializable Implementation
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
@@ -789,5 +651,4 @@ namespace System.Reflection
         }
        #endregion
     }
-
 }
index 92d230c..e568a17 100644 (file)
@@ -63,10 +63,9 @@ namespace System.Reflection
         #endregion
 
         #region Internal Static Members
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeType target)
         {
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
 
             IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
 
@@ -86,10 +85,9 @@ namespace System.Reflection
             return Array.AsReadOnly(pca);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeFieldInfo target)
         {
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
 
             IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
 
@@ -109,10 +107,9 @@ namespace System.Reflection
             return Array.AsReadOnly(pca);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeMethodInfo target)
         {
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
 
             IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
 
@@ -132,34 +129,30 @@ namespace System.Reflection
             return Array.AsReadOnly(pca);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeConstructorInfo target)
         {
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
 
             return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeEventInfo target)
         {
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
 
             return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimePropertyInfo target)
         {
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
 
             return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeModule target)
         {
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
 
             if (target.IsResource())
                 return new List<CustomAttributeData>();
@@ -167,10 +160,9 @@ namespace System.Reflection
             return GetCustomAttributes(target, target.MetadataToken);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeAssembly target)
         {
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
 
             IList<CustomAttributeData> cad = GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle()));
 
@@ -190,10 +182,9 @@ namespace System.Reflection
             return Array.AsReadOnly(pca);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeParameterInfo target)
         {
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
 
             IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
 
@@ -302,7 +293,6 @@ namespace System.Reflection
 
             return new CustomAttributeType(encodedType, encodedArrayType, encodedEnumType, enumName);
         }
-        [System.Security.SecurityCritical]  // auto-generated
         private static IList<CustomAttributeData> GetCustomAttributes(RuntimeModule module, int tkTarget)
         {
             CustomAttributeRecord[] records = GetCustomAttributeRecords(module, tkTarget);
@@ -316,7 +306,6 @@ namespace System.Reflection
         #endregion 
 
         #region Internal Static Members
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static CustomAttributeRecord[] GetCustomAttributeRecords(RuntimeModule module, int targetToken)
         {
             MetadataImport scope = module.MetadataImport;
@@ -369,7 +358,6 @@ namespace System.Reflection
         {
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private CustomAttributeData(RuntimeModule scope, CustomAttributeRecord caRecord)
         {
             m_scope = scope;
@@ -753,7 +741,6 @@ namespace System.Reflection
             }
         }
 
-        [SecuritySafeCritical]
         private static object EncodedValueToRawValue(long val, CustomAttributeEncoding encodedType)
         {
             switch (encodedType)
@@ -838,7 +825,7 @@ namespace System.Reflection
 
         private static object CanonicalizeValue(object value)
         {
-            Contract.Assert(value != null);
+            Debug.Assert(value != null);
 
             if (value.GetType().IsEnum)
             {
@@ -1015,7 +1002,6 @@ namespace System.Reflection
     internal struct CustomAttributeEncodedArgument
     { 
         #region Parser
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void ParseAttributeArguments(
             IntPtr pCa, 
@@ -1024,7 +1010,6 @@ namespace System.Reflection
             ref CustomAttributeNamedParameter[] CustomAttributeTypedArgument,
             RuntimeAssembly assembly);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void ParseAttributeArguments(ConstArray attributeBlob, 
             ref CustomAttributeCtorParameter[] customAttributeCtorParameters,
             ref CustomAttributeNamedParameter[] customAttributeNamedParameters,
@@ -1034,8 +1019,8 @@ namespace System.Reflection
                 throw new ArgumentNullException(nameof(customAttributeModule));
             Contract.EndContractBlock();
 
-            Contract.Assert(customAttributeCtorParameters != null);
-            Contract.Assert(customAttributeNamedParameters != null);
+            Debug.Assert(customAttributeCtorParameters != null);
+            Debug.Assert(customAttributeNamedParameters != null);
 
             if (customAttributeCtorParameters.Length != 0 || customAttributeNamedParameters.Length != 0)
             {
@@ -1131,11 +1116,9 @@ namespace System.Reflection
         IntPtr m_Next;
         IntPtr m_Assembly;
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern void Push(RuntimeAssembly assembly);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public extern void Pop();
@@ -1183,7 +1166,6 @@ namespace System.Reflection
         #endregion
 
         #region Internal Static Members
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeType type, RuntimeType caType, bool inherit)
         {
             Contract.Requires(type != null);
@@ -1213,7 +1195,6 @@ namespace System.Reflection
             return false;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType, bool inherit)
         {
             Contract.Requires(method != null);
@@ -1241,7 +1222,6 @@ namespace System.Reflection
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType)
         {
             Contract.Requires(ctor != null);
@@ -1253,7 +1233,6 @@ namespace System.Reflection
             return IsCustomAttributeDefined(ctor.GetRuntimeModule(), ctor.MetadataToken, caType);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimePropertyInfo property, RuntimeType caType)
         {
             Contract.Requires(property != null);
@@ -1265,7 +1244,6 @@ namespace System.Reflection
             return IsCustomAttributeDefined(property.GetRuntimeModule(), property.MetadataToken, caType);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeEventInfo e, RuntimeType caType)
         {
             Contract.Requires(e != null);
@@ -1277,7 +1255,6 @@ namespace System.Reflection
             return IsCustomAttributeDefined(e.GetRuntimeModule(), e.MetadataToken, caType);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType)
         {
             Contract.Requires(field != null);
@@ -1289,7 +1266,6 @@ namespace System.Reflection
             return IsCustomAttributeDefined(field.GetRuntimeModule(), field.MetadataToken, caType);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType)
         {
             Contract.Requires(parameter != null);
@@ -1301,7 +1277,6 @@ namespace System.Reflection
             return IsCustomAttributeDefined(parameter.GetRuntimeModule(), parameter.MetadataToken, caType);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType) 
         {
             Contract.Requires(assembly != null);
@@ -1313,7 +1288,6 @@ namespace System.Reflection
             return IsCustomAttributeDefined(assembly.ManifestModule as RuntimeModule, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeModule module, RuntimeType caType)
         {
             Contract.Requires(module != null);
@@ -1325,7 +1299,6 @@ namespace System.Reflection
             return IsCustomAttributeDefined(module, module.MetadataToken, caType);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Object[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool inherit)
         {
             Contract.Requires(type != null);
@@ -1388,7 +1361,7 @@ namespace System.Reflection
                 else
                 {
                     type = type.DeclaringType as RuntimeType;
-                    Contract.Assert(type != null);
+                    Debug.Assert(type != null);
                 }
             }
 
@@ -1397,16 +1370,7 @@ namespace System.Reflection
 
         private static bool SpecialAllowCriticalAttributes(RuntimeType type)
         {
-            // Types participating in Type Equivalence are always transparent.
-            // See TokenSecurityDescriptor::VerifySemanticDataComputed in securitymeta.cpp.
-            // Because of that we allow critical attributes applied to full trust equivalent types.
-            // DeclaringType is null for global methods and fields and the global type never participates in type equivalency.
-
-#if FEATURE_CORECLR
             return false;
-#else
-            return type != null && type.Assembly.IsFullyTrusted && RuntimeTypeHandle.IsEquivalentType(type);
-#endif //!FEATURE_CORECLR
         }
 
         private static bool AllowCriticalCustomAttributes(MethodBase method)
@@ -1429,7 +1393,6 @@ namespace System.Reflection
             return AllowCriticalCustomAttributes(parameter.DefiningMethod);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Object[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool inherit)
         {
             Contract.Requires(method != null);
@@ -1474,7 +1437,6 @@ namespace System.Reflection
             return typedResult;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Object[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType)
         {
             Contract.Requires(ctor != null);
@@ -1487,7 +1449,6 @@ namespace System.Reflection
             return attributes;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Object[] GetCustomAttributes(RuntimePropertyInfo property, RuntimeType caType)
         {
             Contract.Requires(property != null);
@@ -1506,7 +1467,6 @@ namespace System.Reflection
             return attributes;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Object[] GetCustomAttributes(RuntimeEventInfo e, RuntimeType caType)
         {
             Contract.Requires(e != null);
@@ -1524,7 +1484,6 @@ namespace System.Reflection
             return attributes;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Object[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType)
         {
             Contract.Requires(field != null);
@@ -1537,7 +1496,6 @@ namespace System.Reflection
             return attributes;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Object[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType)
         {
             Contract.Requires(parameter != null);
@@ -1550,7 +1508,6 @@ namespace System.Reflection
             return attributes;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) 
         {
             Contract.Requires(assembly != null);
@@ -1565,7 +1522,6 @@ namespace System.Reflection
             return attributes;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType) 
         {
             Contract.Requires(module != null);
@@ -1579,20 +1535,17 @@ namespace System.Reflection
             return attributes;
         }
 
-        [System.Security.SecuritySafeCritical]
         internal static bool IsAttributeDefined(RuntimeModule decoratedModule, int decoratedMetadataToken, int attributeCtorToken)
         {
             return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, null, attributeCtorToken, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static bool IsCustomAttributeDefined(
             RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType)
         {
             return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, attributeFilterType, 0, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static bool IsCustomAttributeDefined(
             RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType, int attributeCtorToken, bool mustBeInheritable)
         {
@@ -1604,7 +1557,7 @@ namespace System.Reflection
 
             if (attributeFilterType != null)
             {
-                Contract.Assert(attributeCtorToken == 0);
+                Debug.Assert(attributeCtorToken == 0);
 
                 MetadataImport scope = decoratedModule.MetadataImport;
                 RuntimeType attributeType;
@@ -1627,8 +1580,8 @@ namespace System.Reflection
             }
             else
             {
-                Contract.Assert(attributeFilterType == null);
-                Contract.Assert(!MetadataToken.IsNullToken(attributeCtorToken));
+                Debug.Assert(attributeFilterType == null);
+                Debug.Assert(!MetadataToken.IsNullToken(attributeCtorToken));
 
                 for (int i = 0; i < car.Length; i++)
                 {
@@ -1642,14 +1595,12 @@ namespace System.Reflection
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe static object[] GetCustomAttributes(
             RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType, bool isDecoratedTargetSecurityTransparent)
         {
             return GetCustomAttributes(decoratedModule, decoratedMetadataToken, pcaCount, attributeFilterType, false, null, isDecoratedTargetSecurityTransparent);
         }
 
-        [System.Security.SecurityCritical]
         private unsafe static object[] GetCustomAttributes(
             RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, 
             RuntimeType attributeFilterType, bool mustBeInheritable, IList derivedAttributes, bool isDecoratedTargetSecurityTransparent)
@@ -1841,7 +1792,6 @@ namespace System.Reflection
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe static bool FilterCustomAttributeRecord(
             CustomAttributeRecord caRecord,
             MetadataImport scope,
@@ -1931,7 +1881,7 @@ namespace System.Reflection
             else
             {
                 // We need to relax this when we add support for other types of decorated tokens.
-                Contract.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly, 
+                Debug.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly, 
                                 "The decoratedToken must be either an assembly, a module, a type, or a member.");
             }
 
@@ -1946,7 +1896,6 @@ namespace System.Reflection
         #endregion
 
         #region Private Static Methods
-        [System.Security.SecurityCritical]  // auto-generated
         private static bool AttributeUsageCheck(
             RuntimeType attributeType, bool mustBeInheritable, object[] attributes, IList derivedAttributes)
         {
@@ -1979,7 +1928,6 @@ namespace System.Reflection
             return true;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static AttributeUsageAttribute GetAttributeUsage(RuntimeType decoratedAttribute)
         {
             RuntimeModule decoratedModule = decoratedAttribute.GetRuntimeModule();
@@ -2014,11 +1962,9 @@ namespace System.Reflection
         #endregion
 
         #region Private Static FCalls
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _ParseAttributeUsageAttribute(
             IntPtr pCa, int cCa, out int targets, out bool inherited, out bool allowMultiple);
-        [System.Security.SecurityCritical]  // auto-generated
         private static void ParseAttributeUsageAttribute(
             ConstArray ca, out AttributeTargets targets, out bool inherited, out bool allowMultiple)
         {
@@ -2027,10 +1973,8 @@ namespace System.Reflection
             targets = (AttributeTargets)_targets;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static unsafe extern Object _CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, byte** ppBlob, byte* pEndBlob, int* pcNamedArgs);
-        [System.Security.SecurityCritical]  // auto-generated
         private static unsafe Object CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, ref IntPtr blob, IntPtr blobEnd, out int namedArgs)
         {
             byte* pBlob = (byte*)blob;
@@ -2042,11 +1986,9 @@ namespace System.Reflection
             return ca;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private unsafe extern static void _GetPropertyOrFieldData(
             RuntimeModule pModule, byte** ppBlobStart, byte* pBlobEnd, out string name, out bool bIsProperty, out RuntimeType type, out object value);
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe static void GetPropertyOrFieldData(
             RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType type, out object value)
         {
@@ -2056,7 +1998,6 @@ namespace System.Reflection
             blobStart = (IntPtr)pBlobStart;
         }
 
-        [System.Security.SecuritySafeCritical]
         private static object[] CreateAttributeArrayHelper(Type elementType, int elementCount)
         {
             return (object[])Array.UnsafeCreateInstance(elementType, elementCount);
@@ -2076,25 +2017,13 @@ namespace System.Reflection
         #endregion
 
         #region FCalls
-#if FEATURE_CAS_POLICY
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        unsafe private static extern void _GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes);
-        [System.Security.SecurityCritical]  // auto-generated
-        unsafe internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes)
-        {
-            _GetSecurityAttributes(module.GetNativeHandle(), token, assembly, out securityAttributes);
-        }
-#else
         internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes)
         {
             securityAttributes = null;
         }
-#endif
         #endregion
 
         #region Static Constructor
-        [System.Security.SecurityCritical]  // auto-generated
         static PseudoCustomAttribute()
         {
             RuntimeType[] pcas = new RuntimeType[]
@@ -2124,17 +2053,16 @@ namespace System.Reflection
             s_pca = temp_pca;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [Conditional("_DEBUG")]
         private static void VerifyPseudoCustomAttribute(RuntimeType pca)
         {
             // If any of these are invariants are no longer true will have to 
             // re-architect the PCA product logic and test cases -- you've been warned!
-            Contract.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error");
+            Debug.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error");
             AttributeUsageAttribute usage = CustomAttribute.GetAttributeUsage(pca);
-            Contract.Assert(usage.Inherited == false, "Pseudo CA Error");
+            Debug.Assert(usage.Inherited == false, "Pseudo CA Error");
             //AllowMultiple is true for TypeForwardedToAttribute
-            //Contract.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
+            //Debug.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
         }
 #endregion
 
@@ -2146,7 +2074,6 @@ namespace System.Reflection
 #pragma warning restore 618
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool includeSecCa, out int count)
         {
             Contract.Requires(type != null);
@@ -2190,7 +2117,6 @@ namespace System.Reflection
             count = pcas.Count;
             return pcas.ToArray();
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeType type, RuntimeType caType)
         {
             bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
@@ -2215,7 +2141,6 @@ namespace System.Reflection
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool includeSecCa, out int count)
         {
             Contract.Requires(method != null);
@@ -2254,7 +2179,6 @@ namespace System.Reflection
             count = pcas.Count;
             return pcas.ToArray();
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType)
         {
             bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
@@ -2280,7 +2204,6 @@ namespace System.Reflection
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType, out int count)
         {
             Contract.Requires(parameter != null);
@@ -2317,7 +2240,6 @@ namespace System.Reflection
             }
             return pcas;
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType)
         {
             bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
@@ -2345,7 +2267,6 @@ namespace System.Reflection
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType, bool includeSecCa, out int count)
         {
             count = 0;
@@ -2380,7 +2301,6 @@ namespace System.Reflection
             count = pcas.Count;
             return pcas.ToArray();
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType)
         {
             int count;
@@ -2397,7 +2317,6 @@ namespace System.Reflection
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType, out int count)
         {
             Contract.Requires(field != null);
@@ -2429,7 +2348,6 @@ namespace System.Reflection
             }
             return pcas;
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType)
         {
             bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
@@ -2452,7 +2370,6 @@ namespace System.Reflection
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType, bool includeSecCa, out int count)
         {
             count = 0;
@@ -2478,7 +2395,6 @@ namespace System.Reflection
             count = pcas.Count;
             return pcas.ToArray();
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType)
         {
             bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
index 6484677..fb93249 100644 (file)
@@ -22,59 +22,45 @@ namespace System.Reflection.Emit
         }
         
         #region QCalls
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern IntPtr CreateTypeNameBuilder();
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void ReleaseTypeNameBuilder(IntPtr pAQN);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void OpenGenericArguments(IntPtr tnb);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void CloseGenericArguments(IntPtr tnb);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void OpenGenericArgument(IntPtr tnb);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void CloseGenericArgument(IntPtr tnb);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void AddName(IntPtr tnb, string name);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void AddPointer(IntPtr tnb);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void AddByRef(IntPtr tnb);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void AddSzArray(IntPtr tnb);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void AddArray(IntPtr tnb, int rank);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void AddAssemblySpec(IntPtr tnb, string assemblySpec);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void ToString(IntPtr tnb, StringHandleOnStack retString);
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void Clear(IntPtr tnb);
@@ -83,7 +69,6 @@ namespace System.Reflection.Emit
         #region Static Members
 
         // TypeNameBuilder is NOT thread safe NOR reliable
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static string ToString(Type type, Format format)
         {
             if (format == Format.FullName || format == Format.AssemblyQualifiedName)
@@ -107,12 +92,10 @@ namespace System.Reflection.Emit
 
         #region Constructor
         private TypeNameBuilder(IntPtr typeNameBuilder) { m_typeNameBuilder = typeNameBuilder; }
-        [System.Security.SecurityCritical]  // auto-generated
         internal void Dispose() { ReleaseTypeNameBuilder(m_typeNameBuilder); }
         #endregion
 
         #region private Members
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddElementType(Type elementType)
         {
             if (elementType.HasElementType)
@@ -131,7 +114,6 @@ namespace System.Reflection.Emit
                 AddArray(elementType.GetArrayRank());
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         private void ConstructAssemblyQualifiedNameWorker(Type type, Format format)
         {
             Type rootType = type;
@@ -179,29 +161,17 @@ namespace System.Reflection.Emit
                 AddAssemblySpec(type.Module.Assembly.FullName);
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         private void OpenGenericArguments() { OpenGenericArguments(m_typeNameBuilder); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void CloseGenericArguments() { CloseGenericArguments(m_typeNameBuilder); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void OpenGenericArgument() { OpenGenericArgument(m_typeNameBuilder); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void CloseGenericArgument() { CloseGenericArgument(m_typeNameBuilder); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddName(string name) { AddName(m_typeNameBuilder, name); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddPointer() { AddPointer(m_typeNameBuilder); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddByRef() { AddByRef(m_typeNameBuilder); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddSzArray() { AddSzArray(m_typeNameBuilder); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddArray(int rank) { AddArray(m_typeNameBuilder, rank); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddAssemblySpec(string assemblySpec) { AddAssemblySpec(m_typeNameBuilder, assemblySpec); }
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override string ToString() { string ret = null; ToString(m_typeNameBuilder, JitHelpers.GetStringHandleOnStack(ref ret)); return ret; }
-        [System.Security.SecurityCritical]  // auto-generated
         private void Clear() { Clear(m_typeNameBuilder); }
         #endregion
     }
index 3e13c01..9331ae1 100644 (file)
@@ -98,17 +98,11 @@ namespace System.Reflection.Emit
             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public override FileStream GetFile(String name)
         {
             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public override FileStream[] GetFiles(bool getResourceModules)
         {
             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
@@ -131,9 +125,6 @@ namespace System.Reflection.Emit
 
         public override String Location
         {
-#if FEATURE_CORECLR
-            [SecurityCritical]
-#endif // FEATURE_CORECLR
             get
             {
                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
@@ -142,9 +133,6 @@ namespace System.Reflection.Emit
 
         public override String CodeBase
         {
-#if FEATURE_CORECLR
-            [SecurityCritical]
-#endif // FEATURE_CORECLR
             get
             {
                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
@@ -168,43 +156,20 @@ namespace System.Reflection.Emit
 
     // AssemblyBuilder class.
     // deliberately not [serializable]
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_AssemblyBuilder))]
     [ComVisible(true)]
     public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder
     {
         #region FCALL
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private Module nGetInMemoryAssemblyModule()
         {
             return AssemblyBuilder.GetInMemoryAssemblyModule(GetNativeHandle());
         }
 
-#if !FEATURE_CORECLR
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern RuntimeModule GetOnDiskAssemblyModule(RuntimeAssembly assembly);
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private ModuleBuilder GetOnDiskAssemblyModuleBuilder()
-        {
-            if (m_onDiskAssemblyModuleBuilder == null)
-            {
-                Module module = AssemblyBuilder.GetOnDiskAssemblyModule(InternalAssembly.GetNativeHandle());
-                ModuleBuilder modBuilder = new ModuleBuilder(this, (InternalModuleBuilder)module);
-                modBuilder.Init("RefEmit_OnDiskManifestModule", null, 0);
-                m_onDiskAssemblyModuleBuilder = modBuilder;
-            }
-
-            return m_onDiskAssemblyModuleBuilder;
-        }
-#endif // FEATURE_CORECLR
-
         #endregion
 
         #region Internal Data Members
@@ -215,9 +180,6 @@ namespace System.Reflection.Emit
         // Set to true if the manifest module was returned by code:DefineDynamicModule to the user
         private bool m_fManifestModuleUsedAsDefinedModule;
         internal const string MANIFEST_MODULE_NAME = "RefEmit_InMemoryManifestModule";
-#if !FEATURE_CORECLR
-        private ModuleBuilder m_onDiskAssemblyModuleBuilder;
-#endif // !FEATURE_CORECLR
 
 #if FEATURE_APPX
         private bool m_profileAPICheck;
@@ -226,22 +188,10 @@ namespace System.Reflection.Emit
         internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module)
         {
             Contract.Requires(module != null);
-            Contract.Assert(this.InternalAssembly == module.Assembly);
+            Debug.Assert(this.InternalAssembly == module.Assembly);
 
             lock(SyncRoot)
             {
-#if !FEATURE_CORECLR
-                foreach (ModuleBuilder modBuilder in m_assemblyData.m_moduleBuilderList)
-                {
-                    if (modBuilder.InternalModule == module)
-                        return modBuilder;
-                }
-
-                // m_onDiskAssemblyModuleBuilder is null before Save
-                if (m_onDiskAssemblyModuleBuilder != null && m_onDiskAssemblyModuleBuilder.InternalModule == module)
-                    return m_onDiskAssemblyModuleBuilder;
-#endif // !FEATURE_CORECLR
-
                 // in CoreCLR there is only one module in each dynamic assembly, the manifest module
                 if (m_manifestModuleBuilder.InternalModule == module)
                     return m_manifestModuleBuilder;
@@ -271,7 +221,6 @@ namespace System.Reflection.Emit
             return InternalAssembly.GetNativeHandle();
         }
 
-        [SecurityCritical]
         internal Version GetVersion()
         {
             return InternalAssembly.GetVersion();
@@ -289,7 +238,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Constructor
-        [System.Security.SecurityCritical]  // auto-generated
         internal AssemblyBuilder(AppDomain domain,
                                  AssemblyName name,
                                  AssemblyBuilderAccess access,
@@ -306,10 +254,6 @@ namespace System.Reflection.Emit
                 throw new ArgumentNullException(nameof(name));
 
             if (access != AssemblyBuilderAccess.Run
-#if !FEATURE_CORECLR
-                && access != AssemblyBuilderAccess.Save
-                && access != AssemblyBuilderAccess.RunAndSave
-#endif // !FEATURE_CORECLR
 #if FEATURE_REFLECTION_ONLY_LOAD
                 && access != AssemblyBuilderAccess.ReflectionOnly
 #endif // FEATURE_REFLECTION_ONLY_LOAD
@@ -329,14 +273,6 @@ namespace System.Reflection.Emit
 
             // Clone the name in case the caller modifies it underneath us.
             name = (AssemblyName)name.Clone();
-            
-#if !FEATURE_CORECLR
-            // Set the public key from the key pair if one has been provided.
-            // (Overwite any public key in the Assembly name, since it's no
-            // longer valid to have a disparity).
-            if (name.KeyPair != null)
-                name.SetPublicKey(name.KeyPair.PublicKey);
-#endif
 
             // If the caller is trusted they can supply identity
             // evidence for the new assembly. Otherwise we copy the
@@ -350,13 +286,6 @@ namespace System.Reflection.Emit
                 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
 #pragma warning restore 618
 
-#if FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR
-            // Collectible assemblies require FullTrust. This demand may be removed if we deem the
-            // feature robust enough to be used directly by untrusted API consumers.
-            if (access == AssemblyBuilderAccess.RunAndCollect)
-                new PermissionSet(PermissionState.Unrestricted).Demand();
-#endif // FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR
-
             // Scan the assembly level attributes for any attributes which modify how we create the
             // assembly. Currently, we look for any attribute which modifies the security transparency
             // of the assembly.
@@ -427,7 +356,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void InitManifestModule()
         {
             InternalModuleBuilder modBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule();
@@ -456,7 +384,6 @@ namespace System.Reflection.Emit
         * to have a strong name and a hash will be computed when the assembly
         * is saved.
         **********************************************/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static AssemblyBuilder DefineDynamicAssembly(
             AssemblyName name,
@@ -469,7 +396,6 @@ namespace System.Reflection.Emit
                                                  null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static AssemblyBuilder DefineDynamicAssembly(
             AssemblyName name,
@@ -487,7 +413,6 @@ namespace System.Reflection.Emit
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern Assembly nCreateDynamicAssembly(AppDomain domain,
                                                               AssemblyName name,
@@ -504,7 +429,6 @@ namespace System.Reflection.Emit
 
         private class AssemblyBuilderLock { }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static AssemblyBuilder InternalDefineDynamicAssembly(
             AssemblyName name,
             AssemblyBuilderAccess access,
@@ -517,13 +441,6 @@ namespace System.Reflection.Emit
             IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes,
             SecurityContextSource securityContextSource)
         {
-#if FEATURE_CAS_POLICY
-            if (evidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
-            {
-                throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
-            }
-#endif // FEATURE_CAS_POLICY
-
             lock (typeof(AssemblyBuilderLock))
             {
                 // we can only create dynamic assemblies in the current domain
@@ -550,7 +467,6 @@ namespace System.Reflection.Emit
         * a transient module.
         * 
         **********************************************/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public ModuleBuilder DefineDynamicModule(
             String      name)
@@ -561,7 +477,6 @@ namespace System.Reflection.Emit
             return DefineDynamicModuleInternal(name, false, ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public ModuleBuilder DefineDynamicModule(
             String      name,
@@ -573,7 +488,6 @@ namespace System.Reflection.Emit
             return DefineDynamicModuleInternal( name, emitSymbolInfo, ref stackMark );
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private ModuleBuilder DefineDynamicModuleInternal(
             String      name,
             bool        emitSymbolInfo,         // specify if emit symbol info or not
@@ -585,7 +499,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private ModuleBuilder DefineDynamicModuleInternalNoLock(
             String      name,
             bool        emitSymbolInfo,         // specify if emit symbol info or not
@@ -602,7 +515,7 @@ namespace System.Reflection.Emit
 
             BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )");
 
-            Contract.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal");
+            Debug.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal");
 
             ModuleBuilder dynModule;
             ISymbolWriter writer = null;
@@ -694,163 +607,6 @@ namespace System.Reflection.Emit
             }
         }
 
-#if !FEATURE_CORECLR
-        /**********************************************
-        *
-        * Define stand alone managed resource for Assembly
-        *
-        **********************************************/
-        public IResourceWriter DefineResource(
-            String      name,
-            String      description,
-            String      fileName)
-        {
-            return DefineResource(name, description, fileName, ResourceAttributes.Public);
-        }
-
-        /**********************************************
-        *
-        * Define stand alone managed resource for Assembly
-        *
-        **********************************************/
-        public IResourceWriter DefineResource(
-            String      name,
-            String      description,
-            String      fileName,
-            ResourceAttributes attribute)
-        {
-            lock(SyncRoot)
-            {
-                return DefineResourceNoLock(name, description, fileName, attribute);
-            }
-        }
-
-        private IResourceWriter DefineResourceNoLock(
-            String      name,
-            String      description,
-            String      fileName,
-            ResourceAttributes attribute)
-        {
-            if (name == null)
-                throw new ArgumentNullException(nameof(name));
-            if (name.Length == 0)
-                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
-            if (fileName == null)
-                throw new ArgumentNullException(nameof(fileName));
-            if (fileName.Length == 0)
-                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(fileName));
-            if (!String.Equals(fileName, Path.GetFileName(fileName)))
-                throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), nameof(fileName));
-            Contract.EndContractBlock();
-
-            BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineResource( " + name + ", " + fileName + ")");
-
-            m_assemblyData.CheckResNameConflict(name);
-            m_assemblyData.CheckFileNameConflict(fileName);
-
-            ResourceWriter resWriter;
-            String  fullFileName;
-
-            if (m_assemblyData.m_strDir == null)
-            {
-                // If assembly directory is null, use current directory
-                fullFileName = Path.Combine(Directory.GetCurrentDirectory(), fileName);
-                resWriter = new ResourceWriter(fullFileName);
-            }
-            else
-            {
-                // Form the full path given the directory provided by user
-                fullFileName = Path.Combine(m_assemblyData.m_strDir, fileName);
-                resWriter = new ResourceWriter(fullFileName);
-            }
-            // get the full path
-            fullFileName = Path.GetFullPath(fullFileName);
-            
-            // retrieve just the file name
-            fileName = Path.GetFileName(fullFileName);
-            
-            m_assemblyData.AddResWriter( new ResWriterData( resWriter, null, name, fileName, fullFileName, attribute) );
-            return resWriter;
-        }
-
-        /**********************************************
-        *
-        * Add an existing resource file to the Assembly
-        *
-        **********************************************/
-        public void AddResourceFile(
-            String      name,
-            String      fileName)
-        {
-            AddResourceFile(name, fileName, ResourceAttributes.Public);
-        }
-
-        /**********************************************
-        *
-        * Add an existing resource file to the Assembly
-        *
-        **********************************************/
-        public void AddResourceFile(
-            String      name,
-            String      fileName,
-            ResourceAttributes attribute)
-        {
-            lock(SyncRoot)
-            {
-                AddResourceFileNoLock(name, fileName, attribute);
-            }
-        }
-
-        [System.Security.SecuritySafeCritical]
-        private void AddResourceFileNoLock(
-            String      name,
-            String      fileName,
-            ResourceAttributes attribute)
-        {
-            if (name == null)
-                throw new ArgumentNullException(nameof(name));
-            if (name.Length == 0)
-                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
-            if (fileName == null)
-                throw new ArgumentNullException(nameof(fileName));
-            if (fileName.Length == 0)
-                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), fileName);
-            if (!String.Equals(fileName, Path.GetFileName(fileName)))
-                throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), nameof(fileName));
-            Contract.EndContractBlock();
-
-            BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.AddResourceFile( " + name + ", " + fileName + ")");
-
-            m_assemblyData.CheckResNameConflict(name);
-            m_assemblyData.CheckFileNameConflict(fileName);
-
-            String  fullFileName;
-
-            if (m_assemblyData.m_strDir == null)
-            {
-                // If assembly directory is null, use current directory
-                fullFileName = Path.Combine(Directory.GetCurrentDirectory(), fileName);
-            }
-            else
-            {
-                // Form the full path given the directory provided by user
-                fullFileName = Path.Combine(m_assemblyData.m_strDir, fileName);
-            }
-            
-            // get the full path
-            fullFileName = Path.UnsafeGetFullPath(fullFileName);
-            
-            // retrieve just the file name
-            fileName = Path.GetFileName(fullFileName);
-            
-            if (File.UnsafeExists(fullFileName) == false)
-                throw new FileNotFoundException(Environment.GetResourceString(
-                    "IO.FileNotFound_FileName",
-                    fileName), fileName);
-            m_assemblyData.AddResWriter( new ResWriterData( null, null, name, fileName, fullFileName, attribute) );
-        }
-#endif // !FEATURE_CORECLR
-
         #region object overrides
         public override bool Equals(object obj)
         {
@@ -889,17 +645,11 @@ namespace System.Reflection.Emit
             return InternalAssembly.GetManifestResourceNames();
         }
         
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public override FileStream GetFile(String name)
         {
             return InternalAssembly.GetFile(name);
         }
         
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public override FileStream[] GetFiles(bool getResourceModules)
         {
             return InternalAssembly.GetFiles(getResourceModules);
@@ -922,9 +672,6 @@ namespace System.Reflection.Emit
 
         public override String Location
         {
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             get
             {
                 return InternalAssembly.Location;
@@ -941,9 +688,6 @@ namespace System.Reflection.Emit
         
         public override String CodeBase
         {
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             get
             {
                 return InternalAssembly.CodeBase;
@@ -966,9 +710,6 @@ namespace System.Reflection.Emit
             return InternalAssembly.GetExportedTypes();
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public override AssemblyName GetName(bool copiedName)
         {
             return InternalAssembly.GetName(copiedName);
@@ -987,33 +728,6 @@ namespace System.Reflection.Emit
             return InternalAssembly.GetType(name, throwOnError, ignoreCase);
         }
 
-#if FEATURE_CAS_POLICY
-        public override Evidence Evidence
-        {
-            get
-            {
-                return InternalAssembly.Evidence;
-            }
-        }
-
-        public override PermissionSet PermissionSet
-        {
-            [SecurityCritical]
-            get
-            {
-                return InternalAssembly.PermissionSet;
-            }
-        }
-
-        public override SecurityRuleSet SecurityRuleSet
-        {
-            get
-            {
-                return InternalAssembly.SecurityRuleSet;
-            }
-        }
-#endif // FEATURE_CAS_POLICY
-
         public override Module ManifestModule
         {
             get
@@ -1090,142 +804,6 @@ namespace System.Reflection.Emit
         #endregion
 
 
-#if !FEATURE_CORECLR
-        /**********************************************
-        *
-        * Add an unmanaged Version resource to the
-        *  assembly
-        *
-        **********************************************/
-        public void DefineVersionInfoResource(
-            String      product, 
-            String      productVersion, 
-            String      company, 
-            String      copyright, 
-            String      trademark)
-        {
-            lock(SyncRoot)
-            {
-                DefineVersionInfoResourceNoLock(
-                    product,
-                    productVersion,
-                    company,
-                    copyright,
-                    trademark);
-            }
-        }
-
-        private void DefineVersionInfoResourceNoLock(
-            String product,
-            String productVersion,
-            String company,
-            String copyright,
-            String trademark)
-        {
-            if (m_assemblyData.m_strResourceFileName != null ||
-                m_assemblyData.m_resourceBytes != null ||
-                m_assemblyData.m_nativeVersion != null)
-                throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-
-            m_assemblyData.m_nativeVersion = new NativeVersionInfo();
-
-            m_assemblyData.m_nativeVersion.m_strCopyright = copyright;
-            m_assemblyData.m_nativeVersion.m_strTrademark = trademark;
-            m_assemblyData.m_nativeVersion.m_strCompany = company;
-            m_assemblyData.m_nativeVersion.m_strProduct = product;
-            m_assemblyData.m_nativeVersion.m_strProductVersion = productVersion;
-            m_assemblyData.m_hasUnmanagedVersionInfo = true;
-            m_assemblyData.m_OverrideUnmanagedVersionInfo = true;
-
-        }
-        
-        public void DefineVersionInfoResource()
-        {
-            lock(SyncRoot)
-            {
-                DefineVersionInfoResourceNoLock();
-            }
-        }
-
-        private void DefineVersionInfoResourceNoLock()
-        {
-            if (m_assemblyData.m_strResourceFileName != null ||
-                m_assemblyData.m_resourceBytes != null ||
-                m_assemblyData.m_nativeVersion != null)
-                throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-            
-            m_assemblyData.m_hasUnmanagedVersionInfo = true;
-            m_assemblyData.m_nativeVersion = new NativeVersionInfo();
-        }
-
-        public void DefineUnmanagedResource(Byte[] resource)
-        {
-            if (resource == null)
-                throw new ArgumentNullException(nameof(resource));
-            Contract.EndContractBlock();
-
-            lock(SyncRoot)
-            {
-                DefineUnmanagedResourceNoLock(resource);
-            }
-        }
-
-        private void DefineUnmanagedResourceNoLock(Byte[] resource)
-        {
-            if (m_assemblyData.m_strResourceFileName != null ||
-                m_assemblyData.m_resourceBytes != null ||
-                m_assemblyData.m_nativeVersion != null)
-                throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-            
-            m_assemblyData.m_resourceBytes = new byte[resource.Length];
-            Buffer.BlockCopy(resource, 0, m_assemblyData.m_resourceBytes, 0, resource.Length);
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public void DefineUnmanagedResource(String resourceFileName)
-        {
-            if (resourceFileName == null)
-                throw new ArgumentNullException(nameof(resourceFileName));
-            Contract.EndContractBlock();
-
-            lock(SyncRoot)
-            {
-                DefineUnmanagedResourceNoLock(resourceFileName);
-            }
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private void DefineUnmanagedResourceNoLock(String resourceFileName)
-        {
-            if (m_assemblyData.m_strResourceFileName != null ||
-                m_assemblyData.m_resourceBytes != null ||
-                m_assemblyData.m_nativeVersion != null)
-                throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-            
-            // Check caller has the right to read the file.
-            string      strFullFileName;
-            if (m_assemblyData.m_strDir == null)
-            {
-                // If assembly directory is null, use current directory
-                strFullFileName = Path.Combine(Directory.GetCurrentDirectory(), resourceFileName);
-            }
-            else
-            {
-                // Form the full path given the directory provided by user
-                strFullFileName = Path.Combine(m_assemblyData.m_strDir, resourceFileName);
-            }
-            strFullFileName = Path.GetFullPath(resourceFileName);
-            new FileIOPermission(FileIOPermissionAccess.Read, strFullFileName).Demand();
-            
-            if (File.Exists(strFullFileName) == false)
-                throw new FileNotFoundException(Environment.GetResourceString(
-                    "IO.FileNotFound_FileName",
-                    resourceFileName), resourceFileName);
-            m_assemblyData.m_strResourceFileName = strFullFileName;
-        }
-#endif // !FEATURE_CORECLR
-
-
         /**********************************************
         *
         * return a dynamic module with the specified name.
@@ -1268,17 +846,11 @@ namespace System.Reflection.Emit
         * an exe.
         *
         **********************************************/
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public void SetEntryPoint(
             MethodInfo  entryMethod) 
         {
             SetEntryPoint(entryMethod, PEFileKinds.ConsoleApplication);
         }
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public void SetEntryPoint(
             MethodInfo  entryMethod,        // entry method for the assembly. We use this to determine the entry module
             PEFileKinds fileKind)           // file kind for the assembly.
@@ -1306,29 +878,12 @@ namespace System.Reflection.Emit
 
             m_assemblyData.m_entryPointMethod = entryMethod;
             m_assemblyData.m_peFileKind = fileKind;
-            
-#if !FEATURE_CORECLR
-            // Setting the entry point
-            ModuleBuilder tmpMB = tmpModule as ModuleBuilder;
-            if (tmpMB != null)
-                m_assemblyData.m_entryPointModule = tmpMB;
-            else
-                m_assemblyData.m_entryPointModule = GetModuleBuilder((InternalModuleBuilder)tmpModule);
-
-            MethodToken entryMethodToken = m_assemblyData.m_entryPointModule.GetMethodToken(entryMethod);
-            m_assemblyData.m_entryPointModule.SetEntryPoint(entryMethodToken);
-#endif //!FEATURE_CORECLR
         }
 
 
         /**********************************************
         * Use this function if client decides to form the custom attribute blob themselves
         **********************************************/
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -1344,7 +899,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute)
         {
             TypeBuilder.DefineCustomAttribute(
@@ -1366,7 +920,6 @@ namespace System.Reflection.Emit
         /**********************************************
         * Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
         **********************************************/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
         {
             if (customBuilder == null)
@@ -1381,7 +934,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)
         {
             customBuilder.CreateCustomAttribute(
@@ -1411,7 +963,6 @@ namespace System.Reflection.Emit
             Save(assemblyFileName, System.Reflection.PortableExecutableKinds.ILOnly, System.Reflection.ImageFileMachine.I386);
         }
             
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Save(String assemblyFileName, 
             PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
         {
@@ -1421,358 +972,15 @@ namespace System.Reflection.Emit
             }
         }
 
-#if FEATURE_CORECLR
         private void SaveNoLock(String assemblyFileName, 
             PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
         {
-            // AssemblyBuilderAccess.Save can never be set with FEATURE_CORECLR
+            // AssemblyBuilderAccess.Save can never be set in CoreCLR
             throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly"));
         }
-#else // FEATURE_CORECLR
-        [System.Security.SecurityCritical]  // auto-generated
-        private void SaveNoLock(String assemblyFileName, 
-            PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
-        {
-            if (assemblyFileName == null)
-                throw new ArgumentNullException(nameof(assemblyFileName));
-            if (assemblyFileName.Length == 0)
-                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(assemblyFileName));
-            if (!String.Equals(assemblyFileName, Path.GetFileName(assemblyFileName)))
-                throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), nameof(assemblyFileName));
-            Contract.EndContractBlock();
-
-            int i;
-            int         size;
-            Type        type;
-            TypeBuilder typeBuilder;
-            ModuleBuilder modBuilder;
-            String      strModFileName;
-            ModuleBuilder assemblyModule;
-            ResWriterData tempRes;
-            int[]       tkAttrs = null;
-            int[]       tkAttrs2 = null;
-            ModuleBuilder onDiskAssemblyModule;
 
-            BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilder.Save( " + assemblyFileName + " )");
-
-            String tmpVersionFile = null;
-
-            try 
-            {
-                if (m_assemblyData.m_iCABuilder != 0)
-                    tkAttrs = new int[m_assemblyData.m_iCABuilder];
-                if ( m_assemblyData.m_iCAs != 0)
-                    tkAttrs2 = new int[m_assemblyData.m_iCAs];
-    
-                if (m_assemblyData.m_isSaved == true)
-                {
-                    // assembly has been saved before!
-                    throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_AssemblyHasBeenSaved,
-                        InternalAssembly.GetSimpleName()));
-                }
-
-                if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) != AssemblyBuilderAccess.Save)
-                {
-                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly"));
-                }
-    
-                // Check if assembly info is supposed to be stored with one of the module files.
-                assemblyModule = m_assemblyData.FindModuleWithFileName(assemblyFileName);
-    
-                if (assemblyModule != null)
-                {
-                    m_onDiskAssemblyModuleBuilder = assemblyModule;
-
-                    // In memory this module is not the manifest module and has a valid file token
-                    // On disk it will be the manifest module so lets clean the file token
-                    // We should not retrieve FileToken after the assembly has been saved
-                    // If that is absolutely necessary, we need two separate fields on ModuleBuilderData:
-                    // the in memory file token and the on disk file token.
-                    assemblyModule.m_moduleData.FileToken = 0;
-                }
-                else
-                {   // If assembly is to be stored alone, then no file name should conflict with it.
-                    // This check will ensure resource file names are different assembly file name.
-                    m_assemblyData.CheckFileNameConflict(assemblyFileName);
-                }
-    
-                if (m_assemblyData.m_strDir == null)
-                {
-                    // set it to current directory
-                    m_assemblyData.m_strDir = Directory.GetCurrentDirectory();
-                }
-                else if (Directory.Exists(m_assemblyData.m_strDir) == false)
-                {
-                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectory", 
-                        m_assemblyData.m_strDir));
-                }
-    
-                // after this point, assemblyFileName is the full path name.
-                assemblyFileName = Path.Combine(m_assemblyData.m_strDir, assemblyFileName);
-                assemblyFileName = Path.GetFullPath(assemblyFileName);
-    
-                // Check caller has the right to create the assembly file itself.
-                new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, assemblyFileName).Demand();
-    
-                // 1. setup/create the IMetaDataAssemblyEmit for the on disk version
-                if (assemblyModule != null)
-                {
-                    // prepare saving CAs on assembly def. We need to introduce the MemberRef for
-                    // the CA's type first of all. This is for the case the we have embedded manifest.
-                    // We need to introduce these MRs before we call PreSave where we will snap
-                    // into a ondisk metadata. If we do it after this, the ondisk metadata will
-                    // not contain the proper MRs.
-                    //
-                    for (i=0; i < m_assemblyData.m_iCABuilder; i++)
-                    {
-                        tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk(
-                            assemblyModule); 
-                    }
-                    for (i=0; i < m_assemblyData.m_iCAs; i++)
-                    {
-                        tkAttrs2[i] = assemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token;
-                    }
-                    assemblyModule.PreSave(assemblyFileName, portableExecutableKind, imageFileMachine);
-                }
-    
-                RuntimeModule runtimeAssemblyModule = (assemblyModule != null) ? assemblyModule.ModuleHandle.GetRuntimeModule() : null;
-                PrepareForSavingManifestToDisk(GetNativeHandle(), runtimeAssemblyModule);
-
-                // This function will return the embedded manifest module, an already exposed ModuleBuilder
-                // created by user, or make the stand alone manifest module exposed through managed code.
-                //
-                onDiskAssemblyModule = GetOnDiskAssemblyModuleBuilder();
-    
-                // Set any native resources on the OnDiskAssemblyModule.
-                if (m_assemblyData.m_strResourceFileName != null)
-                    onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(m_assemblyData.m_strResourceFileName);
-                else if (m_assemblyData.m_resourceBytes != null)
-                    onDiskAssemblyModule.DefineUnmanagedResourceInternalNoLock(m_assemblyData.m_resourceBytes);
-                else if (m_assemblyData.m_hasUnmanagedVersionInfo == true)
-                {
-                    // calculate unmanaged version info from assembly's custom attributes
-                    m_assemblyData.FillUnmanagedVersionInfo();
-    
-                    String strFileVersion = m_assemblyData.m_nativeVersion.m_strFileVersion;
-                    if (strFileVersion == null)
-                        strFileVersion = GetVersion().ToString();
-    
-                    // Create the file.
-                    CreateVersionInfoResource(
-                         assemblyFileName,
-                         m_assemblyData.m_nativeVersion.m_strTitle,   // title
-                         null, // Icon filename
-                         m_assemblyData.m_nativeVersion.m_strDescription,   // description
-                         m_assemblyData.m_nativeVersion.m_strCopyright,
-                         m_assemblyData.m_nativeVersion.m_strTrademark,
-                         m_assemblyData.m_nativeVersion.m_strCompany,
-                         m_assemblyData.m_nativeVersion.m_strProduct,
-                         m_assemblyData.m_nativeVersion.m_strProductVersion,
-                         strFileVersion, 
-                         m_assemblyData.m_nativeVersion.m_lcid,
-                         m_assemblyData.m_peFileKind == PEFileKinds.Dll,
-                         JitHelpers.GetStringHandleOnStack(ref tmpVersionFile));
-    
-                    onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(tmpVersionFile);
-                }
-    
-                if (assemblyModule == null)
-                {
-                
-                    // This is for introducing the MRs for CA's type. This case is for stand alone
-                    // manifest. We need to wait till PrepareForSavingManifestToDisk is called. 
-                    // That will trigger the creation of the on-disk stand alone manifest module.
-                    //
-                    for (i=0; i < m_assemblyData.m_iCABuilder; i++)
-                    {
-                        tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk(
-                            onDiskAssemblyModule); 
-                    }
-                    for (i=0; i < m_assemblyData.m_iCAs; i++)
-                    {
-                        tkAttrs2[i] = onDiskAssemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token;
-                    }
-                }
-            
-                // 2. save all of the persistable modules contained by this AssemblyBuilder except the module that is going to contain
-                // Assembly information
-                // 
-                // 3. create the file list in the manifest and track the file token. If it is embedded assembly,
-                // the assembly file should not be on the file list.
-                // 
-                size = m_assemblyData.m_moduleBuilderList.Count;
-                for (i = 0; i < size; i++) 
-                {
-                    ModuleBuilder mBuilder = (ModuleBuilder) m_assemblyData.m_moduleBuilderList[i];
-                    if (mBuilder.IsTransient() == false && mBuilder != assemblyModule)
-                    {
-                        strModFileName = mBuilder.m_moduleData.m_strFileName;
-                        if (m_assemblyData.m_strDir != null)
-                        {
-                            strModFileName = Path.Combine(m_assemblyData.m_strDir, strModFileName);
-                            strModFileName = Path.GetFullPath(strModFileName);
-                        }
-                        
-                        // Check caller has the right to create the Module file itself.
-                        new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, strModFileName).Demand();
-
-                        mBuilder.m_moduleData.FileToken = AddFile(GetNativeHandle(), mBuilder.m_moduleData.m_strFileName);
-                        mBuilder.PreSave(strModFileName, portableExecutableKind, imageFileMachine);
-                        mBuilder.Save(strModFileName, false, portableExecutableKind, imageFileMachine);
-    
-                        // Cannot set the hash value when creating the file since the file token
-                        // is needed to created the entries for the embedded resources in the
-                        // module and the resources need to be there before you figure the hash.
-                        SetFileHashValue(GetNativeHandle(), mBuilder.m_moduleData.FileToken, strModFileName);
-                    }
-                }
-        
-                // 4. Add the public ComType
-                for (i=0; i < m_assemblyData.m_iPublicComTypeCount; i++)
-                {
-                    type = m_assemblyData.m_publicComTypeList[i];
-                    // If the type that was added as a Public Com Type was obtained via Reflection,
-                    //  it will be a System.RuntimeType, even if it was really, at the same time,
-                    //  a TypeBuilder.  Unfortunately, you can't get back to the TypeBuilder, so 
-                    //  this code has to deal with either-or.
-                    if (type is RuntimeType)
-                    {
-                        // If type is a runtime type, it must be a baked TypeBuilder,
-                        // ttype.Module should be an InternalModuleBuilder
-
-                        InternalModuleBuilder internalMB = (InternalModuleBuilder)type.Module;
-                        modBuilder = this.GetModuleBuilder(internalMB);
-                        if (modBuilder != assemblyModule)
-                            DefineNestedComType(type, modBuilder.m_moduleData.FileToken, type.MetadataToken);
-                    }
-                    else
-                    {
-                        // Could assert that "type" is a TypeBuilder, but next statement throws if it isn't.
-                        typeBuilder = (TypeBuilder) type;
-                        // If type is a TypeBuilder, type.Module must be a ModuleBuilder.
-                        modBuilder = typeBuilder.GetModuleBuilder();
-                        if (modBuilder != assemblyModule)
-                            DefineNestedComType(type, modBuilder.m_moduleData.FileToken, typeBuilder.MetadataTokenInternal);
-                    }
-                }
-    
-                // 5. write AssemblyDef's CAs (only if we are not saving directly the manifest module itself)
-                if (onDiskAssemblyModule != m_manifestModuleBuilder)
-                {
-                    for (i = 0; i < m_assemblyData.m_iCABuilder; i++)
-                    {
-                        m_assemblyData.m_CABuilders[i].CreateCustomAttribute(
-                            onDiskAssemblyModule,
-                            AssemblyBuilderData.m_tkAssembly,   // This is the AssemblyDef token
-                            tkAttrs[i], true);
-                    }
-
-                    for (i = 0; i < m_assemblyData.m_iCAs; i++)
-                    {
-                        TypeBuilder.DefineCustomAttribute(
-                            onDiskAssemblyModule,               // pass in the in-memory assembly module
-                            AssemblyBuilderData.m_tkAssembly,   // This is the AssemblyDef token
-                            tkAttrs2[i],
-                            m_assemblyData.m_CABytes[i],
-                            true, false);
-                    }
-                }
-    
-                // 6. write security permission requests to the manifest.
-#pragma warning disable 618
-                if (m_assemblyData.m_RequiredPset != null)
-                    AddDeclarativeSecurity(m_assemblyData.m_RequiredPset, SecurityAction.RequestMinimum);
-
-                if (m_assemblyData.m_RefusedPset != null)
-                    AddDeclarativeSecurity(m_assemblyData.m_RefusedPset, SecurityAction.RequestRefuse);
-
-                if (m_assemblyData.m_OptionalPset != null)
-                    AddDeclarativeSecurity(m_assemblyData.m_OptionalPset, SecurityAction.RequestOptional);
-#pragma warning restore 618
-
-                // 7. Save the stand alone managed resources
-                size = m_assemblyData.m_resWriterList.Count;
-                for (i = 0; i < size; i++)
-                {
-                    tempRes = null;
-    
-                    try
-                    {
-                        tempRes = (ResWriterData)m_assemblyData.m_resWriterList[i];
-    
-                        // If the user added an existing resource to the manifest, the
-                        // corresponding ResourceWriter will be null.
-                        if (tempRes.m_resWriter != null)
-                            // Check caller has the right to create the Resource file itself.
-                            new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, tempRes.m_strFullFileName).Demand();
-                    }
-                    finally
-                    {
-                        if (tempRes != null && tempRes.m_resWriter != null)
-                            tempRes.m_resWriter.Close();
-                    }
-    
-                    // Add entry to manifest for this stand alone resource
-                    AddStandAloneResource(GetNativeHandle(), tempRes.m_strName, tempRes.m_strFileName, tempRes.m_strFullFileName, (int)tempRes.m_attribute);
-                }
-    
-                // Save now!!
-                if (assemblyModule == null)
-                {
-                    onDiskAssemblyModule.DefineNativeResource(portableExecutableKind, imageFileMachine);
-    
-                    // Stand alone manifest
-                    int entryPoint = (m_assemblyData.m_entryPointModule != null) ? m_assemblyData.m_entryPointModule.m_moduleData.FileToken : 0;
-
-                    SaveManifestToDisk(GetNativeHandle(), assemblyFileName, entryPoint, (int)m_assemblyData.m_peFileKind,
-                            (int)portableExecutableKind, (int)imageFileMachine);
-                    }
-                else
-                {
-                    // embedded manifest
-                    
-                    // If the module containing the entry point is not the manifest file, we need to
-                    // let the manifest file point to the module which contains the entry point.
-                    // 
-                    // 
-                    // 
-                    // 
-                    if (m_assemblyData.m_entryPointModule != null && m_assemblyData.m_entryPointModule != assemblyModule)
-                        assemblyModule.SetEntryPoint(new MethodToken(m_assemblyData.m_entryPointModule.m_moduleData.FileToken));
-                    assemblyModule.Save(assemblyFileName, true, portableExecutableKind, imageFileMachine);
-                }
-                m_assemblyData.m_isSaved = true;
-            }
-            finally
-            {
-                if (tmpVersionFile != null)
-                {
-                    // Delete file.
-                    System.IO.File.Delete(tmpVersionFile);
-                }
-            }
-        }
-#endif // FEATURE_CORECLR
-    
-#if FEATURE_CAS_POLICY
-        [System.Security.SecurityCritical]  // auto-generated
-        private void AddDeclarativeSecurity(PermissionSet pset, SecurityAction action)
-        {
-            // Translate sets into internal encoding (uses standard binary serialization).
-            byte[] blob = pset.EncodeXml();
-            AddDeclarativeSecurity(GetNativeHandle(), action, blob, blob.Length);
-        }
-#endif // FEATURE_CAS_POLICY
-        
         internal bool IsPersistable()
         {
-#if !FEATURE_CORECLR // AssemblyBuilderAccess.Save is never set in CoreCLR
-            if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) == AssemblyBuilderAccess.Save)
-            {
-                return true;
-            }
-            else
-#endif // FEATURE_CORECLR
             {
                 return false;
             }
@@ -1783,7 +991,6 @@ namespace System.Reflection.Emit
         * Internal helper to walk the nested type hierachy
         *
         **********************************************/
-        [System.Security.SecurityCritical]  // auto-generated
         private int DefineNestedComType(Type type, int tkResolutionScope, int tkTypeDef)
         {
             Type        enclosingType = type.DeclaringType;
@@ -1798,7 +1005,6 @@ namespace System.Reflection.Emit
             return AddExportedTypeOnDisk(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal int DefineExportedTypeInMemory(Type type, int tkResolutionScope, int tkTypeDef)
         {
             Type enclosingType = type.DeclaringType;
@@ -1825,32 +1031,7 @@ namespace System.Reflection.Emit
          **********************************************/
         private AssemblyBuilder() {}
 
-#if !FEATURE_CORECLR
-        void _AssemblyBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _AssemblyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        // If you implement this method, make sure to include _AssemblyBuilder.Invoke in VM\DangerousAPIs.h and 
-        // include _AssemblyBuilder in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
-        void _AssemblyBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
         // Create a new module in which to emit code. This module will not contain the manifest.
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static private extern void DefineDynamicModule(RuntimeAssembly containingAssembly,
@@ -1863,7 +1044,6 @@ namespace System.Reflection.Emit
                                                        bool fIsTransient,
                                                        out int tkFile);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static Module DefineDynamicModule(RuntimeAssembly containingAssembly, 
                                            bool emitSymbolInfo,
                                            String name,
@@ -1889,12 +1069,10 @@ namespace System.Reflection.Emit
         }
 
         // The following functions are native helpers for creating on-disk manifest
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static private extern void PrepareForSavingManifestToDisk(RuntimeAssembly assembly, RuntimeModule assemblyModule);  // module to contain assembly information if assembly is embedded
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static private extern void SaveManifestToDisk(RuntimeAssembly assembly,
@@ -1904,19 +1082,16 @@ namespace System.Reflection.Emit
                                                 int portableExecutableKind, 
                                                 int ImageFileMachine);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static private extern int AddFile(RuntimeAssembly assembly, String strFileName);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static private extern void SetFileHashValue(RuntimeAssembly assembly,
                                                     int tkFile, 
                                                     String strFullFileName);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static private extern int AddExportedTypeInMemory(RuntimeAssembly assembly,
@@ -1925,7 +1100,6 @@ namespace System.Reflection.Emit
                                                           int tkTypeDef,
                                                           TypeAttributes flags);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static private extern int AddExportedTypeOnDisk(RuntimeAssembly assembly, 
@@ -1935,7 +1109,6 @@ namespace System.Reflection.Emit
                                                         TypeAttributes flags);
 
         // Add an entry to assembly's manifestResource table for a stand alone resource.
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static private extern void AddStandAloneResource(RuntimeAssembly assembly,
@@ -1944,7 +1117,6 @@ namespace System.Reflection.Emit
                                                          String strFullFileName,
                                                          int attribute);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
 #pragma warning disable 618
@@ -1952,7 +1124,6 @@ namespace System.Reflection.Emit
 #pragma warning restore 618
 
         // Functions for defining unmanaged resources.
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static private extern void CreateVersionInfoResource(String filename, String title, String iconFilename, String description,
index 00a961d..5c86d8e 100644 (file)
@@ -8,17 +8,13 @@ using System;
 // EE uses these enum values..look for m_dwDynamicAssemblyAccess in Assembly.hpp
 
 namespace System.Reflection.Emit 
-{    
+{
     [Serializable]
     [System.Runtime.InteropServices.ComVisible(true)]
     [Flags]
     public enum AssemblyBuilderAccess
     {
         Run = 1,
-#if !FEATURE_CORECLR // these are unsupported
-        Save = 2,
-        RunAndSave = Run | Save,
-#endif // !FEATURE_CORECLR
 #if FEATURE_REFLECTION_ONLY_LOAD
         ReflectionOnly = 6, // 4 | Save,
 #endif // FEATURE_REFLECTION_ONLY_LOAD
index b2e62d6..f0f83e7 100644 (file)
@@ -14,11 +14,7 @@ namespace System.Reflection.Emit {
     using System.Security;
     using System.Diagnostics;
     using CultureInfo = System.Globalization.CultureInfo;
-#if !FEATURE_CORECLR
-    using ResourceWriter = System.Resources.ResourceWriter;
-#else // FEATURE_CORECLR
     using IResourceWriter = System.Resources.IResourceWriter;
-#endif // !FEATURE_CORECLR
     using System.IO;
     using System.Runtime.Versioning;
     using System.Diagnostics.SymbolStore;
@@ -29,7 +25,6 @@ namespace System.Reflection.Emit {
     // this class cannot be accessed from the EE.
     internal class AssemblyBuilderData
     {
-        [SecurityCritical]
         internal AssemblyBuilderData(
             InternalAssemblyBuilder assembly, 
             String                  strAssemblyName, 
@@ -120,7 +115,6 @@ namespace System.Reflection.Emit {
         // If DefineUnmanagedVersionInfo is called, the parameter provided will override
         // the CA's value.
         //                      
-        [System.Security.SecurityCritical]  // auto-generated
         internal void FillUnmanagedVersionInfo()
         {
             // Get the lcid set on the assembly name as default if available
@@ -469,7 +463,7 @@ namespace System.Reflection.Emit {
 
         // hard coding the assembly def token
         internal const int              m_tkAssembly = 0x20000001;
-    
+
         // Security permission requests
         internal PermissionSet          m_RequiredPset;
         internal PermissionSet          m_OptionalPset;
@@ -485,10 +479,6 @@ namespace System.Reflection.Emit {
         internal MethodInfo             m_entryPointMethod;
         internal Assembly               m_ISymWrapperAssembly;
 
-#if !FEATURE_CORECLR
-        internal ModuleBuilder          m_entryPointModule;
-#endif //!FEATURE_CORECLR
-                                  
         // For unmanaged resources
         internal String                 m_strResourceFileName;
         internal byte[]                 m_resourceBytes;
@@ -507,7 +497,6 @@ namespace System.Reflection.Emit {
     **********************************************/
     internal class ResWriterData 
     {
-#if FEATURE_CORECLR
         internal ResWriterData(
             IResourceWriter  resWriter,
             Stream          memoryStream,
@@ -524,29 +513,8 @@ namespace System.Reflection.Emit {
             m_nextResWriter = null;
             m_attribute = attribute;
         }
-#else
-        internal ResWriterData(
-            ResourceWriter  resWriter,
-            Stream          memoryStream,
-            String          strName,
-            String          strFileName,
-            String          strFullFileName,
-            ResourceAttributes attribute)
-        {
-            m_resWriter = resWriter;
-            m_memoryStream = memoryStream;
-            m_strName = strName;
-            m_strFileName = strFileName;
-            m_strFullFileName = strFullFileName;
-            m_nextResWriter = null;
-            m_attribute = attribute;
-        }
-#endif
-#if !FEATURE_CORECLR
-        internal ResourceWriter         m_resWriter;
-#else // FEATURE_CORECLR
-         internal IResourceWriter         m_resWriter;
-#endif // !FEATURE_CORECLR
+
+        internal IResourceWriter        m_resWriter;
         internal String                 m_strName;
         internal String                 m_strFileName;
         internal String                 m_strFullFileName;
index 0d8ce5a..8dba934 100644 (file)
@@ -2,33 +2,15 @@
 // 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.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Security.Permissions;
-using System.Security.Policy;
-
 namespace System.Runtime.InteropServices
 {
     [GuidAttribute("BEBB2505-8B54-3443-AEAD-142A16DD9CC7")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.AssemblyBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _AssemblyBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("ED3E4384-D7E2-3FA7-8FFD-8940D330519A")]
@@ -38,141 +20,69 @@ namespace System.Runtime.InteropServices
     [System.Runtime.InteropServices.ComVisible(true)]
     public interface _ConstructorBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("BE9ACCE8-AAFF-3B91-81AE-8211663F5CAD")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.CustomAttributeBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _CustomAttributeBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("C7BD73DE-9F85-3290-88EE-090B8BDFE2DF")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EnumBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _EnumBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("AADABA99-895D-3D65-9760-B1F12621FAE8")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EventBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _EventBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("CE1A3BF5-975E-30CC-97C9-1EF70F8F3993")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.FieldBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _FieldBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("A4924B27-6E3B-37F7-9B83-A4501955E6A7")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ILGenerator))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _ILGenerator
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("4E6350D1-A08B-3DEC-9A3E-C465F9AEEC0C")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.LocalBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _LocalBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("007D8A14-FDF3-363E-9A0B-FEC0618260A2")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _MethodBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
 #if FEATURE_METHOD_RENTAL
@@ -180,18 +90,9 @@ namespace System.Runtime.InteropServices
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodRental))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _MethodRental
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 #endif
 
@@ -199,90 +100,44 @@ namespace System.Runtime.InteropServices
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ModuleBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _ModuleBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("36329EBA-F97A-3565-BC07-0ED5C6EF19FC")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ParameterBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _ParameterBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("15F9A479-9397-3A63-ACBD-F51977FB0F02")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.PropertyBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _PropertyBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("7D13DD37-5A04-393C-BBCA-A5FEA802893D")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.SignatureHelper))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _SignatureHelper
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("7E5678EE-48B3-3F83-B076-C58543498A58")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.TypeBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _TypeBuilder
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
-
 }
index 7bf3a67..ef76adc 100644 (file)
@@ -16,7 +16,6 @@ namespace System.Reflection.Emit
     using System.Runtime.InteropServices;
     using System.Diagnostics.Contracts;
     
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_ConstructorBuilder))]
     [System.Runtime.InteropServices.ComVisible(true)]
@@ -31,7 +30,6 @@ namespace System.Reflection.Emit
         {
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
             Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type)
         {
@@ -49,7 +47,6 @@ namespace System.Reflection.Emit
             token = m_methodBuilder.GetToken();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
             Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) : 
             this(name, attributes, callingConvention, parameterTypes, null, null, mod, type)
@@ -205,9 +202,6 @@ namespace System.Reflection.Emit
             return m_methodBuilder.GetILGenerator(streamSize);
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
         {
             if (m_isDefaultConstructor)
@@ -218,36 +212,6 @@ namespace System.Reflection.Emit
             m_methodBuilder.SetMethodBody(il, maxStack, localSignature, exceptionHandlers, tokenFixups);
         }
 
-#if FEATURE_CAS_POLICY
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
-        {
-            if (pset == null)
-                throw new ArgumentNullException(nameof(pset));
-
-#pragma warning disable 618
-            if (!Enum.IsDefined(typeof(SecurityAction), action) ||
-                action == SecurityAction.RequestMinimum ||
-                action == SecurityAction.RequestOptional ||
-                action == SecurityAction.RequestRefuse)
-            {
-                throw new ArgumentOutOfRangeException(nameof(action));
-            }
-#pragma warning restore 618
-            Contract.EndContractBlock();
-
-            // Cannot add declarative security after type is created.
-            if (m_methodBuilder.IsTypeCreated())
-                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
-    
-            // Translate permission set into serialized format (use standard binary serialization).
-            byte[] blob = pset.EncodeXml();
-    
-            // Write the blob into the metadata.
-            TypeBuilder.AddDeclarativeSecurity(GetModuleBuilder().GetNativeHandle(), GetToken().Token, action, blob, blob.Length);
-        }
-#endif // FEATURE_CAS_POLICY
-
         public override CallingConventions CallingConvention 
         { 
             get 
@@ -282,9 +246,6 @@ namespace System.Reflection.Emit
             get { return m_methodBuilder.Signature; }
         }
     
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -308,28 +269,6 @@ namespace System.Reflection.Emit
         }
 
         #endregion
-
-#if !FEATURE_CORECLR
-        void _ConstructorBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ConstructorBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ConstructorBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ConstructorBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 }
 
index 3ef44a5..545657a 100644 (file)
@@ -22,9 +22,9 @@ namespace System.Reflection.Emit {
     using System.Security.Permissions;
     using System.Runtime.InteropServices;
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_CustomAttributeBuilder))]
     [System.Runtime.InteropServices.ComVisible(true)]
@@ -353,7 +353,7 @@ namespace System.Reflection.Emit {
                         writer.Write((byte)CustomAttributeEncoding.Double);
                         break;
                     default:
-                        Contract.Assert(false, "Invalid primitive type");
+                        Debug.Assert(false, "Invalid primitive type");
                         break;
                 }
             }
@@ -437,7 +437,7 @@ namespace System.Reflection.Emit {
                         writer.Write((ulong)value);
                         break;
                     default:
-                        Contract.Assert(false, "Invalid enum base type");
+                        Debug.Assert(false, "Invalid enum base type");
                         break;
                 }
             }
@@ -515,7 +515,7 @@ namespace System.Reflection.Emit {
                         writer.Write((double)value);
                         break;
                     default:
-                        Contract.Assert(false, "Invalid primitive type");
+                        Debug.Assert(false, "Invalid primitive type");
                         break;
                 }
             }
@@ -550,7 +550,6 @@ namespace System.Reflection.Emit {
          
 
         // return the byte interpretation of the custom attribute
-        [System.Security.SecurityCritical]  // auto-generated
         internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner)
         {
             CreateCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con).Token, false);
@@ -563,7 +562,6 @@ namespace System.Reflection.Emit {
         // This function has to be called before we snap the in-memory module for on disk (i.e. Presave on
         // ModuleBuilder.
         //*************************************************
-        [System.Security.SecurityCritical]  // auto-generated
         internal int PrepareCreateCustomAttributeToDisk(ModuleBuilder mod)
         {
             return mod.InternalGetConstructorToken(m_con, true).Token;
@@ -572,35 +570,12 @@ namespace System.Reflection.Emit {
         //*************************************************
         // Call this function with toDisk=1, after on disk module has been snapped.
         //*************************************************
-        [System.Security.SecurityCritical]  // auto-generated
         internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk)
         {
             TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk, 
                                                       typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType);
         }
 
-#if !FEATURE_CORECLR
-        void _CustomAttributeBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _CustomAttributeBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _CustomAttributeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _CustomAttributeBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
         internal ConstructorInfo    m_con;
         internal Object[]           m_constructorArgs;
         internal byte[]             m_blob;
index 7a5c5a8..9e1d829 100644 (file)
@@ -16,6 +16,7 @@ namespace System.Reflection.Emit
     using System.Collections.Generic;
     using System.Security.Permissions;
     using System.Threading;
+    using System.Diagnostics;
     using System.Diagnostics.CodeAnalysis;
     using System.Diagnostics.Contracts;
     using System.Security;
@@ -35,7 +36,6 @@ namespace System.Reflection.Emit
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
         {
             dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
@@ -86,7 +86,6 @@ namespace System.Reflection.Emit
         // Token resolution calls
         //
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override void Emit(OpCode opcode, MethodInfo meth)
         {
             if (meth == null)
@@ -227,7 +226,6 @@ namespace System.Reflection.Emit
         // Signature related calls (vararg, calli)
         //
         //
-        [System.Security.SecuritySafeCritical] // overrides SC
         public override void EmitCalli(OpCode opcode,
                                        CallingConventions callingConvention,
                                        Type returnType,
@@ -306,7 +304,6 @@ namespace System.Reflection.Emit
             PutInteger4(token);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
         {
             if (methodInfo == null)
@@ -364,7 +361,7 @@ namespace System.Reflection.Emit
             // SignatureHelper.
             if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
             {
-                Contract.Assert(opcode.Equals(OpCodes.Calli),
+                Debug.Assert(opcode.Equals(OpCodes.Calli),
                                 "Unexpected opcode encountered for StackBehaviour VarPop.");
                 // Pop the arguments..
                 stackchange -= signature.ArgumentCount;
@@ -481,7 +478,6 @@ namespace System.Reflection.Emit
             throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes)
         {
             Type[] parameterTypes;
@@ -518,7 +514,6 @@ namespace System.Reflection.Emit
                 return GetTokenForVarArgMethod(dm, sig);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override SignatureHelper GetMemberRefSignature(
                                                 CallingConventions call,
                                                 Type returnType,
@@ -703,9 +698,6 @@ namespace System.Reflection.Emit
             m_method.m_resolver = this;
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         internal DynamicResolver(DynamicILInfo dynamicILInfo)
         {
             m_stackSize = dynamicILInfo.MaxStackSize;
@@ -773,7 +765,6 @@ namespace System.Reflection.Emit
         {
             internal RuntimeMethodHandleInternal m_methodHandle;
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
             ~DestroyScout()
             {
                 if (m_methodHandle.IsNullHandle())
@@ -886,7 +877,6 @@ namespace System.Reflection.Emit
             return m_exceptionHeader;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe void GetEHInfo(int excNumber, void* exc)
         {
             CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc;
@@ -921,7 +911,6 @@ namespace System.Reflection.Emit
         }
 #endif // FEATURE_COMPRESSEDSTACK
 
-        [System.Security.SecurityCritical]
         internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle)
         {
             typeHandle = new IntPtr();
@@ -1002,9 +991,6 @@ namespace System.Reflection.Emit
     }
 
 
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#endif
     [System.Runtime.InteropServices.ComVisible(true)]
     public class DynamicILInfo
     {
@@ -1031,7 +1017,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Internal Methods
-        [System.Security.SecurityCritical]  // auto-generated
         internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
         {
             dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
@@ -1063,7 +1048,6 @@ namespace System.Reflection.Emit
             m_maxStackSize = maxStackSize;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         public unsafe void SetCode(byte* code, int codeSize, int maxStackSize)
         {
@@ -1089,7 +1073,6 @@ namespace System.Reflection.Emit
             m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : EmptyArray<Byte>.Value;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         public unsafe void SetExceptions(byte* exceptions, int exceptionsSize)
         {
@@ -1114,7 +1097,6 @@ namespace System.Reflection.Emit
             m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : EmptyArray<Byte>.Value;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         public unsafe void SetLocalSignature(byte* localSignature, int signatureSize)
         {
@@ -1135,7 +1117,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Public Scope Methods
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public int GetTokenFor(RuntimeMethodHandle method)
         {
             return DynamicScope.GetTokenFor(method);
@@ -1221,7 +1202,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Public Methods
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public int GetTokenFor(RuntimeMethodHandle method)
         {
             IRuntimeMethodInfo methodReal = method.GetMethodInfo();
index bb6af23..1b8c97d 100644 (file)
@@ -15,6 +15,7 @@ namespace System.Reflection.Emit
     using System.Threading;
     using System.Runtime.CompilerServices;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Runtime.InteropServices;
 
@@ -25,9 +26,6 @@ namespace System.Reflection.Emit
         internal IRuntimeMethodInfo m_methodHandle;
         private RuntimeType m_returnType;
         private DynamicILGenerator m_ilGenerator;
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         private DynamicILInfo m_DynamicILInfo;
         private bool m_fInitLocals;
         private RuntimeModule m_module;
@@ -72,7 +70,6 @@ namespace System.Reflection.Emit
 
         private DynamicMethod() { }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public DynamicMethod(string name,
                              Type returnType,
@@ -92,7 +89,6 @@ namespace System.Reflection.Emit
                 ref stackMark);  // transparentMethod
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public DynamicMethod(string name,
                              Type returnType,
@@ -113,11 +109,6 @@ namespace System.Reflection.Emit
                 ref stackMark);  // transparentMethod
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public DynamicMethod(string name, 
                              Type returnType, 
@@ -137,11 +128,6 @@ namespace System.Reflection.Emit
                 ref stackMark);  // transparentMethod
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public DynamicMethod(string name, 
                              Type returnType, 
@@ -162,11 +148,6 @@ namespace System.Reflection.Emit
                 ref stackMark); // transparentMethod
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public DynamicMethod(string name, 
                              MethodAttributes attributes, 
@@ -189,11 +170,6 @@ namespace System.Reflection.Emit
                 ref stackMark); // transparentMethod
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public DynamicMethod(string name, 
                              Type returnType, 
@@ -213,11 +189,6 @@ namespace System.Reflection.Emit
                 ref stackMark); // transparentMethod
         }
         
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public DynamicMethod(string name, 
                              Type returnType, 
@@ -238,11 +209,6 @@ namespace System.Reflection.Emit
                 ref stackMark); // transparentMethod
         }
         
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public DynamicMethod(string name, 
                              MethodAttributes attributes, 
@@ -286,7 +252,6 @@ namespace System.Reflection.Emit
 
         // We create a transparent assembly to host DynamicMethods. Since the assembly does not have any
         // non-public fields (or any fields at all), it is a safe anonymous assembly to host DynamicMethods
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         private static RuntimeModule GetDynamicMethodsModule()
         {
@@ -302,21 +267,6 @@ namespace System.Reflection.Emit
                 CustomAttributeBuilder transparencyAttribute = new CustomAttributeBuilder(transparencyCtor, EmptyArray<Object>.Value);
                 List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
                 assemblyAttributes.Add(transparencyAttribute);
-#if !FEATURE_CORECLR
-                // On the desktop, we need to use the security rule set level 1 for anonymously hosted
-                // dynamic methods.  In level 2, transparency rules are strictly enforced, which leads to
-                // errors when a fully trusted application causes a dynamic method to be generated that tries
-                // to call a method with a LinkDemand or a SecurityCritical method.  To retain compatibility
-                // with the v2.0 and v3.x frameworks, these calls should be allowed.
-                //
-                // If this rule set was not explicitly called out, then the anonymously hosted dynamic methods
-                // assembly would inherit the rule set from the creating assembly - which would cause it to
-                // be level 2 because mscorlib.dll is using the level 2 rules.
-                ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) });
-                CustomAttributeBuilder securityRulesAttribute =
-                    new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level1 });
-                assemblyAttributes.Add(securityRulesAttribute);
-#endif // !FEATURE_CORECLR
 
                 AssemblyName assemblyName = new AssemblyName("Anonymously Hosted DynamicMethods Assembly");
                 StackCrawlMark stackMark = StackCrawlMark.LookForMe;
@@ -338,7 +288,6 @@ namespace System.Reflection.Emit
             return s_anonymouslyHostedDynamicMethodsModule;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe void Init(String name, 
                                  MethodAttributes attributes, 
                                  CallingConventions callingConvention, 
@@ -374,7 +323,7 @@ namespace System.Reflection.Emit
 
             if (transparentMethod)
             {
-                Contract.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods");
+                Debug.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods");
                 m_module = GetDynamicMethodsModule();
                 if (skipVisibility)
                 {
@@ -387,9 +336,9 @@ namespace System.Reflection.Emit
             }
             else
             {
-                Contract.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set");
-                Contract.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly");
-                Contract.Assert(m == null || owner == null, "m and owner cannot both be set");
+                Debug.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set");
+                Debug.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly");
+                Debug.Assert(m == null || owner == null, "m and owner cannot both be set");
 
                 if (m != null)
                     m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects.
@@ -435,101 +384,23 @@ namespace System.Reflection.Emit
             m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void PerformSecurityCheck(Module m, ref StackCrawlMark stackMark, bool skipVisibility)
         {
             if (m == null) 
                 throw new ArgumentNullException(nameof(m));
             Contract.EndContractBlock();
-#if !FEATURE_CORECLR
-
-            RuntimeModule rtModule;
-            ModuleBuilder mb = m as ModuleBuilder;
-            if (mb != null)
-                rtModule = mb.InternalModule;
-            else
-                rtModule = m as RuntimeModule;
-
-            if (rtModule == null)
-            {
-                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeModule"), nameof(m));
-            }
-
-            // The user cannot explicitly use this assembly
-            if (rtModule == s_anonymouslyHostedDynamicMethodsModule)
-                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"), nameof(m));
-
-            // ask for member access if skip visibility
-            if (skipVisibility) 
-                new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
-
-#if !FEATURE_CORECLR
-            // ask for control evidence if outside of the caller assembly
-            RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark);
-            m_creatorAssembly = callingType.GetRuntimeAssembly();
-            if (m.Assembly != m_creatorAssembly)
-            {
-                // Demand the permissions of the assembly where the DynamicMethod will live
-                CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence,
-                                                                      m.Assembly.PermissionSet);
-            }
-#else //FEATURE_CORECLR
-#pragma warning disable 618
-                new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
-#pragma warning restore 618
-#endif //FEATURE_CORECLR
-#endif //!FEATURE_CORECLR
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility)
         {
             if (owner == null)
                 throw new ArgumentNullException(nameof(owner));
-#if !FEATURE_CORECLR
-
-            RuntimeType rtOwner = owner as RuntimeType;
-            if (rtOwner == null)
-                rtOwner = owner.UnderlyingSystemType as RuntimeType;
-
-            if (rtOwner == null)
-                throw new ArgumentNullException(nameof(owner), Environment.GetResourceString("Argument_MustBeRuntimeType"));
-
-            // get the type the call is coming from
-            RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark);
-
-            // ask for member access if skip visibility
-            if (skipVisibility) 
-                new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
-            else
-            {
-                // if the call is not coming from the same class ask for member access
-                if (callingType != rtOwner)
-                    new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
-            }
-#if !FEATURE_CORECLR
-            m_creatorAssembly = callingType.GetRuntimeAssembly();
-
-            // ask for control evidence if outside of the caller module
-            if (rtOwner.Assembly != m_creatorAssembly)
-            {
-                // Demand the permissions of the assembly where the DynamicMethod will live
-                CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence,
-                                                                      owner.Assembly.PermissionSet);
-            }
-#else //FEATURE_CORECLR
-#pragma warning disable 618
-                new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
-#pragma warning restore 618
-#endif //FEATURE_CORECLR
-#endif //!FEATURE_CORECLR
         }
 
         //
         // Delegate and method creation
         //
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public sealed override Delegate CreateDelegate(Type delegateType) {
             if (m_restrictedSkipVisibility)
@@ -545,7 +416,6 @@ namespace System.Reflection.Emit
             return d;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public sealed override Delegate CreateDelegate(Type delegateType, Object target) {
             if (m_restrictedSkipVisibility)
@@ -578,7 +448,6 @@ namespace System.Reflection.Emit
 #endif
 
         // This is guaranteed to return a valid handle
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe RuntimeMethodHandle GetMethodDescriptor() {
             if (m_methodHandle == null) {
                 lock (this) {
@@ -636,95 +505,19 @@ namespace System.Reflection.Emit
 
         public override bool IsSecurityCritical
         {
-#if FEATURE_CORECLR
             get { return true; }
-#else
-            [SecuritySafeCritical]
-            get
-            {
-                if (m_methodHandle != null)
-                {
-                    return RuntimeMethodHandle.IsSecurityCritical(m_methodHandle);
-                }
-                else if (m_typeOwner != null)
-                {
-                    RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
-                    Contract.Assert(assembly != null);
-
-                    return assembly.IsAllSecurityCritical();
-                }
-                else
-                {
-                    RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
-                    Contract.Assert(assembly != null);
-
-                    return assembly.IsAllSecurityCritical();
-                }
-            }
-#endif
         }
 
         public override bool IsSecuritySafeCritical
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            [SecuritySafeCritical]
-            get
-            {
-                if (m_methodHandle != null)
-                {
-                    return RuntimeMethodHandle.IsSecuritySafeCritical(m_methodHandle);
-                }
-                else if (m_typeOwner != null)
-                {
-                    RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
-                    Contract.Assert(assembly != null);
-
-                    return assembly.IsAllPublicAreaSecuritySafeCritical();
-                }
-                else
-                {
-                    RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
-                    Contract.Assert(assembly != null);
-
-                    return assembly.IsAllSecuritySafeCritical();
-                }
-            }
-#endif
         }
 
         public override bool IsSecurityTransparent
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            [SecuritySafeCritical]
-            get
-            {
-                if (m_methodHandle != null)
-                {
-                    return RuntimeMethodHandle.IsSecurityTransparent(m_methodHandle);
-                }
-                else if (m_typeOwner != null)
-                {
-                    RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
-                    Contract.Assert(assembly != null);
-
-                    return !assembly.IsAllSecurityCritical();
-                }
-                else
-                {
-                    RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
-                    Contract.Assert(assembly != null);
-
-                    return !assembly.IsAllSecurityCritical();
-                }
-            }
-#endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
             if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_CallToVarArg"));
@@ -801,7 +594,6 @@ namespace System.Reflection.Emit
             return null;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public DynamicILInfo GetDynamicILInfo()
         {
 #pragma warning disable 618
@@ -814,7 +606,6 @@ namespace System.Reflection.Emit
             return GetDynamicILInfo(new DynamicScope());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal DynamicILInfo GetDynamicILInfo(DynamicScope scope)
         {
             if (m_DynamicILInfo == null)
@@ -831,7 +622,6 @@ namespace System.Reflection.Emit
             return GetILGenerator(64);
         }
 
-       [System.Security.SecuritySafeCritical]  // auto-generated
        public ILGenerator GetILGenerator(int streamSize) 
         {
             if (m_ilGenerator == null)
index dfb0b15..82dc282 100644 (file)
@@ -23,7 +23,6 @@ namespace System.Reflection.Emit {
     using System.Security.Permissions;
 
     
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_EnumBuilder))]
 [System.Runtime.InteropServices.ComVisible(true)]
@@ -313,9 +312,6 @@ namespace System.Reflection.Emit {
 
        // Use this function if client decides to form the custom attribute blob themselves
 
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#endif
 [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -398,7 +394,6 @@ namespace System.Reflection.Emit {
             
         // Constructs a EnumBuilder.
         // EnumBuilder can only be a top-level (not nested) enum type.
-        [System.Security.SecurityCritical]  // auto-generated
         internal EnumBuilder(
             String      name,                       // name of type
             Type        underlyingType,             // underlying type for an Enum
@@ -414,29 +409,6 @@ namespace System.Reflection.Emit {
             m_underlyingField = m_typeBuilder.DefineField("value__", underlyingType, FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
         }
 
-#if !FEATURE_CORECLR
-        void _EnumBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _EnumBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _EnumBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _EnumBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
-
         /*****************************************************
          * 
          * private data members
index 60289a1..449b208 100644 (file)
@@ -24,7 +24,6 @@ namespace System.Reflection.Emit {
     // A EventBuilder is always associated with a TypeBuilder.  The TypeBuilder.DefineEvent
     // method will return a new EventBuilder to a client.
     // 
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_EventBuilder))]
 [System.Runtime.InteropServices.ComVisible(true)]
@@ -58,7 +57,6 @@ namespace System.Reflection.Emit {
             return m_evToken;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics)
         {
             if (mdBuilder == null)
@@ -75,25 +73,21 @@ namespace System.Reflection.Emit {
                 mdBuilder.GetToken().Token);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetAddOnMethod(MethodBuilder mdBuilder)
         {
             SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.AddOn);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetRemoveOnMethod(MethodBuilder mdBuilder)
         {
             SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.RemoveOn);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetRaiseMethod(MethodBuilder mdBuilder)
         {
             SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Fire);
         }
        
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AddOtherMethod(MethodBuilder mdBuilder)
         {
             SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other);
@@ -101,11 +95,6 @@ namespace System.Reflection.Emit {
     
         // Use this function if client decides to form the custom attribute blob themselves
 
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#else
-[System.Security.SecuritySafeCritical]
-#endif
 [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -125,7 +114,6 @@ namespace System.Reflection.Emit {
         }
 
         // Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
         {
             if (customBuilder == null)
@@ -137,29 +125,6 @@ namespace System.Reflection.Emit {
             customBuilder.CreateCustomAttribute(m_module, m_evToken.Token);
         }
 
-#if !FEATURE_CORECLR
-        void _EventBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _EventBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _EventBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _EventBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
-
         // These are package private so that TypeBuilder can access them.
         private String              m_name;         // The name of the event
         private EventToken          m_evToken;      // The token of this event
@@ -167,8 +132,4 @@ namespace System.Reflection.Emit {
         private EventAttributes     m_attributes;
         private TypeBuilder         m_type;       
     }
-
-
-
-
 }
index 84449bd..595d60a 100644 (file)
@@ -13,7 +13,6 @@ namespace System.Reflection.Emit
     using System.Security.Permissions;
     using System.Diagnostics.Contracts;
     
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_FieldBuilder))]
 [System.Runtime.InteropServices.ComVisible(true)]
@@ -29,7 +28,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Constructor
-        [System.Security.SecurityCritical]  // auto-generated
         internal FieldBuilder(TypeBuilder typeBuilder, String fieldName, Type type, 
             Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
         {
@@ -69,7 +67,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Internal Members
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetData(byte[] data, int size)
         {
             ModuleBuilder.SetFieldRVAContent(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), m_tkField.Token, data, size);
@@ -181,11 +178,6 @@ namespace System.Reflection.Emit
             return m_tkField;
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         public void SetOffset(int iOffset) 
         {
             m_typeBuilder.ThrowIfCreated();     
@@ -193,7 +185,6 @@ namespace System.Reflection.Emit
             TypeBuilder.SetFieldLayoutOffset(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, iOffset);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
         public void SetMarshal(UnmanagedMarshal unmanagedMarshal)
         {
@@ -208,7 +199,6 @@ namespace System.Reflection.Emit
             TypeBuilder.SetFieldMarshal(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, ubMarshal, ubMarshal.Length);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetConstant(Object defaultValue) 
         {
             m_typeBuilder.ThrowIfCreated();  
@@ -217,11 +207,6 @@ namespace System.Reflection.Emit
         }
         
 
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#else
-[System.Security.SecuritySafeCritical]
-#endif
 [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -240,7 +225,6 @@ namespace System.Reflection.Emit
                 m_tkField.Token, module.GetConstructorToken(con).Token, binaryAttribute, false, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
         {
             if (customBuilder == null)
@@ -255,27 +239,5 @@ namespace System.Reflection.Emit
         }
 
         #endregion
-
-#if !FEATURE_CORECLR
-        void _FieldBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _FieldBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _FieldBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _FieldBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 }
index bcf70db..6987ea1 100644 (file)
@@ -212,9 +212,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Public Members
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {   
             m_type.SetGenParamCustomAttribute(con, binaryAttribute);
index 22f78df..ed0763b 100644 (file)
@@ -12,6 +12,7 @@ namespace System.Reflection.Emit
     using System.Reflection;
     using System.Security.Permissions;
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     
     [ClassInterface(ClassInterfaceType.None)]
@@ -209,20 +210,17 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetMethodToken(MethodBase method, Type[] optionalParameterTypes, bool useMethodDef)
         {
             return ((ModuleBuilder)m_methodBuilder.Module).GetMethodTokenInternal(method, optionalParameterTypes, useMethodDef);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, 
             Type[] parameterTypes, Type[] optionalParameterTypes)
         {
             return GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, 0);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, 
             Type[] parameterTypes, Type[] optionalParameterTypes, int cGenericParameters)
         {
@@ -413,7 +411,7 @@ namespace System.Reflection.Emit
         {
             if (m_RelocFixupCount == 0)
             {
-                Contract.Assert(m_RelocFixupList == null);
+                Debug.Assert(m_RelocFixupList == null);
                 return null;
             }
 
@@ -471,7 +469,6 @@ namespace System.Reflection.Emit
             PutInteger4(arg);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public virtual void Emit(OpCode opcode, MethodInfo meth)
         {
             if (meth == null)
@@ -503,7 +500,6 @@ namespace System.Reflection.Emit
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, 
             Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes)
         {
@@ -592,7 +588,6 @@ namespace System.Reflection.Emit
             PutInteger4(modBuilder.GetSignatureToken(sig).Token);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
         {
             if (methodInfo == null)
@@ -652,7 +647,7 @@ namespace System.Reflection.Emit
             // SignatureHelper.
             if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
             {
-                Contract.Assert(opcode.Equals(OpCodes.Calli),
+                Debug.Assert(opcode.Equals(OpCodes.Calli),
                                 "Unexpected opcode encountered for StackBehaviour VarPop.");
                 // Pop the arguments..
                 stackchange -= signature.ArgumentCount;
@@ -665,7 +660,6 @@ namespace System.Reflection.Emit
             PutInteger4(tempVal);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public virtual void Emit(OpCode opcode, ConstructorInfo con)
         {
@@ -686,7 +680,7 @@ namespace System.Reflection.Emit
             if (opcode.StackBehaviourPush == StackBehaviour.Varpush)
             {
                 // Instruction must be one of call or callvirt.
-                Contract.Assert(opcode.Equals(OpCodes.Call) ||
+                Debug.Assert(opcode.Equals(OpCodes.Call) ||
                                 opcode.Equals(OpCodes.Callvirt),
                                 "Unexpected opcode encountered for StackBehaviour of VarPush.");
                 stackchange++;
@@ -694,7 +688,7 @@ namespace System.Reflection.Emit
             if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
             {
                 // Instruction must be one of call, callvirt or newobj.
-                Contract.Assert(opcode.Equals(OpCodes.Call) ||
+                Debug.Assert(opcode.Equals(OpCodes.Call) ||
                                 opcode.Equals(OpCodes.Callvirt) ||
                                 opcode.Equals(OpCodes.Newobj),
                                 "Unexpected opcode encountered for StackBehaviour of VarPop.");
@@ -709,7 +703,6 @@ namespace System.Reflection.Emit
             PutInteger4(tk);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public virtual void Emit(OpCode opcode, Type cls)
         {
             // Puts opcode onto the stream and then the metadata token represented
@@ -749,7 +742,6 @@ namespace System.Reflection.Emit
             m_ILStream[m_length++] = (byte) (arg>>56);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe public virtual void Emit(OpCode opcode, float arg) {
             EnsureCapacity(7);
             InternalEmit(opcode);
@@ -760,7 +752,6 @@ namespace System.Reflection.Emit
             m_ILStream[m_length++] = (byte) (tempVal>>24);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe public virtual void Emit(OpCode opcode, double arg) {
             EnsureCapacity(11);
             InternalEmit(opcode);
@@ -1361,28 +1352,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #endregion
-
-#if !FEATURE_CORECLR
-        void _ILGenerator.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ILGenerator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ILGenerator.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ILGenerator.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 
     internal struct __FixupData
@@ -1471,7 +1440,7 @@ namespace System.Reflection.Emit
                 m_catchAddr[m_currentCatch] = -1;
                 if (m_currentCatch > 0)
                 {
-                    Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
+                    Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
                     m_catchEndAddr[m_currentCatch-1] = catchorfilterAddr;
                 }
             }
@@ -1488,7 +1457,7 @@ namespace System.Reflection.Emit
                 {
                         if (m_type[m_currentCatch] != Filter)
                         {
-                            Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
+                            Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
                             m_catchEndAddr[m_currentCatch-1] = catchEndAddr;
                         }
                 }
@@ -1530,9 +1499,9 @@ namespace System.Reflection.Emit
         }
 
         internal void Done(int endAddr) {
-            Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0");
-            Contract.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0");
-            Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
+            Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0");
+            Debug.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0");
+            Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
             m_catchEndAddr[m_currentCatch-1] = endAddr;
             m_currentState = State_Done;
         }
@@ -1595,8 +1564,8 @@ namespace System.Reflection.Emit
         // not having a nesting relation. 
         internal bool IsInner(__ExceptionInfo exc) {
             Contract.Requires(exc != null);
-            Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0");
-            Contract.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0");
+            Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0");
+            Debug.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0");
 
             int exclast = exc.m_currentCatch - 1;
             int last = m_currentCatch - 1;
@@ -1605,7 +1574,7 @@ namespace System.Reflection.Emit
                 return true;
             else if (exc.m_catchEndAddr[exclast] == m_catchEndAddr[last])
             {
-                Contract.Assert(exc.GetEndAddress() != GetEndAddress(),
+                Debug.Assert(exc.GetEndAddress() != GetEndAddress(),
                                 "exc.GetEndAddress() != GetEndAddress()");
                 if (exc.GetEndAddress() > GetEndAddress())
                     return true;
@@ -1761,9 +1730,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         internal void EmitScopeTree(ISymbolWriter symWriter)
         {
             int         i;
@@ -1820,7 +1786,7 @@ namespace System.Reflection.Emit
             // make sure that arrays are large enough to hold addition info
             i = FindDocument(document);
             
-            Contract.Assert(i < m_DocumentCount, "Bad document look up!");
+            Debug.Assert(i < m_DocumentCount, "Bad document look up!");
             m_Documents[i].AddLineNumberInfo(document, iOffset, iStartLine, iStartColumn, iEndLine, iEndColumn);
         }
         
@@ -1873,9 +1839,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         internal void EmitLineNumberInfo(ISymbolWriter symWriter)
         {
             for (int i = 0; i < m_DocumentCount; i++)
@@ -1911,7 +1874,7 @@ namespace System.Reflection.Emit
             int             iEndLine,
             int             iEndColumn)
         {
-            Contract.Assert(document == m_document, "Bad document look up!");
+            Debug.Assert(document == m_document, "Bad document look up!");
             
             // make sure that arrays are large enough to hold addition info
             EnsureCapacity();
@@ -1967,9 +1930,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         internal void EmitLineNumberInfo(ISymbolWriter symWriter)
         {
             int[]       iOffsetsTemp;
index 00fdd00..a737895 100644 (file)
@@ -2,10 +2,6 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
-// 
-
-#if FEATURE_CORECLR
-
 namespace System.Reflection.Emit
 {
     using System;
@@ -14,7 +10,6 @@ namespace System.Reflection.Emit
     using System.Runtime.CompilerServices;
     using System.Diagnostics.SymbolStore;
 
-
     //-----------------------------------------------------------------------------------
     // On Telesto, we don't ship the ISymWrapper.dll assembly. However, ReflectionEmit
     // relies on that assembly to write out managed PDBs.
@@ -58,9 +53,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // Ctor
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             internal SymDocumentWriter(PunkSafeHandle pDocumentWriterSafeHandle)
             {
                 m_pDocumentWriterSafeHandle = pDocumentWriterSafeHandle;
@@ -72,9 +64,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // Returns the underlying ISymUnmanagedDocumentWriter* (as a safehandle.)
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             internal PunkSafeHandle GetUnmanaged()
             {
                 return m_pDocumentWriterSafeHandle;
@@ -97,9 +86,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // SetCheckSum() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecuritySafeCritical]
-            #endif
             void ISymbolDocumentWriter.SetCheckSum(Guid algorithmId, byte [] checkSum)
             {
                 int hr = m_vtable.SetCheckSum(m_pDocWriter, algorithmId, (uint)checkSum.Length, checkSum);
@@ -109,7 +95,6 @@ namespace System.Reflection.Emit
                 }
             }
     
-            [System.Security.SecurityCritical]
             private delegate int DSetCheckSum(ISymUnmanagedDocumentWriter * pThis, Guid algorithmId, uint checkSumSize, [In] byte[] checkSum);
 
             //------------------------------------------------------------------------------
@@ -117,7 +102,6 @@ namespace System.Reflection.Emit
             // exactly. If a member is declared as an IntPtr rather than a delegate, it means
             // we don't call that particular member.
             //------------------------------------------------------------------------------
-            [System.Security.SecurityCritical]
             [StructLayout(LayoutKind.Sequential)]
             private struct ISymUnmanagedDocumentWriterVTable
             {
@@ -126,9 +110,6 @@ namespace System.Reflection.Emit
                 internal IntPtr                Release;
 
                 internal IntPtr                SetSource;
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical]
-                #endif
                 internal DSetCheckSum          SetCheckSum;
             }
     
@@ -136,7 +117,6 @@ namespace System.Reflection.Emit
             // This layout must match the (start) of the unmanaged ISymUnmanagedDocumentWriter
             // COM object.
             //------------------------------------------------------------------------------
-            [System.Security.SecurityCritical]
             [StructLayout(LayoutKind.Sequential)]
             private struct ISymUnmanagedDocumentWriter
             {
@@ -146,19 +126,14 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // Stores underlying ISymUnmanagedDocumentWriter* pointer (wrapped in a safehandle.)
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             private PunkSafeHandle m_pDocumentWriterSafeHandle;
 
-            [SecurityCritical]
             private ISymUnmanagedDocumentWriter * m_pDocWriter;
 
             //------------------------------------------------------------------------------
             // Stores the "managed vtable" (actually a structure full of delegates that
             // P/Invoke to the corresponding unmanaged COM methods.)
             //------------------------------------------------------------------------------
-            [SecurityCritical]
             private ISymUnmanagedDocumentWriterVTable m_vtable;
 
     
@@ -212,9 +187,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // DefineDocument() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             ISymbolDocumentWriter ISymbolWriter.DefineDocument(String url,
                                                                Guid language,
                                                                Guid languageVendor,
@@ -237,9 +209,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // SetUserEntryPoint() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             void ISymbolWriter.SetUserEntryPoint(SymbolToken entryMethod)
             {
                 int hr = m_vtable.SetUserEntryPoint(m_pWriter, entryMethod.GetToken());
@@ -252,9 +221,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // OpenMethod() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             void ISymbolWriter.OpenMethod(SymbolToken method)
             {
                 int hr = m_vtable.OpenMethod(m_pWriter, method.GetToken());
@@ -267,9 +233,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // CloseMethod() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             void ISymbolWriter.CloseMethod()
             {
                 int hr = m_vtable.CloseMethod(m_pWriter);
@@ -282,9 +245,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // DefineSequencePoints() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             void ISymbolWriter.DefineSequencePoints(ISymbolDocumentWriter document,
                                                     int[] offsets,
                                                     int[] lines,
@@ -344,9 +304,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // OpenScope() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             int ISymbolWriter.OpenScope(int startOffset)
             {
                 int ret;
@@ -361,9 +318,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // CloseScope() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             void ISymbolWriter.CloseScope(int endOffset)
             {
                 int hr = m_vtable.CloseScope(m_pWriter, endOffset);
@@ -388,9 +342,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // DefineLocalVariable() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             void ISymbolWriter.DefineLocalVariable(String name,
                                                    FieldAttributes attributes,
                                                    byte[] signature,
@@ -476,9 +427,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // SetSymAttribute() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             void ISymbolWriter.SetSymAttribute(SymbolToken parent, String name, byte[] data)
             {
                 int hr = m_vtable.SetSymAttribute(m_pWriter, parent.GetToken(), name, data.Length, data);
@@ -515,9 +463,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // UsingNamespace() wrapper
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             void ISymbolWriter.UsingNamespace(String name)
             {
                 int hr = m_vtable.UsingNamespace(m_pWriter, name);
@@ -557,9 +502,6 @@ namespace System.Reflection.Emit
             // with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on pointers
             // furnished through SetUnderlyingWriter. Lifetime management is entirely up to the caller.
             //------------------------------------------------------------------------------
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
             internal void InternalSetUnderlyingWriter(IntPtr ppUnderlyingWriter)
             {
                 m_pWriter = *((ISymUnmanagedWriter**)ppUnderlyingWriter);
@@ -569,7 +511,6 @@ namespace System.Reflection.Emit
             //------------------------------------------------------------------------------
             // Define delegates for the unmanaged COM methods we invoke.
             //------------------------------------------------------------------------------
-            [System.Security.SecurityCritical]
             private delegate int DInitialize(ISymUnmanagedWriter*                     pthis,
                                              IntPtr                                   emitter,  //IUnknown*
                                              [MarshalAs(UnmanagedType.LPWStr)] String filename, //WCHAR*
@@ -577,7 +518,6 @@ namespace System.Reflection.Emit
                                              [MarshalAs(UnmanagedType.Bool)] bool     fFullBuild
                                              );
 
-            [System.Security.SecurityCritical]
             private delegate int DDefineDocument(ISymUnmanagedWriter*                     pthis,
                                                  [MarshalAs(UnmanagedType.LPWStr)] String url,
                                                  [In] ref Guid                            language,
@@ -586,14 +526,10 @@ namespace System.Reflection.Emit
                                                  [Out] out PunkSafeHandle                 ppsymUnmanagedDocumentWriter
                                                 );
                                                                               
-            [System.Security.SecurityCritical]
             private delegate int DSetUserEntryPoint(ISymUnmanagedWriter* pthis, int entryMethod);
-            [System.Security.SecurityCritical]
             private delegate int DOpenMethod(ISymUnmanagedWriter* pthis, int entryMethod);
-            [System.Security.SecurityCritical]
             private delegate int DCloseMethod(ISymUnmanagedWriter* pthis);
 
-            [System.Security.SecurityCritical]
             private delegate int DDefineSequencePoints(ISymUnmanagedWriter* pthis,
                                                        PunkSafeHandle       document,
                                                        int                  spCount,
@@ -603,15 +539,11 @@ namespace System.Reflection.Emit
                                                        [In] int[]           endLines,
                                                        [In] int[]           endColumns);
 
-            [System.Security.SecurityCritical]
             private delegate int DOpenScope(ISymUnmanagedWriter* pthis, int startOffset, [Out] out int pretval);
-            [System.Security.SecurityCritical]
             private delegate int DCloseScope(ISymUnmanagedWriter* pthis, int endOffset);
 
-            [System.Security.SecurityCritical]
             private delegate int DSetScopeRange(ISymUnmanagedWriter* pthis, int scopeID, int startOffset, int endOffset);
 
-            [System.Security.SecurityCritical]
             private delegate int DDefineLocalVariable(ISymUnmanagedWriter*                     pthis,
                                                       [MarshalAs(UnmanagedType.LPWStr)] String name,
                                                       int                                      attributes,
@@ -625,10 +557,8 @@ namespace System.Reflection.Emit
                                                       int                                      endOffset
                                                      );
 
-            [System.Security.SecurityCritical]
             private delegate int DClose(ISymUnmanagedWriter* pthis);
 
-            [System.Security.SecurityCritical]
             private delegate int DSetSymAttribute(ISymUnmanagedWriter*                     pthis,
                                                   int                                      parent,
                                                   [MarshalAs(UnmanagedType.LPWStr)] String name,
@@ -637,11 +567,8 @@ namespace System.Reflection.Emit
                                                  );
 
 
-            [System.Security.SecurityCritical]
             private delegate int DOpenNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name);
-            [System.Security.SecurityCritical]
             private delegate int DCloseNamespace(ISymUnmanagedWriter* pthis);
-            [System.Security.SecurityCritical]
             private delegate int DUsingNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name);
 
 
@@ -658,77 +585,32 @@ namespace System.Reflection.Emit
                 internal IntPtr                AddRef;
                 internal IntPtr                Release;
 
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DDefineDocument       DefineDocument;
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DSetUserEntryPoint    SetUserEntryPoint;
 
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DOpenMethod           OpenMethod;
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DCloseMethod          CloseMethod;
 
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DOpenScope            OpenScope;
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DCloseScope           CloseScope;
 
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DSetScopeRange        SetScopeRange;
 
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DDefineLocalVariable  DefineLocalVariable;
                 internal IntPtr                DefineParameter;
                 internal IntPtr                DefineField;
                 internal IntPtr                DefineGlobalVariable;
 
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DClose                Close;
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DSetSymAttribute      SetSymAttribute;
 
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DOpenNamespace        OpenNamespace;
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DCloseNamespace       CloseNamespace;
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DUsingNamespace       UsingNamespace;
 
                 internal IntPtr                SetMethodSourceRange;
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DInitialize           Initialize;
                 internal IntPtr                GetDebugInfo;
-                #if FEATURE_CORECLR
-                [System.Security.SecurityCritical] // auto-generated
-                #endif
                 internal DDefineSequencePoints DefineSequencePoints;
         
             }
@@ -749,7 +631,6 @@ namespace System.Reflection.Emit
             // As with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on this pointer.
             // Managing lifetime is up to the caller (coreclr.dll).
             //------------------------------------------------------------------------------
-            [SecurityCritical]
             private ISymUnmanagedWriter      *m_pWriter;
 
             //------------------------------------------------------------------------------
@@ -778,20 +659,13 @@ namespace System.Reflection.Emit
     //
     // Had to make this a non-nested class since FCall's don't like to bind to nested classes.
     //--------------------------------------------------------------------------------------
-    #if FEATURE_CORECLR
-    [System.Security.SecurityCritical] // auto-generated
-    #endif
     sealed class PunkSafeHandle : SafeHandle
     {
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         internal PunkSafeHandle()
             : base((IntPtr)0, true)
         {
         }
 
-        [SecurityCritical]
         override protected bool ReleaseHandle()
         {
             m_Release(handle);
@@ -800,7 +674,6 @@ namespace System.Reflection.Emit
 
         public override bool IsInvalid
         {
-            [SecurityCritical]
             get { return handle == ((IntPtr)0); }
         }
 
@@ -810,19 +683,10 @@ namespace System.Reflection.Emit
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern IntPtr nGetDReleaseTarget();     // FCall gets us the native DRelease target (so we don't need named dllexport from coreclr.dll)
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         static PunkSafeHandle()
         {
             m_Release = (DRelease)(Marshal.GetDelegateForFunctionPointer(nGetDReleaseTarget(), typeof(DRelease)));
             m_Release((IntPtr)0); // make one call to make sure the delegate is fully prepped before we're in the critical finalizer situation.
         }
-
     } // PunkSafeHandle
-
 } //namespace System.Reflection.Emit
-
-
-#endif //FEATURE_CORECLR
-
index 4008703..a34d5eb 100644 (file)
@@ -124,28 +124,6 @@ namespace System.Reflection.Emit
             }
         }
         #endregion
-
-#if !FEATURE_CORECLR
-        void _LocalBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _LocalBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _LocalBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _LocalBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 }
 
index a060098..654e166 100644 (file)
@@ -16,12 +16,12 @@ namespace System.Reflection.Emit
     using System.Collections.Generic;
     using System.Security.Permissions;
     using System.Runtime.InteropServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_MethodBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class MethodBuilder : MethodInfo, _MethodBuilder
     {
         #region Private Data Members
@@ -196,7 +196,6 @@ namespace System.Reflection.Emit
             m_module.CheckContext(types);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void CreateMethodBodyHelper(ILGenerator il)
         {
             // Sets the IL of the method.  An ILGenerator is passed as an argument and the method
@@ -367,7 +366,7 @@ namespace System.Reflection.Emit
             }
             else
             {
-                Contract.Assert(false, "We should never get here!");
+                Debug.Assert(false, "We should never get here!");
                 return null;
             }
         }
@@ -389,7 +388,6 @@ namespace System.Reflection.Emit
             return m_mdMethodFixups;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal SignatureHelper GetMethodSignature()
         {
             if (m_parameterTypes == null)
@@ -480,7 +478,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Object Overrides
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool Equals(Object obj) {
             if (!(obj is MethodBuilder)) {
                 return false;
@@ -505,7 +502,6 @@ namespace System.Reflection.Emit
             return this.m_strName.GetHashCode();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString()
         {
             StringBuilder sb = new StringBuilder(1000);
@@ -599,29 +595,17 @@ namespace System.Reflection.Emit
 
         public override bool IsSecurityCritical
         {
-#if FEATURE_CORECLR
             get { return true; }
-#else
-            get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
-#endif
         }
 
         public override bool IsSecuritySafeCritical
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
-#endif
         }
 
         public override bool IsSecurityTransparent
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
-#endif
         }
         #endregion
 
@@ -733,7 +717,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Public Members
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public MethodToken GetToken()
         {
             // We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498
@@ -779,16 +762,15 @@ namespace System.Reflection.Emit
                 m_containingType.m_lastTokenizedMethod = i;
             }
 
-            Contract.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
-            Contract.Assert(currentToken.Token != 0, "The token should not be 0");
+            Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
+            Debug.Assert(currentToken.Token != 0, "The token should not be 0");
 
             return currentToken;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private MethodToken GetTokenNoLock()
         {
-            Contract.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
+            Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
 
             int sigLength;
             byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength);
@@ -853,7 +835,6 @@ namespace System.Reflection.Emit
         }
 
        
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName)
         {
             if (position < 0)
@@ -870,7 +851,6 @@ namespace System.Reflection.Emit
             return new ParameterBuilder(this, position, attributes, strParamName);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
         public void SetMarshal(UnmanagedMarshal unmanagedMarshal)
         {
@@ -927,46 +907,6 @@ namespace System.Reflection.Emit
             m_symCustomAttrs.Add(new SymCustomAttr(name, data));
         }
 
-#if FEATURE_CAS_POLICY
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
-        {
-            if (pset == null)
-                throw new ArgumentNullException(nameof(pset));
-            Contract.EndContractBlock();
-
-            ThrowIfGeneric ();
-
-#pragma warning disable 618
-            if (!Enum.IsDefined(typeof(SecurityAction), action) ||
-                action == SecurityAction.RequestMinimum ||
-                action == SecurityAction.RequestOptional ||
-                action == SecurityAction.RequestRefuse)
-            {
-                throw new ArgumentOutOfRangeException(nameof(action));
-            }
-#pragma warning restore 618
-
-            // cannot declarative security after type is created
-            m_containingType.ThrowIfCreated();
-
-            // Translate permission set into serialized format (uses standard binary serialization format).
-            byte[] blob = null;
-            int length = 0;
-            if (!pset.IsEmpty())
-            {
-                blob = pset.EncodeXml();
-                length = blob.Length;
-            }
-
-            // Write the blob into the metadata.
-            TypeBuilder.AddDeclarativeSecurity(m_module.GetNativeHandle(), MetadataTokenInternal, action, blob, length);
-        }
-#endif // FEATURE_CAS_POLICY
-
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
         {
             if (il == null)
@@ -1068,9 +1008,6 @@ namespace System.Reflection.Emit
         /// <summary>
         /// Obsolete.
         /// </summary>
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public void CreateMethodBody(byte[] il, int count)
         {
             ThrowIfGeneric();
@@ -1107,7 +1044,6 @@ namespace System.Reflection.Emit
             m_bIsBaked = true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetImplementationFlags(MethodImplAttributes attributes) 
         {
             ThrowIfGeneric ();
@@ -1170,7 +1106,6 @@ namespace System.Reflection.Emit
 
         public String Signature 
         { 
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get 
             { 
                 return GetMethodSignature().ToString(); 
@@ -1178,11 +1113,6 @@ namespace System.Reflection.Emit
         }
 
 
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#else
-[System.Security.SecuritySafeCritical]
-#endif
 [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -1203,7 +1133,6 @@ namespace System.Reflection.Emit
                 ParseCA(con, binaryAttribute);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
         {
             if (customBuilder == null)
@@ -1251,29 +1180,6 @@ namespace System.Reflection.Emit
         internal bool m_isDllImport = false;
 
         #endregion
-
-#if !FEATURE_CORECLR
-        void _MethodBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MethodBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MethodBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
     }
 
     internal class LocalSymInfo
@@ -1378,9 +1284,6 @@ namespace System.Reflection.Emit
             checked { m_iNameSpaceCount++; }
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter)
         {
             int         i;
@@ -1539,13 +1442,13 @@ namespace System.Reflection.Emit
         internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
             int kind, int exceptionTypeToken)
         {
-            Contract.Assert(tryStartOffset >= 0);
-            Contract.Assert(tryEndOffset >= 0);
-            Contract.Assert(filterOffset >= 0);
-            Contract.Assert(handlerStartOffset >= 0);
-            Contract.Assert(handlerEndOffset >= 0);
-            Contract.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
-            Contract.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
+            Debug.Assert(tryStartOffset >= 0);
+            Debug.Assert(tryEndOffset >= 0);
+            Debug.Assert(filterOffset >= 0);
+            Debug.Assert(handlerStartOffset >= 0);
+            Debug.Assert(handlerEndOffset >= 0);
+            Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
+            Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
 
             m_tryStartOffset = tryStartOffset;
             m_tryEndOffset = tryEndOffset;
index c474b70..6884f50 100644 (file)
@@ -12,7 +12,6 @@ namespace System.Reflection.Emit
     using System.Diagnostics.SymbolStore;
     using System.Globalization;
     using System.Reflection;
-    using System.Diagnostics;
     using System.IO;
     using System.Resources;
     using System.Security;
@@ -22,6 +21,7 @@ namespace System.Reflection.Emit
     using System.Threading;
     using System.Runtime.Versioning;
     using System.Runtime.CompilerServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     internal sealed class InternalModuleBuilder : RuntimeModule
@@ -50,7 +50,6 @@ namespace System.Reflection.Emit
     }
 
     // deliberately not [serializable]
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_ModuleBuilder))]
     [System.Runtime.InteropServices.ComVisible(true)]
@@ -97,9 +96,6 @@ namespace System.Reflection.Emit
         private Dictionary<string, Type> m_TypeBuilderDict;
         private ISymbolWriter m_iSymWriter;
         internal ModuleBuilderData m_moduleData;
-#if !FEATURE_CORECLR
-        private MethodToken m_EntryPoint;
-#endif //!FEATURE_CORECLR
         internal InternalModuleBuilder m_internalModuleBuilder;
         // This is the "external" AssemblyBuilder
         // only the "external" ModuleBuilder has this set
@@ -157,42 +153,35 @@ namespace System.Reflection.Emit
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static int GetTypeRef(RuntimeModule module, String strFullName, RuntimeModule refedModule, String strRefedModuleFileName, int tkResolution);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static int GetMemberRef(RuntimeModule module, RuntimeModule refedModule, int tr, int defToken);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetMemberRef(Module refedModule, int tr, int defToken)
         {
             return GetMemberRef(GetNativeHandle(), GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), tr, defToken);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static int GetMemberRefFromSignature(RuntimeModule module, int tr, String methodName, byte[] signature, int length);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetMemberRefFromSignature(int tr, String methodName, byte[] signature, int length)
         {
             return GetMemberRefFromSignature(GetNativeHandle(), tr, methodName, signature, length);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static int GetMemberRefOfMethodInfo(RuntimeModule module, int tr, IRuntimeMethodInfo method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method)
         {
-            Contract.Assert(method != null);
+            Debug.Assert(method != null);
 
 #if FEATURE_APPX
             if (ContainingAssemblyBuilder.ProfileAPICheck)
@@ -205,10 +194,9 @@ namespace System.Reflection.Emit
             return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method)
         {
-            Contract.Assert(method != null);
+            Debug.Assert(method != null);
 
 #if FEATURE_APPX
             if (ContainingAssemblyBuilder.ProfileAPICheck)
@@ -221,15 +209,13 @@ namespace System.Reflection.Emit
             return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static int GetMemberRefOfFieldInfo(RuntimeModule module, int tkType, RuntimeTypeHandle declaringType, int tkField);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField)
         {
-            Contract.Assert(runtimeField != null);
+            Debug.Assert(runtimeField != null);
 
 #if FEATURE_APPX
             if (ContainingAssemblyBuilder.ProfileAPICheck)
@@ -243,38 +229,31 @@ namespace System.Reflection.Emit
             return GetMemberRefOfFieldInfo(GetNativeHandle(), tkType, declaringType, runtimeField.MetadataToken);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static int GetTokenFromTypeSpec(RuntimeModule pModule, byte[] signature, int length);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetTokenFromTypeSpec(byte[] signature, int length)
         {
             return GetTokenFromTypeSpec(GetNativeHandle(), signature, length);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static int GetArrayMethodToken(RuntimeModule module, int tkTypeSpec, String methodName, byte[] signature, int sigLength);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static int GetStringConstant(RuntimeModule module, String str, int length);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void PreSavePEFile(RuntimeModule module, int portableExecutableKind, int imageFileMachine);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void SavePEFile(RuntimeModule module, String fileName, int entryPoint, int isExe, bool isManifestFile);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void AddResource(
@@ -282,17 +261,14 @@ namespace System.Reflection.Emit
             byte[] resBytes, int resByteCount, int tkFile, int attribute,
             int portableExecutableKind, int imageFileMachine);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void SetModuleName(RuntimeModule module, String strModuleName);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal extern static void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[] data, int length);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void DefineNativeResourceFile(RuntimeModule module, 
@@ -300,7 +276,6 @@ namespace System.Reflection.Emit
                                                             int portableExecutableKind, 
                                                             int ImageFileMachine);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void DefineNativeResourceBytes(RuntimeModule module,
@@ -308,7 +283,6 @@ namespace System.Reflection.Emit
                                                              int portableExecutableKind, 
                                                              int imageFileMachine);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void DefineNativeResource(PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
         {
             string strResourceFileName = m_moduleData.m_strResourceFileName;
@@ -351,105 +325,7 @@ namespace System.Reflection.Emit
 
             return null;
         }
-        
-#if !FEATURE_CORECLR
-        internal void SetEntryPoint(MethodToken entryPoint)
-        {           
-            // Sets the entry point of the module to be a given method.  If no entry point
-            // is specified, calling EmitPEFile will generate a dll.
-            // AssemblyBuilder.SetEntryPoint has already demanded required permission
-            m_EntryPoint = entryPoint;
-        }
-#endif //!FEATURE_CORECLR
-
-
-#if !FEATURE_CORECLR
-        // This is a helper called by AssemblyBuilder save to presave information for the persistable modules.
-        // no need to lock here because we have already taken the lock in AssemblyBuilder.Save
-        [System.Security.SecurityCritical]  // auto-generated
-        internal void PreSave(String fileName,
-            PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
-        {
-            if (m_moduleData.m_isSaved == true)
-            {
-                // can only save once
-                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
-                    Environment.GetResourceString("InvalidOperation_ModuleHasBeenSaved"),
-                    m_moduleData.m_strModuleName));
-            }
-        
-            if (m_moduleData.m_fGlobalBeenCreated == false && m_moduleData.m_fHasGlobal == true)
-                throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalFunctionNotBaked")); 
 
-            TypeBuilder typeBuilder;
-            foreach (Type item in m_TypeBuilderDict.Values)
-            {
-                if (item is TypeBuilder)
-                {
-                    typeBuilder = (TypeBuilder)item;
-                }
-                else
-                {
-                    EnumBuilder enumBuilder = (EnumBuilder)item;
-                    typeBuilder = enumBuilder.m_typeBuilder;
-                }
-
-                if (!typeBuilder.IsCreated())
-                {
-                    // cannot save to PE file without creating all of the types first 
-                    throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture,
-                        Environment.GetResourceString("NotSupported_NotAllTypesAreBaked"), 
-                        typeBuilder.FullName)); 
-                }
-            }
-
-            PreSavePEFile(GetNativeHandle(), (int)portableExecutableKind, (int)imageFileMachine);
-        }
-
-        // no need to lock here because we have already taken the lock in AssemblyBuilder.Save
-        [System.Security.SecurityCritical]  // auto-generated
-        internal void Save(String fileName, bool isAssemblyFile, PortableExecutableKinds portableExecutableKind, 
-            ImageFileMachine imageFileMachine)
-        {
-            // This is a helper called by AssemblyBuilder save to save information for the persistable modules.
-            if (m_moduleData.m_embeddedRes != null)
-            {
-                // There are embedded resources for this module
-                ResWriterData   resWriter;
-
-                // Add each resource content into the to be saved PE file
-                for (resWriter = m_moduleData.m_embeddedRes; resWriter != null; resWriter = resWriter.m_nextResWriter)
-                {
-                    if (resWriter.m_resWriter != null)
-                        resWriter.m_resWriter.Generate();                    
-                    
-                    byte[] resBytes = new byte[resWriter.m_memoryStream.Length];
-                    resWriter.m_memoryStream.Flush();
-                    resWriter.m_memoryStream.Position = 0;
-                    resWriter.m_memoryStream.Read(resBytes, 0, resBytes.Length);
-
-                    AddResource(GetNativeHandle(),
-                                resWriter.m_strName, 
-                                resBytes,
-                                resBytes.Length,
-                                m_moduleData.FileToken,
-                                (int)resWriter.m_attribute, 
-                                (int)portableExecutableKind,
-                                (int)imageFileMachine);
-                }
-            }
-
-            DefineNativeResource(portableExecutableKind, imageFileMachine);
-
-            PEFileKinds pekind = isAssemblyFile ? ContainingAssemblyBuilder.m_assemblyData.m_peFileKind : PEFileKinds.Dll;
-
-            SavePEFile(GetNativeHandle(), fileName, m_EntryPoint.Token, (int)pekind, isAssemblyFile); 
-
-            m_moduleData.m_isSaved = true;
-        }
-#endif // !FEATURE_CORECLR
-
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetTypeRefNested(Type type, Module refedModule, String strRefedModuleFileName)
         {
             // This function will generate correct TypeRef token for top level type and nested type.
@@ -464,8 +340,8 @@ namespace System.Reflection.Emit
                 typeName = UnmangleTypeName(typeName);
             }
 
-            Contract.Assert(!type.IsByRef, "Must not be ByRef.");
-            Contract.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");
+            Debug.Assert(!type.IsByRef, "Must not be ByRef.");
+            Debug.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");
 
 #if FEATURE_APPX
             if (ContainingAssemblyBuilder.ProfileAPICheck)
@@ -481,7 +357,6 @@ namespace System.Reflection.Emit
             return GetTypeRef(GetNativeHandle(), typeName, GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), strRefedModuleFileName, tkResolution);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal MethodToken InternalGetConstructorToken(ConstructorInfo con, bool usingRef)
         {
             // Helper to get constructor token. If usingRef is true, we will never use the def token
@@ -556,7 +431,6 @@ namespace System.Reflection.Emit
             return new MethodToken( mr );
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void Init(String strModuleName, String strFileName, int tkFile)
         {
             m_moduleData = new ModuleBuilderData(this, strModuleName, strFileName, tkFile);
@@ -565,7 +439,6 @@ namespace System.Reflection.Emit
 
         // This is a method for changing module and file name of the manifest module (created by default for 
         // each assembly).
-        [System.Security.SecurityCritical]  // auto-generated
         internal void ModifyModuleName(string name)
         {
             // Reset the names in the managed ModuleBuilderData
@@ -622,7 +495,6 @@ namespace System.Reflection.Emit
             return m as RuntimeModule;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private int GetMemberRefToken(MethodBase method, IEnumerable<Type> optionalParameterTypes)
         {
             Type[] parameterTypes;
@@ -671,11 +543,11 @@ namespace System.Reflection.Emit
                 }
                 else
                 {
-                    Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
+                    Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
 
                     if (method.IsGenericMethod)
                     {
-                        Contract.Assert(masmi != null);
+                        Debug.Assert(masmi != null);
 
                         methDef = masmi.GetGenericMethodDefinition();
                         methDef = methDef.Module.ResolveMethod(
@@ -728,7 +600,6 @@ namespace System.Reflection.Emit
             return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
             Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters) 
         {
@@ -949,11 +820,6 @@ namespace System.Reflection.Emit
 
         public override String FullyQualifiedName
         {
-#if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-#else
-            [System.Security.SecuritySafeCritical]
-#endif
             get
             {
                 String fullyQualifiedName = m_moduleData.m_strFileName;
@@ -1085,18 +951,11 @@ namespace System.Reflection.Emit
             }
         }
 
-#if FEATURE_X509 && FEATURE_CAS_POLICY
-        public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
-        {
-            return InternalModule.GetSignerCertificate();
-        }
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
         #endregion
 
         #region Public Members
 
         #region Define Type
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public TypeBuilder DefineType(String name)
         {
             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
@@ -1107,7 +966,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public TypeBuilder DefineType(String name, TypeAttributes attr)
         {
             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
@@ -1118,7 +976,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent)
         {
             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
@@ -1132,11 +989,6 @@ namespace System.Reflection.Emit
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, int typesize)
         {
             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
@@ -1147,11 +999,6 @@ namespace System.Reflection.Emit
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize)
         {
             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
@@ -1162,7 +1009,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
         {
@@ -1174,7 +1020,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize)
         {
             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
@@ -1182,11 +1027,6 @@ namespace System.Reflection.Emit
             return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); ;
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packsize)
         {
             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
@@ -1197,7 +1037,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, PackingSize packsize)
         {
             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
@@ -1211,7 +1050,6 @@ namespace System.Reflection.Emit
 
         // This API can only be used to construct a top-level (not nested) enum type.
         // Nested enum types can be defined manually using ModuleBuilder.DefineType.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public EnumBuilder DefineEnum(String name, TypeAttributes visibility, Type underlyingType)
         {
             Contract.Ensures(Contract.Result<EnumBuilder>() != null);
@@ -1222,17 +1060,16 @@ namespace System.Reflection.Emit
                 EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType);
 
                 // This enum is not generic, nested, and cannot have any element type.
-                Contract.Assert(name == enumBuilder.FullName);
+                Debug.Assert(name == enumBuilder.FullName);
 
                 // Replace the TypeBuilder object in m_TypeBuilderDict with this EnumBuilder object.
-                Contract.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
+                Debug.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
                 m_TypeBuilderDict[name] = enumBuilder;
 
                 return enumBuilder;
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private EnumBuilder DefineEnumNoLock(String name, TypeAttributes visibility, Type underlyingType)
         {
             Contract.Ensures(Contract.Result<EnumBuilder>() != null);
@@ -1243,166 +1080,7 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Define Resource
-#if !FEATURE_CORECLR
-        public IResourceWriter DefineResource(String name, String description)
-        {
-            // Define embedded managed resource to be stored in this module
-            Contract.Ensures(Contract.Result<IResourceWriter>() != null);
-             
-            return DefineResource(name, description, ResourceAttributes.Public);
-        }
-
-        public IResourceWriter DefineResource(String name, String description, ResourceAttributes attribute)
-        {
-            // Define embedded managed resource to be stored in this module
-            Contract.Ensures(Contract.Result<IResourceWriter>() != null);
-
-            lock(SyncRoot)
-            {
-                return DefineResourceNoLock(name, description, attribute);
-            }
-        }
-
-        private IResourceWriter DefineResourceNoLock(String name, String description, ResourceAttributes attribute)
-        {
-            // Define embedded managed resource to be stored in this module
-
-            if (IsTransient())
-                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
-
-            if (name == null)
-                throw new ArgumentNullException(nameof(name));
-            if (name.Length == 0)
-                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
-            Contract.Ensures(Contract.Result<IResourceWriter>() != null);
-            Contract.EndContractBlock();
-
-            if (m_assemblyBuilder.IsPersistable())
-            {
-                m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name);
-
-                    MemoryStream stream = new MemoryStream();
-                    ResourceWriter resWriter = new ResourceWriter(stream);
-                    ResWriterData resWriterData = new ResWriterData( resWriter, stream, name, String.Empty, String.Empty, attribute);
-
-                // chain it to the embedded resource list
-                resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes;
-                m_moduleData.m_embeddedRes = resWriterData;
-                return resWriter;
-            }
-            else
-            {
-                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
-            }
-        }
-
-        public void DefineManifestResource(String name, Stream stream, ResourceAttributes attribute)
-        {
-            if (name == null)
-                throw new ArgumentNullException(nameof(name));
-            
-            if (stream == null)
-                throw new ArgumentNullException(nameof(stream));
-            Contract.EndContractBlock();
-
-            // Define embedded managed resource to be stored in this module
 
-            lock(SyncRoot)
-            {
-                DefineManifestResourceNoLock(name, stream, attribute);
-            }
-        }
-
-        private void DefineManifestResourceNoLock(String name, Stream stream, ResourceAttributes attribute)
-        {
-            // Define embedded managed resource to be stored in this module
-           if (IsTransient())
-                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
-           Contract.EndContractBlock();
-
-            if (name == null)
-                throw new ArgumentNullException(nameof(name));
-            if (name.Length == 0)
-                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
-        
-            if (m_assemblyBuilder.IsPersistable())
-            {
-                m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name);
-
-                ResWriterData resWriterData = new ResWriterData( null, stream, name, String.Empty, String.Empty, attribute);
-    
-                // chain it to the embedded resource list
-                resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes;
-                m_moduleData.m_embeddedRes = resWriterData;
-            }
-            else
-            { 
-                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
-            }
-        }
-
-
-        public void DefineUnmanagedResource(Byte[] resource)
-        {
-            lock(SyncRoot)
-            {
-                DefineUnmanagedResourceInternalNoLock(resource);
-            }
-        }
-
-        internal void DefineUnmanagedResourceInternalNoLock(Byte[] resource)
-        {
-            if (resource == null)
-                throw new ArgumentNullException(nameof(resource));
-            Contract.EndContractBlock();
-
-            if (m_moduleData.m_strResourceFileName != null || m_moduleData.m_resourceBytes != null)
-                throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-                        
-            m_moduleData.m_resourceBytes = new byte[resource.Length];
-            Buffer.BlockCopy(resource, 0, m_moduleData.m_resourceBytes, 0, resource.Length);
-        }
-
-        [System.Security.SecuritySafeCritical]
-        public void DefineUnmanagedResource(String resourceFileName)
-        {
-            lock(SyncRoot)
-            {
-                DefineUnmanagedResourceFileInternalNoLock(resourceFileName);
-            }
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal void DefineUnmanagedResourceFileInternalNoLock(String resourceFileName)
-        {
-            if (resourceFileName == null)
-                throw new ArgumentNullException(nameof(resourceFileName));
-            Contract.EndContractBlock();
-
-            if (m_moduleData.m_resourceBytes != null || m_moduleData.m_strResourceFileName != null)
-                throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-
-            // Check caller has the right to read the file.
-            string strFullFileName;
-            strFullFileName = Path.UnsafeGetFullPath(resourceFileName);
-            new FileIOPermission(FileIOPermissionAccess.Read, strFullFileName).Demand();
-
-            new EnvironmentPermission(PermissionState.Unrestricted).Assert();
-            try
-            {
-                if (File.UnsafeExists(resourceFileName) == false)
-                    throw new FileNotFoundException(Environment.GetResourceString(
-                        "IO.FileNotFound_FileName",
-                        resourceFileName), resourceFileName);
-            }
-            finally
-            {
-                CodeAccessPermission.RevertAssert();
-            }
-
-            m_moduleData.m_strResourceFileName = strFullFileName;
-        }
-#endif // !FEATURE_CORECLR
         #endregion
 
         #region Define Global Method
@@ -1463,9 +1141,6 @@ namespace System.Reflection.Emit
                 parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
         }
         
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes, 
             CallingConventions callingConvention, Type returnType, Type[] parameterTypes, 
             CallingConvention nativeCallConv, CharSet nativeCharSet)
@@ -1475,9 +1150,6 @@ namespace System.Reflection.Emit
             return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, 
             CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, 
             CharSet nativeCharSet)
@@ -1491,9 +1163,6 @@ namespace System.Reflection.Emit
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         private MethodBuilder DefinePInvokeMethodNoLock(String name, String dllName, String entryName, MethodAttributes attributes, 
             CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, 
             CharSet nativeCharSet)
@@ -1536,9 +1205,6 @@ namespace System.Reflection.Emit
 
         #region Define Data
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes)
         {
             // This method will define an initialized Data in .sdata. 
@@ -1552,9 +1218,6 @@ namespace System.Reflection.Emit
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes)
         {
             // This method will define an initialized Data in .sdata. 
@@ -1571,9 +1234,6 @@ namespace System.Reflection.Emit
             return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes);
         }
         
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
         {
             Contract.Ensures(Contract.Result<FieldBuilder>() != null);
@@ -1584,9 +1244,6 @@ namespace System.Reflection.Emit
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes)
         {
             // This method will define an uninitialized Data in .sdata. 
@@ -1611,13 +1268,11 @@ namespace System.Reflection.Emit
         //   1. GetTypeToken
         //   2. ldtoken (see ILGenerator)
         // For all other occasions we should return the generic type instantiated on its formal parameters.
-        [System.Security.SecurityCritical]  // auto-generated
         internal TypeToken GetTypeTokenInternal(Type type)
         {
             return GetTypeTokenInternal(type, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private TypeToken GetTypeTokenInternal(Type type, bool getGenericDefinition)
         {
             lock(SyncRoot)
@@ -1626,13 +1281,11 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public TypeToken GetTypeToken(Type type)
         {        
             return GetTypeTokenInternal(type, true);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private TypeToken GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition)
         {
             if (type == null)
@@ -1698,19 +1351,6 @@ namespace System.Reflection.Emit
             //
             ModuleBuilder refedModuleBuilder = refedModule as ModuleBuilder;
 
-#if !FEATURE_CORECLR
-            Contract.Assert(refedModuleBuilder != null || refedModule is RuntimeModule);
-            bool isRefedModuleTransient = refedModuleBuilder != null ?
-                                          refedModuleBuilder.IsTransient() :
-                                          ((RuntimeModule)refedModule).IsTransientInternal();
-
-            // We cannot have a non-transient module referencing to a transient module.
-            if (IsTransient() == false && isRefedModuleTransient)
-            {
-                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadTransientModuleReference"));
-            }
-#endif // !FEATURE_CORECLR
-
             String strRefedModuleFileName = String.Empty;
             if (refedModule.Assembly.Equals(this.Assembly))
             {
@@ -1741,7 +1381,6 @@ namespace System.Reflection.Emit
             return GetTypeToken(InternalModule.GetType(name, false, true));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public MethodToken GetMethodToken(MethodInfo method)
         {
             lock(SyncRoot)
@@ -1750,7 +1389,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal MethodToken GetMethodTokenInternal(MethodInfo method)
         {
             lock(SyncRoot)
@@ -1763,7 +1401,6 @@ namespace System.Reflection.Emit
         //   1. GetMethodToken
         //   2. ldtoken (see ILGenerator)
         // For all other occasions we should return the method on the generic type instantiated on the formal parameters.
-        [System.Security.SecurityCritical]  // auto-generated
         private MethodToken GetMethodTokenNoLock(MethodInfo method, bool getGenericTypeDefinition)
         {
             // Return a MemberRef token if MethodInfo is not defined in this module. Or 
@@ -1873,7 +1510,6 @@ namespace System.Reflection.Emit
             return new MethodToken(mr);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public MethodToken GetConstructorToken(ConstructorInfo constructor, IEnumerable<Type> optionalParameterTypes)
         {
             if (constructor == null)
@@ -1888,7 +1524,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public MethodToken GetMethodToken(MethodInfo method, IEnumerable<Type> optionalParameterTypes)
         {
             if (method == null)
@@ -1910,7 +1545,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal int GetMethodTokenInternal(MethodBase method, IEnumerable<Type> optionalParameterTypes, bool useMethodDef)
         {
             int tk = 0;
@@ -1919,7 +1553,7 @@ namespace System.Reflection.Emit
             if (method.IsGenericMethod)
             {
                 // Constructors cannot be generic.
-                Contract.Assert(methodInfo != null);
+                Debug.Assert(methodInfo != null);
 
                 // Given M<Bar> unbind to M<S>
                 MethodInfo methodInfoUnbound = methodInfo;
@@ -1977,7 +1611,6 @@ namespace System.Reflection.Emit
             return tk;
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public MethodToken GetArrayMethodToken(Type arrayClass, String methodName, CallingConventions callingConvention, 
             Type returnType, Type[] parameterTypes)
         {
@@ -1987,7 +1620,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName, CallingConventions callingConvention, 
             Type returnType, Type[] parameterTypes)
         {
@@ -2023,7 +1655,6 @@ namespace System.Reflection.Emit
                 typeSpec.Token, methodName, sigBytes, length));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public MethodInfo GetArrayMethod(Type arrayClass, String methodName, CallingConventions callingConvention, 
             Type returnType, Type[] parameterTypes)
         {
@@ -2040,7 +1671,6 @@ namespace System.Reflection.Emit
             return new SymbolMethod(this, token, arrayClass, methodName, callingConvention, returnType, parameterTypes);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public MethodToken GetConstructorToken(ConstructorInfo con)
         {
@@ -2048,7 +1678,6 @@ namespace System.Reflection.Emit
             return InternalGetConstructorToken(con, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public FieldToken GetFieldToken(FieldInfo field) 
         {
             lock(SyncRoot)
@@ -2057,7 +1686,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private FieldToken GetFieldTokenNoLock(FieldInfo field) 
         {
             if (field == null) {
@@ -2146,7 +1774,6 @@ namespace System.Reflection.Emit
             return new FieldToken(mr, field.GetType());
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringToken GetStringConstant(String str) 
         {
             if (str == null)
@@ -2160,7 +1787,6 @@ namespace System.Reflection.Emit
             return new StringToken(GetStringConstant(GetNativeHandle(), str, str.Length));
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public SignatureToken GetSignatureToken(SignatureHelper sigHelper)
         {
             // Define signature token given a signature helper. This will define a metadata
@@ -2179,7 +1805,6 @@ namespace System.Reflection.Emit
             sigBytes = sigHelper.InternalGetSignature(out sigLength);
             return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), sigBytes, sigLength), this);
         }           
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength)
         {
             if (sigBytes == null)
@@ -2196,11 +1821,6 @@ namespace System.Reflection.Emit
 
         #region Other
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -2218,7 +1838,6 @@ namespace System.Reflection.Emit
                 false, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
         {
             if (customBuilder == null)
@@ -2264,9 +1883,6 @@ namespace System.Reflection.Emit
             return m_iSymWriter;
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] 
-#endif
         public ISymbolDocumentWriter DefineDocument(String url, Guid language, Guid languageVendor, Guid documentType)
         {
             // url cannot be null but can be an empty string 
@@ -2280,9 +1896,6 @@ namespace System.Reflection.Emit
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         private ISymbolDocumentWriter DefineDocumentNoLock(String url, Guid language, Guid languageVendor, Guid documentType)
         {
             if (m_iSymWriter == null)
@@ -2294,11 +1907,6 @@ namespace System.Reflection.Emit
             return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType);
         }
     
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public void SetUserEntryPoint(MethodInfo entryPoint)
         {
             lock(SyncRoot)
@@ -2307,7 +1915,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetUserEntryPointNoLock(MethodInfo entryPoint)
         {
             // Set the user entry point. Compiler may generate startup stub before calling user main.
@@ -2384,27 +1991,5 @@ namespace System.Reflection.Emit
         #endregion
 
         #endregion    
-
-#if !FEATURE_CORECLR
-        void _ModuleBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ModuleBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ModuleBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ModuleBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 }
index 2bec04a..96e60d9 100644 (file)
@@ -9,6 +9,7 @@
 namespace System.Reflection.Emit
 {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Globalization;
     using System.IO;
@@ -21,7 +22,6 @@ namespace System.Reflection.Emit
     [Serializable]
     internal class ModuleBuilderData
     {
-        [System.Security.SecurityCritical]  // auto-generated
         internal ModuleBuilderData(ModuleBuilder module, String strModuleName, String strFileName, int tkFile)
         {
             m_globalTypeBuilder = new TypeBuilder(module);
@@ -32,7 +32,6 @@ namespace System.Reflection.Emit
         }
 
         // Initialize module and file names.
-        [System.Security.SecurityCritical]  // auto-generated
         private void InitNames(String strModuleName, String strFileName)
         {
             m_strModuleName = strModuleName;
@@ -55,10 +54,9 @@ namespace System.Reflection.Emit
 
         // This is a method for changing module and file name of the manifest module (created by default for 
         // each assembly).
-        [System.Security.SecurityCritical]  // auto-generated
         internal virtual void ModifyModuleName(String strModuleName)
         {
-            Contract.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module");
+            Debug.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module");
             InitNames(strModuleName, null /*strFileName*/);
         }
 
index cae4f05..d7bfacd 100644 (file)
@@ -36,7 +36,6 @@ public struct OpCode
 
     internal const int StackChangeShift             = 28;           // XXXX0000000000000000000000000000
 
-#if FEATURE_CORECLR
     private OpCodeValues m_value;
     private int m_flags;
 
@@ -80,7 +79,6 @@ public struct OpCode
         }
     }
 
-
     public StackBehaviour StackBehaviourPop
     {
         get
@@ -112,121 +110,6 @@ public struct OpCode
             return (short)m_value;
         }
     }
-#else // FEATURE_CORECLR
-    //
-    // The exact layout is part of the legacy COM mscorlib surface, so it is
-    // pretty much set in stone for desktop CLR. Ideally, we would use the packed 
-    // bit field like for CoreCLR, but that would be a breaking change.
-    //
-
-// disable csharp compiler warning #0414: field assigned unused value
-#pragma warning disable 0414
-    private String m_stringname; // not used - computed lazily
-#pragma warning restore 0414
-    private StackBehaviour m_pop;
-    private StackBehaviour m_push;
-    private OperandType m_operand;
-    private OpCodeType m_type;
-    private int m_size;
-    private byte m_s1;
-    private byte m_s2;
-    private FlowControl m_ctrl;
-
-    // Specifies whether the current instructions causes the control flow to
-    // change unconditionally.
-    private bool m_endsUncondJmpBlk;
-
-
-    // Specifies the stack change that the current instruction causes not
-    // taking into account the operand dependant stack changes.
-    private int m_stackChange;
-
-
-    internal OpCode(OpCodeValues value, int flags)
-    {
-        m_stringname = null; // computed lazily
-        m_pop = (StackBehaviour)((flags >> StackBehaviourPopShift) & StackBehaviourMask);
-        m_push = (StackBehaviour)((flags >> StackBehaviourPushShift) & StackBehaviourMask);
-        m_operand = (OperandType)(flags & OperandTypeMask);
-        m_type = (OpCodeType)((flags >> OpCodeTypeShift) & OpCodeTypeMask);
-        m_size = (flags >> SizeShift) & SizeMask;
-        m_s1 = (byte)((int)value >> 8);
-        m_s2 = (byte)(int)value;
-        m_ctrl = (FlowControl)((flags >> FlowControlShift) & FlowControlMask);
-        m_endsUncondJmpBlk = (flags & EndsUncondJmpBlkFlag) != 0;
-        m_stackChange = (flags >> StackChangeShift);
-    }
-
-    internal bool EndsUncondJmpBlk()
-    {
-        return m_endsUncondJmpBlk;
-    }
-
-    internal int StackChange()
-    {
-        return m_stackChange;
-    }
-
-    public OperandType OperandType
-    {
-        get
-        {
-            return (m_operand);
-        }
-    }
-
-    public FlowControl FlowControl
-    {
-        get
-        {
-            return (m_ctrl);
-        }
-    }
-
-    public OpCodeType OpCodeType
-    {
-        get
-        {
-            return (m_type);
-        }
-    }
-
-
-    public StackBehaviour StackBehaviourPop
-    {
-        get
-        {
-            return (m_pop);
-        }
-    }
-
-    public StackBehaviour StackBehaviourPush
-    {
-        get
-        {
-            return (m_push);
-        }
-    }
-
-    public int Size
-    {
-        get
-        {
-            return (m_size);
-        }
-    }
-
-    public short Value
-    {
-        get
-        {
-            if (m_size == 2)
-                return (short)(m_s1 << 8 | m_s2);
-            return (short)m_s2;
-        }
-    }
-#endif // FEATURE_CORECLR
-
 
     private static volatile string[] g_nameCache;
 
@@ -308,5 +191,4 @@ public struct OpCode
         return Name;
     }
 }
-
 }
index 615cbb8..7909562 100644 (file)
@@ -25,7 +25,6 @@ namespace System.Reflection.Emit {
     public class ParameterBuilder : _ParameterBuilder
     {
         // set ParamMarshal
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
         public virtual void SetMarshal(UnmanagedMarshal unmanagedMarshal)
         {
@@ -44,7 +43,6 @@ namespace System.Reflection.Emit {
         }
     
         // Set the default value of the parameter
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public virtual void SetConstant(Object defaultValue) 
         {
             TypeBuilder.SetConstantValue(
@@ -56,7 +54,6 @@ namespace System.Reflection.Emit {
         
         // Use this function if client decides to form the custom attribute blob themselves
 
-        [System.Security.SecuritySafeCritical]
         [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -75,7 +72,6 @@ namespace System.Reflection.Emit {
         }
 
         // Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
         {
             if (customBuilder == null)
@@ -92,7 +88,6 @@ namespace System.Reflection.Emit {
         private ParameterBuilder() {}
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal ParameterBuilder(
             MethodBuilder   methodBuilder, 
             int             sequence, 
@@ -117,28 +112,6 @@ namespace System.Reflection.Emit {
             return m_pdToken;
         } 
 
-#if !FEATURE_CORECLR
-        void _ParameterBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ParameterBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ParameterBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ParameterBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-    
         internal int MetadataTokenInternal { get { return m_pdToken.Token; } }
         
         public virtual String Name {
index 4b8e40f..e7442b4 100644 (file)
@@ -25,7 +25,6 @@ namespace System.Reflection.Emit {
     // A PropertyBuilder is always associated with a TypeBuilder.  The TypeBuilder.DefineProperty
     // method will return a new PropertyBuilder to a client.
     // 
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_PropertyBuilder))]
     [System.Runtime.InteropServices.ComVisible(true)]
@@ -67,7 +66,6 @@ namespace System.Reflection.Emit {
         //************************************************
         // Set the default value of the Property
         //************************************************
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetConstant(Object defaultValue) 
         {
             m_containingType.ThrowIfCreated();
@@ -103,7 +101,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics)
         {
             if (mdBuilder == null)
@@ -119,21 +116,18 @@ namespace System.Reflection.Emit {
                 mdBuilder.GetToken().Token);
         }    
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetGetMethod(MethodBuilder mdBuilder)
         {
             SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Getter);
             m_getMethod = mdBuilder;
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetSetMethod(MethodBuilder mdBuilder)
         {
             SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Setter);
             m_setMethod = mdBuilder;                
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AddOtherMethod(MethodBuilder mdBuilder)
         {
             SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other);
@@ -141,11 +135,6 @@ namespace System.Reflection.Emit {
     
         // Use this function if client decides to form the custom attribute blob themselves
 
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#else
-[System.Security.SecuritySafeCritical]
-#endif
 [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -164,7 +153,6 @@ namespace System.Reflection.Emit {
         }
 
         // Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
         {
             if (customBuilder == null)
@@ -256,28 +244,6 @@ namespace System.Reflection.Emit {
             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
         }
 
-#if !FEATURE_CORECLR
-        void _PropertyBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _PropertyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _PropertyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _PropertyBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
         public override String Name {
             get { return m_name; }
         }
@@ -302,5 +268,4 @@ namespace System.Reflection.Emit {
         private MethodInfo          m_setMethod;
         private TypeBuilder         m_containingType;
     }
-
 }
index b2a3493..c40035b 100644 (file)
@@ -8,6 +8,7 @@ namespace System.Reflection.Emit
 {
     using System.Text;
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Reflection;
     using System.Runtime.CompilerServices;
@@ -25,19 +26,16 @@ namespace System.Reflection.Emit
         #endregion
     
         #region Static Members
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes)
         {
             return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam)
         {
             return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType)
         {
             return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null);
@@ -52,7 +50,6 @@ namespace System.Reflection.Emit
             return sigHelp;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal static SignatureHelper GetMethodSigHelper(
             Module scope, CallingConventions callingConvention,
             Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
@@ -62,7 +59,6 @@ namespace System.Reflection.Emit
                 optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static SignatureHelper GetMethodSigHelper(
             Module scope, CallingConventions callingConvention, int cGenericParam,
             Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
@@ -96,7 +92,6 @@ namespace System.Reflection.Emit
             return sigHelp;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType)
         {
             SignatureHelper sigHelp;
@@ -168,7 +163,6 @@ namespace System.Reflection.Emit
             return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, 
                 parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
         }
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention,
             Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, 
             Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
@@ -192,7 +186,6 @@ namespace System.Reflection.Emit
             return sigHelp;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal static SignatureHelper GetTypeSigToken(Module mod, Type type)
         {
             if (mod == null)
@@ -221,7 +214,6 @@ namespace System.Reflection.Emit
             Init(mod, callingConvention);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters,
             Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
         {
@@ -234,14 +226,12 @@ namespace System.Reflection.Emit
             AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers);                          
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, 
             Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
             : this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers)
         {
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private SignatureHelper(Module mod, Type type)
         {
             Init(mod);
@@ -290,7 +280,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Private Members
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddOneArgTypeHelper(Type argument, bool pinned)
         {
             if (pinned)
@@ -299,7 +288,6 @@ namespace System.Reflection.Emit
             AddOneArgTypeHelper(argument);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
         {
             // This function will not increase the argument count. It only fills in bytes 
@@ -326,7 +314,7 @@ namespace System.Reflection.Emit
                     AddElementType(CorElementType.CModOpt);
 
                     int token = m_module.GetTypeToken(t).Token;
-                    Contract.Assert(!MetadataToken.IsNullToken(token));
+                    Debug.Assert(!MetadataToken.IsNullToken(token));
                     AddToken(token);
                 }
             }
@@ -349,7 +337,7 @@ namespace System.Reflection.Emit
                     AddElementType(CorElementType.CModReqd);
 
                     int token = m_module.GetTypeToken(t).Token;
-                    Contract.Assert(!MetadataToken.IsNullToken(token));
+                    Debug.Assert(!MetadataToken.IsNullToken(token));
                     AddToken(token);
                 }
             }
@@ -357,9 +345,7 @@ namespace System.Reflection.Emit
             AddOneArgTypeHelper(clsArgument);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, false); }
-        [System.Security.SecurityCritical]  // auto-generated
         private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst)
         {
             if (clsArgument.IsGenericParameter)
@@ -613,7 +599,6 @@ namespace System.Reflection.Emit
             AddToken(clsToken.Token);
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe void InternalAddRuntimeType(Type type)
         {
             // Add a runtime type into the signature. 
@@ -822,7 +807,6 @@ namespace System.Reflection.Emit
             AddArgument(clsArgument, null, null);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AddArgument(Type argument, bool pinned)
         {
             if (argument == null)
@@ -851,7 +835,6 @@ namespace System.Reflection.Emit
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
         {
             if (m_sigDone)
@@ -968,28 +951,6 @@ namespace System.Reflection.Emit
         
         #endregion
 
-#if !FEATURE_CORECLR
-        void _SignatureHelper.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _SignatureHelper.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _SignatureHelper.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _SignatureHelper.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
     }
 }
 
index 62780f4..6b47770 100644 (file)
@@ -26,7 +26,6 @@ namespace System.Reflection.Emit
         #endregion
 
         #region Constructor
-        [System.Security.SecurityCritical]  // auto-generated
         internal SymbolMethod(ModuleBuilder mod, MethodToken token, Type arrayClass, String methodName, 
             CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
         {
index dd34891..73778d5 100644 (file)
@@ -10,13 +10,13 @@ namespace System.Reflection.Emit {
     using System.Reflection;
     using System.Security;
     using System.Security.Permissions;
-    using System.Diagnostics;
     using System.Runtime.InteropServices;
     using System.Runtime.CompilerServices;
     using System.Collections.Generic;
     using CultureInfo = System.Globalization.CultureInfo;
     using System.Threading;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
 
@@ -35,7 +35,6 @@ namespace System.Reflection.Emit {
         Size128                     = 128,
     }
 
-    [HostProtection(MayLeakOnAbort = true)]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_TypeBuilder))]
     [System.Runtime.InteropServices.ComVisible(true)]
@@ -75,7 +74,6 @@ namespace System.Reflection.Emit {
                 m_customBuilder = customBuilder;
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             public void Bake(ModuleBuilder module, int token)
             {
                 if (m_customBuilder == null)
@@ -174,36 +172,30 @@ namespace System.Reflection.Emit {
         #endregion
 
         #region Private Static FCalls
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private static extern void SetParentType(RuntimeModule module, int tdTypeDef, int tkParent);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private static extern void AddInterfaceImpl(RuntimeModule module, int tdTypeDef, int tkInterface);
         #endregion
 
         #region Internal Static FCalls
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern int DefineMethod(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength, 
             MethodAttributes attributes);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern int DefineMethodSpec(RuntimeModule module, int tkParent, byte[] signature, int sigLength);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern int DefineField(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength, 
             FieldAttributes attributes);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private static extern void SetMethodIL(RuntimeModule module, int tk, bool isInitLocals,  
@@ -213,13 +205,11 @@ namespace System.Reflection.Emit {
             ExceptionHandler[] exceptions, int numExceptions, 
             int [] tokenFixups, int numTokenFixups);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private static extern void DefineCustomAttribute(RuntimeModule module, int tkAssociate, int tkConstructor, 
             byte[] attr, int attrLength, bool toDisk, bool updateCompilerFlags);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor,
             byte[] attr, bool toDisk, bool updateCompilerFlags)
         {
@@ -235,75 +225,56 @@ namespace System.Reflection.Emit {
                 localAttr, (localAttr != null) ? localAttr.Length : 0, toDisk, updateCompilerFlags);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern void SetPInvokeData(RuntimeModule module, String DllName, String name, int token, int linkFlags);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern int DefineProperty(RuntimeModule module, int tkParent, String name, PropertyAttributes attributes,
             byte[] signature, int sigLength);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern int DefineEvent(RuntimeModule module, int tkParent, String name, EventAttributes attributes, int tkEventType);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern void DefineMethodSemantics(RuntimeModule module, int tkAssociation, 
             MethodSemanticsAttributes semantics, int tkMethod);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern void DefineMethodImpl(RuntimeModule module, int tkType, int tkBody, int tkDecl);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern void SetMethodImpl(RuntimeModule module, int tkMethod, MethodImplAttributes MethodImplAttributes);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern int SetParamInfo(RuntimeModule module, int tkMethod, int iSequence, 
             ParameterAttributes iParamAttributes, String strParamName);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern int GetTokenFromSig(RuntimeModule module, byte[] signature, int sigLength);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern void SetFieldLayoutOffset(RuntimeModule module, int fdToken, int iOffset);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern void SetClassLayout(RuntimeModule module, int tk, PackingSize iPackingSize, int iTypeSize);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         internal static extern void SetFieldMarshal(RuntimeModule module, int tk, byte[] ubMarshal, int ubSize);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private static extern unsafe void SetConstantValue(RuntimeModule module, int tk, int corType, void* pValue);
-
-#if FEATURE_CAS_POLICY
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-               [SuppressUnmanagedCodeSecurity]
-        internal static extern void AddDeclarativeSecurity(RuntimeModule module, int parent, SecurityAction action, byte[] blob, int cb);
-#endif
         #endregion
 
         #region Internal\Private Static Members
@@ -381,7 +352,6 @@ namespace System.Reflection.Emit {
             return false;                
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, Object value)
         {
             // This is a helper function that is used by ParameterBuilder, PropertyBuilder,
@@ -433,7 +403,7 @@ namespace System.Reflection.Emit {
                     }
                     else // must be a runtime Enum Type
                     {
-                        Contract.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder.");
+                        Debug.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder.");
 
                         underlyingType = Enum.GetUnderlyingType(destType);
 
@@ -576,7 +546,6 @@ namespace System.Reflection.Emit {
             m_typeInterfaces = new List<Type>();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal TypeBuilder(
             String name,
             TypeAttributes attr,
@@ -590,7 +559,6 @@ namespace System.Reflection.Emit {
             Init(name, attr, parent, interfaces, module, iPackingSize, iTypeSize, enclosingType);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void Init(String fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module,
             PackingSize iPackingSize, int iTypeSize, TypeBuilder enclosingType)
         {
@@ -685,32 +653,12 @@ namespace System.Reflection.Emit {
             if ((m_iPackingSize != 0) ||(m_iTypeSize != 0))
                 SetClassLayout(GetModuleBuilder().GetNativeHandle(), m_tdType.Token, m_iPackingSize, m_iTypeSize);
 
-#if !FEATURE_CORECLR
-            // If the type is public and it is contained in a assemblyBuilder,
-            // update the public COMType list.
-            if (IsPublicComType(this))
-            {
-                if (containingAssem.IsPersistable() && m_module.IsTransient() == false)
-                {
-                    // This will throw InvalidOperationException if the assembly has been saved
-                    // Ideally we should reject all emit operations if the assembly has been saved,
-                    // but that would be a breaking change for some. Currently you cannot define 
-                    // modules and public types, but you can still define private types and global methods.
-                    containingAssem.m_assemblyData.AddPublicComType(this);
-                }
-
-                // Now add the type to the ExportedType table
-                if (!m_module.Equals(containingAssem.ManifestModule))
-                    containingAssem.DefineExportedTypeInMemory(this, m_module.m_moduleData.FileToken, m_tdType.Token);
-            }
-#endif
             m_module.AddType(FullName, this);
         }
 
         #endregion
 
         #region Private Members
-        [System.Security.SecurityCritical]  // auto-generated
         private MethodBuilder DefinePInvokeMethodHelper(
             String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, 
             Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
@@ -733,7 +681,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private MethodBuilder DefinePInvokeMethodHelperNoLock(
             String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, 
             Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
@@ -831,7 +778,6 @@ namespace System.Reflection.Emit {
             return method;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private FieldBuilder DefineDataHelper(String name, byte[] data, int size, FieldAttributes attributes)
         {
             String strValueClassName;
@@ -916,19 +862,16 @@ namespace System.Reflection.Emit {
         #endregion
 
         #region FCalls
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private extern static int DefineType(RuntimeModule module,
             String fullname, int tkParent, TypeAttributes attributes, int tkEnclosingType, int[] interfaceTokens);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private extern static int DefineGenericParam(RuntimeModule module,
             String name, int tkParent, GenericParameterAttributes attributes, int position, int[] constraints);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private static extern void TermCreateClass(RuntimeModule module, int tk, ObjectHandleOnStack type);
@@ -1363,50 +1306,17 @@ namespace System.Reflection.Emit {
 
         public override bool IsSecurityCritical
         {
-#if FEATURE_CORECLR
             get { return true; }
-#else
-            get
-            {
-                if (!IsCreated())
-                    throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
-                Contract.EndContractBlock();
-
-                return m_bakedRuntimeType.IsSecurityCritical;
-            }
-#endif
         }
 
         public override bool IsSecuritySafeCritical
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            get
-            {
-                if (!IsCreated())
-                    throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
-                Contract.EndContractBlock();
-
-                return m_bakedRuntimeType.IsSecuritySafeCritical;
-            }
-#endif
         }
 
         public override bool IsSecurityTransparent
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            get
-            {
-                if (!IsCreated())
-                    throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
-                Contract.EndContractBlock();
-
-                return m_bakedRuntimeType.IsSecurityTransparent;
-            }
-#endif
         }
 
         [System.Runtime.InteropServices.ComVisible(true)]
@@ -1491,7 +1401,6 @@ namespace System.Reflection.Emit {
         #endregion
 
         #region ICustomAttributeProvider Implementation
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Object[] GetCustomAttributes(bool inherit)
         {
             if (!IsCreated())
@@ -1501,7 +1410,6 @@ namespace System.Reflection.Emit {
             return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
         {
             if (!IsCreated())
@@ -1519,7 +1427,6 @@ namespace System.Reflection.Emit {
             return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, attributeRuntimeType, inherit);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsDefined(Type attributeType, bool inherit)
         {
             if (!IsCreated())
@@ -1601,7 +1508,6 @@ namespace System.Reflection.Emit {
         #endregion
 
         #region Define Method
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
         {
             lock(SyncRoot)
@@ -1610,7 +1516,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
         {
             if (methodInfoBody == null)
@@ -1737,7 +1642,6 @@ namespace System.Reflection.Emit {
         #endregion
 
         #region Define Constructor
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public ConstructorBuilder DefineTypeInitializer()
         {
@@ -1747,7 +1651,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private ConstructorBuilder DefineTypeInitializerNoLock()
         {
             ThrowIfCreated();
@@ -1835,7 +1738,6 @@ namespace System.Reflection.Emit {
             return DefineConstructor(attributes, callingConvention, parameterTypes, null, null);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, 
             Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
@@ -1851,7 +1753,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention, 
             Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
         {
@@ -1886,11 +1787,6 @@ namespace System.Reflection.Emit {
         #endregion
 
         #region Define PInvoke
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes,
             CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
             CallingConvention nativeCallConv, CharSet nativeCharSet)
@@ -1901,11 +1797,6 @@ namespace System.Reflection.Emit {
             return method;
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, 
             CallingConventions callingConvention, Type returnType, Type[] parameterTypes, 
             CallingConvention nativeCallConv, CharSet nativeCharSet)
@@ -1916,11 +1807,6 @@ namespace System.Reflection.Emit {
             return method;
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
             CallingConventions callingConvention, 
             Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
@@ -1936,7 +1822,6 @@ namespace System.Reflection.Emit {
         #endregion
 
         #region Define Nested Type
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public TypeBuilder DefineNestedType(String name)
         {
             lock(SyncRoot)
@@ -1945,7 +1830,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
         {
@@ -1959,7 +1843,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent)
         {
             lock(SyncRoot)
@@ -1968,7 +1851,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public TypeBuilder DefineNestedType(String name, TypeAttributes attr)
         {
             lock(SyncRoot)
@@ -1977,11 +1859,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, int typeSize)
         {
             lock(SyncRoot)
@@ -1990,11 +1867,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, PackingSize packSize)
         {
             lock(SyncRoot)
@@ -2003,11 +1875,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, PackingSize packSize, int typeSize)
         {
             lock (SyncRoot)
@@ -2016,7 +1883,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private TypeBuilder DefineNestedTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packSize, int typeSize)
         {
             return new TypeBuilder(name, attr, parent, interfaces, m_module, packSize, typeSize, this);
@@ -2030,7 +1896,6 @@ namespace System.Reflection.Emit {
             return DefineField(fieldName, type, null, null, attributes);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public FieldBuilder DefineField(String fieldName, Type type, Type[] requiredCustomModifiers, 
             Type[] optionalCustomModifiers, FieldAttributes attributes) 
         {
@@ -2040,7 +1905,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private FieldBuilder DefineFieldNoLock(String fieldName, Type type, Type[] requiredCustomModifiers, 
             Type[] optionalCustomModifiers, FieldAttributes attributes) 
         {
@@ -2060,11 +1924,6 @@ namespace System.Reflection.Emit {
             return new FieldBuilder(this, fieldName, type, requiredCustomModifiers, optionalCustomModifiers, attributes);
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes)
         {
             lock(SyncRoot)
@@ -2073,7 +1932,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes)
         {
             if (data == null)
@@ -2087,11 +1945,6 @@ namespace System.Reflection.Emit {
             return DefineDataHelper(name, data, data.Length, attributes);
         }
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
         {
             lock(SyncRoot)
@@ -2100,7 +1953,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes)
         {
             // This method will define an uninitialized Data in .sdata.
@@ -2133,7 +1985,6 @@ namespace System.Reflection.Emit {
                 parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); 
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, CallingConventions callingConvention, 
             Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, 
             Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
@@ -2145,7 +1996,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private PropertyBuilder DefinePropertyNoLock(String name, PropertyAttributes attributes, CallingConventions callingConvention,
             Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, 
             Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
@@ -2195,7 +2045,6 @@ namespace System.Reflection.Emit {
                     this);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public EventBuilder DefineEvent(String name, EventAttributes attributes, Type eventtype)
         {
             lock(SyncRoot)
@@ -2204,7 +2053,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private EventBuilder DefineEventNoLock(String name, EventAttributes attributes, Type eventtype)
         {
             if (name == null)
@@ -2246,7 +2094,6 @@ namespace System.Reflection.Emit {
 
         #region Create Type
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public TypeInfo CreateTypeInfo()
         {
             lock (SyncRoot)
@@ -2255,7 +2102,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Type CreateType()
         {
             lock (SyncRoot)
@@ -2273,7 +2119,6 @@ namespace System.Reflection.Emit {
             m_module.CheckContext(types);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private TypeInfo CreateTypeNoLock()
         {
             if (IsCreated())
@@ -2498,7 +2343,6 @@ namespace System.Reflection.Emit {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public void AddInterfaceImplementation(Type interfaceType)
         {
@@ -2518,50 +2362,6 @@ namespace System.Reflection.Emit {
             m_typeInterfaces.Add(interfaceType);
         }
 
-#if FEATURE_CAS_POLICY
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
-        {
-            lock(SyncRoot)
-            {
-                AddDeclarativeSecurityNoLock(action, pset);
-            }
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private void AddDeclarativeSecurityNoLock(SecurityAction action, PermissionSet pset)
-        {
-            if (pset == null)
-                throw new ArgumentNullException(nameof(pset));
-
-#pragma warning disable 618
-            if (!Enum.IsDefined(typeof(SecurityAction), action) ||
-                action == SecurityAction.RequestMinimum ||
-                action == SecurityAction.RequestOptional ||
-                action == SecurityAction.RequestRefuse)
-            {
-                throw new ArgumentOutOfRangeException(nameof(action));
-            }
-#pragma warning restore 618
-
-            Contract.EndContractBlock();
-
-            ThrowIfCreated();
-
-            // Translate permission set into serialized format(uses standard binary serialization format).
-            byte[] blob = null;
-            int length = 0;
-            if (!pset.IsEmpty())
-            {
-                blob = pset.EncodeXml();
-                length = blob.Length;
-            }
-
-            // Write the blob into the metadata.
-            AddDeclarativeSecurity(m_module.GetNativeHandle(), m_tdType.Token, action, blob, length);
-        }
-#endif // FEATURE_CAS_POLICY
-
 public TypeToken TypeToken 
         {
             get 
@@ -2574,11 +2374,6 @@ public TypeToken TypeToken
         }
 
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#else
-        [System.Security.SecuritySafeCritical]
-#endif
         [System.Runtime.InteropServices.ComVisible(true)]
         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
         {
@@ -2593,7 +2388,6 @@ public TypeToken TypeToken
                 binaryAttribute, false, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
         {
             if (customBuilder == null)
@@ -2606,27 +2400,5 @@ public TypeToken TypeToken
         #endregion
 
         #endregion
-
-#if !FEATURE_CORECLR
-        void _TypeBuilder.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _TypeBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _TypeBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 }
index 09eac3a..28e95e2 100644 (file)
@@ -10,7 +10,6 @@ namespace System.Reflection.Emit
 
     // This class is describing the fieldmarshal.
     [Serializable]
-    [HostProtection(MayLeakOnAbort = true)]
     [System.Runtime.InteropServices.ComVisible(true)]
     [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
     public sealed class UnmanagedMarshal
index 5b36e0e..aaaffc0 100644 (file)
@@ -11,6 +11,7 @@ namespace System.Reflection.Emit
     using System.Collections;
     using System.Collections.Generic;
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo
@@ -30,7 +31,7 @@ namespace System.Reflection.Emit
         #region Constructor
         internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type)
         {
-            Contract.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
+            Debug.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
 
             m_method = method;
             m_type = type;
@@ -60,7 +61,7 @@ namespace System.Reflection.Emit
                     return mb.MetadataTokenInternal;
                 else
                 {
-                    Contract.Assert(m_method is RuntimeMethodInfo);
+                    Debug.Assert(m_method is RuntimeMethodInfo);
                     return m_method.MetadataToken;
                 }
             }
@@ -122,7 +123,7 @@ namespace System.Reflection.Emit
         #region Constructor
         internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type)
         {
-            Contract.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
+            Debug.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
 
             m_ctor = constructor;
             m_type = type;
@@ -157,7 +158,7 @@ namespace System.Reflection.Emit
                     return cb.MetadataTokenInternal;
                 else
                 {
-                    Contract.Assert(m_ctor is RuntimeConstructorInfo);
+                    Debug.Assert(m_ctor is RuntimeConstructorInfo);
                     return m_ctor.MetadataToken;
                 }
             }
@@ -231,7 +232,7 @@ namespace System.Reflection.Emit
         #region Constructor
         internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type)
         {
-            Contract.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
+            Debug.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
 
             m_field = field;
             m_type = type;
@@ -258,7 +259,7 @@ namespace System.Reflection.Emit
                     return fb.MetadataTokenInternal;
                 else
                 {
-                    Contract.Assert(m_field is RuntimeFieldInfo);
+                    Debug.Assert(m_field is RuntimeFieldInfo);
                     return m_field.MetadataToken;
                 }
             }
index 509b16b..0eabb9d 100644 (file)
@@ -19,9 +19,6 @@ namespace System.Reflection
     [Serializable]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_EventInfo))]
-#pragma warning disable 618
-    [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
     [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class EventInfo : MemberInfo, _EventInfo
     {
@@ -123,7 +120,7 @@ namespace System.Reflection
                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
 
             // Must be a normal non-WinRT event
-            Contract.Assert(addMethod.ReturnType == typeof(void));
+            Debug.Assert(addMethod.ReturnType == typeof(void));
 #endif // FEATURE_COMINTEROP
 
             addMethod.Invoke(target, new object[] { handler });
@@ -140,13 +137,13 @@ namespace System.Reflection
 
 #if FEATURE_COMINTEROP
             ParameterInfo[] parameters = removeMethod.GetParametersNoCopy();
-            Contract.Assert(parameters != null && parameters.Length == 1);
+            Debug.Assert(parameters != null && parameters.Length == 1);
 
             if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken))
                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
 
             // Must be a normal non-WinRT event
-            Contract.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate));
+            Debug.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate));
 #endif // FEATURE_COMINTEROP
 
             removeMethod.Invoke(target, new object[] { handler });
@@ -190,35 +187,6 @@ namespace System.Reflection
             }
         }
         #endregion
-
-#if !FEATURE_CORECLR
-        Type _EventInfo.GetType()
-        {
-            return base.GetType();
-        }
-
-        void _EventInfo.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _EventInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _EventInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        // If you implement this method, make sure to include _EventInfo.Invoke in VM\DangerousAPIs.h and 
-        // include _EventInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
-        void _EventInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 
     [Serializable]
@@ -228,7 +196,6 @@ namespace System.Reflection
         private int m_token;
         private EventAttributes m_flags;
         private string m_name;
-        [System.Security.SecurityCritical]
         private void* m_utf8name;
         private RuntimeTypeCache m_reflectedTypeCache;
         private RuntimeMethodInfo m_addMethod;
@@ -244,12 +211,11 @@ namespace System.Reflection
         {
             // Used for dummy head node during population
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
         {
             Contract.Requires(declaredType != null);
             Contract.Requires(reflectedTypeCache != null);
-            Contract.Assert(!reflectedTypeCache.IsGlobal);
+            Debug.Assert(!reflectedTypeCache.IsGlobal);
 
             MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
 
@@ -316,7 +282,6 @@ namespace System.Reflection
             return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsDefined(Type attributeType, bool inherit)
         {
             if (attributeType == null)
@@ -341,7 +306,6 @@ namespace System.Reflection
         public override MemberTypes MemberType { get { return MemberTypes.Event; } }
         public override String Name 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get 
             {
                 if (m_name == null)
@@ -373,7 +337,6 @@ namespace System.Reflection
         #endregion
 
         #region ISerializable
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
index 5852de7..e61207a 100644 (file)
@@ -15,9 +15,6 @@ namespace System.Reflection
     using System.Runtime.CompilerServices;
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.InteropServices;
-#if FEATURE_REMOTING
-    using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
     using System.Runtime.Serialization;
     using System.Security.Permissions;
     using System.Threading;
@@ -26,9 +23,6 @@ namespace System.Reflection
     [Serializable]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_FieldInfo))]
-#pragma warning disable 618
-    [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
     [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class FieldInfo : MemberInfo, _FieldInfo
     {
@@ -186,35 +180,6 @@ namespace System.Reflection
         }
 
         #endregion
-
-#if !FEATURE_CORECLR
-        Type _FieldInfo.GetType()
-        {
-            return base.GetType();
-        }
-
-        void _FieldInfo.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _FieldInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _FieldInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        // If you implement this method, make sure to include _FieldInfo.Invoke in VM\DangerousAPIs.h and 
-        // include _FieldInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
-        void _FieldInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 
     [Serializable]
@@ -239,36 +204,6 @@ namespace System.Reflection
         }
         #endregion
 
-#if FEATURE_REMOTING
-        #region Legacy Remoting Cache
-        // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
-        // This member is currently being used by Remoting for caching remoting data. If you
-        // need to cache data here, talk to the Remoting team to work out a mechanism, so that
-        // both caching systems can happily work together.
-        private RemotingFieldCachedData m_cachedData;
-
-        internal RemotingFieldCachedData RemotingCache
-        {
-            get
-            {
-                // This grabs an internal copy of m_cachedData and uses
-                // that instead of looking at m_cachedData directly because
-                // the cache may get cleared asynchronously.  This prevents
-                // us from having to take a lock.
-                RemotingFieldCachedData cache = m_cachedData;
-                if (cache == null)
-                {
-                    cache = new RemotingFieldCachedData(this);
-                    RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
-                    if (ret != null)
-                        cache = ret;
-                }
-                return cache;
-            }
-        }
-        #endregion
-#endif //FEATURE_REMOTING
-
         #region NonPublic Members
         internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
         private RuntimeType ReflectedTypeInternal
@@ -336,7 +271,6 @@ namespace System.Reflection
             return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsDefined(Type attributeType, bool inherit)
         {
             if (attributeType == null)
@@ -362,7 +296,6 @@ namespace System.Reflection
         #endregion
 
         #region ISerializable Implementation
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
@@ -382,7 +315,6 @@ namespace System.Reflection
     internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo
     {
         #region FCalls
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags);
         #endregion
@@ -480,7 +412,6 @@ namespace System.Reflection
         private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); }
 
         #region Constructor
-        [System.Security.SecurityCritical]  // auto-generated
         internal RtFieldInfo(
             RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) 
             : base(reflectedTypeCache, declaringType, bindingFlags)
@@ -493,7 +424,6 @@ namespace System.Reflection
         #region Private Members
         RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 return new RuntimeFieldHandleInternal(m_fieldHandle);
@@ -535,7 +465,6 @@ namespace System.Reflection
             return m.m_fieldHandle == m_fieldHandle;
         }
 
-        [System.Security.SecurityCritical]
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark)
@@ -592,7 +521,6 @@ namespace System.Reflection
         // InternalSetValue() instead. When the caller needs to perform 
         // consistency checks they should call CheckConsistency() before 
         // calling this method.
-        [System.Security.SecurityCritical]  // auto-generated
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
@@ -614,7 +542,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark)
@@ -657,7 +584,6 @@ namespace System.Reflection
         // InternalGetValue() instead. When the caller needs to perform 
         // consistency checks they should call CheckConsistency() before 
         // calling this method.
-        [System.Security.SecurityCritical]
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         internal Object UnsafeGetValue(Object obj)
@@ -685,7 +611,6 @@ namespace System.Reflection
         #region MemberInfo Overrides
         public override String Name 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (m_name == null)
@@ -705,11 +630,9 @@ namespace System.Reflection
 
         public override int MetadataToken
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return RuntimeFieldHandle.GetToken(this); }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal override RuntimeModule GetRuntimeModule()
         {
             return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this));
@@ -726,7 +649,6 @@ namespace System.Reflection
         
         public override object GetRawConstantValue() { throw new InvalidOperationException(); }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         public override Object GetValueDirect(TypedReference obj)
@@ -742,7 +664,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
@@ -751,7 +672,6 @@ namespace System.Reflection
             InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         public override void SetValueDirect(TypedReference obj, Object value)
@@ -793,7 +713,6 @@ namespace System.Reflection
 
         public override Type FieldType 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (m_fieldType == null)
@@ -803,13 +722,11 @@ namespace System.Reflection
             }
         }       
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Type[] GetRequiredCustomModifiers()
         {
             return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Type[] GetOptionalCustomModifiers()
         {
             return new Signature(this, m_declaringType).GetCustomModifiers(1, false);
@@ -857,7 +774,6 @@ namespace System.Reflection
         #region MemberInfo Overrides
         public override String Name 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (m_name == null)
@@ -902,7 +818,6 @@ namespace System.Reflection
 
         public unsafe override Object GetRawConstantValue() { return GetValue(true); }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe Object GetValue(bool raw)
         {
             // Cannot cache these because they could be user defined non-agile enumerations
@@ -924,7 +839,6 @@ namespace System.Reflection
 
         public override Type FieldType 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (m_fieldType == null)
index a8b4b0c..7c6c6bd 100644 (file)
@@ -34,11 +34,9 @@ namespace System.Reflection
         internal IntPtr m_nativeLoaderAllocator;
 
         [SuppressUnmanagedCodeSecurity]
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         private static extern bool Destroy(IntPtr nativeLoaderAllocator);
 
-        [SecuritySafeCritical]
         ~LoaderAllocatorScout()
         {
             if (m_nativeLoaderAllocator.IsNull())
index 1941736..e59244f 100644 (file)
@@ -10,7 +10,6 @@ namespace System.Reflection
 
     internal static class MdConstant
     {
-        [System.Security.SecurityCritical]  // auto-generated
         public static unsafe Object GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw)
         {
             CorElementType corElementType = 0;
index 3bf8edd..bbdf948 100644 (file)
@@ -174,7 +174,6 @@ namespace System.Reflection
         public int Length { get { return m_length; } }
         public byte this[int index]
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (index < 0 || index >= m_length)
@@ -269,7 +268,6 @@ namespace System.Reflection
 
         public int this[int index]
         {
-            [System.Security.SecurityCritical]
             get
             {
                 Contract.Requires(0 <= index && index < Length);
@@ -312,12 +310,10 @@ namespace System.Reflection
         #endregion
 
         #region Static Members
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType, 
             out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
             out int iidParamIndex);
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void GetMarshalAs(ConstArray nativeType, 
             out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType, 
             out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
@@ -351,56 +347,46 @@ namespace System.Reflection
         #endregion
 
         #region FCalls
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute (MethodImplOptions.InternalCall)]
         private unsafe static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result);
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result) 
         { 
             _Enum(m_metadataImport2, (int)type, parent, out result);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result) 
         {
             Enum(MetadataTokenType.TypeDef, mdTypeDef, out result);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void EnumCustomAttributes(int mdToken, out MetadataEnumResult result) 
         {
             Enum(MetadataTokenType.CustomAttribute, mdToken, out result);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void EnumParams(int mdMethodDef, out MetadataEnumResult result) 
         {
             Enum(MetadataTokenType.ParamDef, mdMethodDef, out result);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void EnumFields(int mdTypeDef, out MetadataEnumResult result)
         {
             Enum(MetadataTokenType.FieldDef, mdTypeDef, out result);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void EnumProperties(int mdTypeDef, out MetadataEnumResult result)
         {
             Enum(MetadataTokenType.Property, mdTypeDef, out result);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void EnumEvents(int mdTypeDef, out MetadataEnumResult result)
         {
             Enum(MetadataTokenType.Event, mdTypeDef, out result);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute (MethodImplOptions.InternalCall)]
         private static extern String _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType);
-        [System.Security.SecurityCritical]  // auto-generated
         public String GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType) 
         { 
             int _corElementType; 
@@ -410,10 +396,8 @@ namespace System.Reflection
             return stringVal;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute (MethodImplOptions.InternalCall)]
         private static unsafe extern void _GetUserString(IntPtr scope, int mdToken, void** name, out int length);
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe String GetUserString(int mdToken) 
         { 
             void* name;
@@ -436,10 +420,8 @@ namespace System.Reflection
             return new String(c);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute (MethodImplOptions.InternalCall)]
         private static unsafe extern void _GetName(IntPtr scope, int mdToken, void** name);
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe Utf8String GetName(int mdToken) 
         { 
             void* name;
@@ -448,10 +430,8 @@ namespace System.Reflection
             return new Utf8String(name);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute (MethodImplOptions.InternalCall)]
         private static unsafe extern void _GetNamespace(IntPtr scope, int mdToken, void** namesp);
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe Utf8String GetNamespace(int mdToken) 
         { 
             void* namesp;
@@ -460,10 +440,8 @@ namespace System.Reflection
             return new Utf8String(namesp);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute (MethodImplOptions.InternalCall)]
         private unsafe static extern void _GetEventProps(IntPtr scope, int mdToken, void** name, out int eventAttributes);
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes) 
         { 
             int _eventAttributes; 
@@ -473,10 +451,8 @@ namespace System.Reflection
             eventAttributes = (EventAttributes)_eventAttributes;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute (MethodImplOptions.InternalCall)]
         private static extern void _GetFieldDefProps(IntPtr scope, int mdToken, out int fieldAttributes);
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes) 
         { 
             int _fieldAttributes; 
@@ -484,11 +460,9 @@ namespace System.Reflection
             fieldAttributes = (FieldAttributes)_fieldAttributes;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute (MethodImplOptions.InternalCall)]
         private unsafe static extern void _GetPropertyProps(IntPtr scope, 
             int mdToken, void** name, out int propertyAttributes, out ConstArray signature);
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature) 
         { 
             int _propertyAttributes; 
@@ -498,11 +472,9 @@ namespace System.Reflection
             propertyAttributes = (PropertyAttributes)_propertyAttributes;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute (MethodImplOptions.InternalCall)]
         private static extern void _GetParentToken(IntPtr scope, 
             int mdToken, out int tkParent);
-        [System.Security.SecurityCritical]  // auto-generated
         public int GetParentToken(int tkToken) 
         { 
             int tkParent;
@@ -510,11 +482,9 @@ namespace System.Reflection
             return tkParent;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetParamDefProps(IntPtr scope, 
             int parameterToken, out int sequence, out int attributes);
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes)
         {
             int _attributes;
@@ -524,13 +494,11 @@ namespace System.Reflection
             attributes = (ParameterAttributes)_attributes;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetGenericParamProps(IntPtr scope, 
             int genericParameter, 
             out int flags);
         
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetGenericParamProps(
             int genericParameter, 
             out GenericParameterAttributes attributes)
@@ -540,12 +508,10 @@ namespace System.Reflection
             attributes = (GenericParameterAttributes)_attributes;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetScopeProps(IntPtr scope, 
             out Guid mvid);
         
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetScopeProps(
             out Guid mvid)
         {
@@ -553,7 +519,6 @@ namespace System.Reflection
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         public ConstArray GetMethodSignature(MetadataToken token)
         {
             if (token.IsMemberRef)
@@ -562,13 +527,11 @@ namespace System.Reflection
             return GetSigOfMethodDef(token);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetSigOfMethodDef(IntPtr scope, 
             int methodToken, 
             ref ConstArray signature);
         
-        [System.Security.SecurityCritical]  // auto-generated
         public ConstArray GetSigOfMethodDef(int methodToken)
         {
             ConstArray signature = new ConstArray();
@@ -578,13 +541,11 @@ namespace System.Reflection
             return signature;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetSignatureFromToken(IntPtr scope, 
             int methodToken, 
             ref ConstArray signature);
         
-        [System.Security.SecurityCritical]  // auto-generated
         public ConstArray GetSignatureFromToken(int token)
         {
             ConstArray signature = new ConstArray();
@@ -594,13 +555,11 @@ namespace System.Reflection
             return signature;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetMemberRefProps(IntPtr scope, 
             int memberTokenRef, 
             out ConstArray signature);
         
-        [System.Security.SecurityCritical]  // auto-generated
         public ConstArray GetMemberRefProps(int memberTokenRef)
         {
             ConstArray signature = new ConstArray();
@@ -610,14 +569,12 @@ namespace System.Reflection
             return signature;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetCustomAttributeProps(IntPtr scope, 
             int customAttributeToken, 
             out int constructorToken, 
             out ConstArray signature);
         
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetCustomAttributeProps( 
             int customAttributeToken, 
             out int constructorToken, 
@@ -627,11 +584,9 @@ namespace System.Reflection
                 out constructorToken, out signature);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetClassLayout(IntPtr scope, 
             int typeTokenDef, out int packSize, out int classSize);
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetClassLayout(
             int typeTokenDef, 
             out int packSize, 
@@ -640,11 +595,9 @@ namespace System.Reflection
             _GetClassLayout(m_metadataImport2, typeTokenDef, out packSize, out classSize);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool _GetFieldOffset(IntPtr scope, 
             int typeTokenDef, int fieldTokenDef, out int offset);
-        [System.Security.SecurityCritical]  // auto-generated
         public bool GetFieldOffset(
             int typeTokenDef, 
             int fieldTokenDef, 
@@ -653,13 +606,11 @@ namespace System.Reflection
             return _GetFieldOffset(m_metadataImport2, typeTokenDef, fieldTokenDef, out offset);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetSigOfFieldDef(IntPtr scope, 
             int fieldToken, 
             ref ConstArray fieldMarshal);
         
-        [System.Security.SecurityCritical]  // auto-generated
         public ConstArray GetSigOfFieldDef(int fieldToken)
         {
             ConstArray fieldMarshal = new ConstArray();
@@ -669,13 +620,11 @@ namespace System.Reflection
             return fieldMarshal;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetFieldMarshal(IntPtr scope, 
             int fieldToken, 
             ref ConstArray fieldMarshal);
         
-        [System.Security.SecurityCritical]  // auto-generated
         public ConstArray GetFieldMarshal(int fieldToken)
         {
             ConstArray fieldMarshal = new ConstArray();
@@ -685,7 +634,6 @@ namespace System.Reflection
             return fieldMarshal;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private unsafe static extern void _GetPInvokeMap(IntPtr scope, 
             int token, 
@@ -693,7 +641,6 @@ namespace System.Reflection
             void**  importName, 
             void**  importDll);
         
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe void GetPInvokeMap(
             int token, 
             out PInvokeAttributes attributes, 
@@ -709,10 +656,8 @@ namespace System.Reflection
             attributes = (PInvokeAttributes)_attributes;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool _IsValidToken(IntPtr scope, int token);        
-        [System.Security.SecurityCritical]  // auto-generated
         public bool IsValidToken(int token) 
         { 
             return _IsValidToken(m_metadataImport2, token); 
index 248c78b..96a89ad 100644 (file)
@@ -16,9 +16,6 @@ namespace System.Reflection
     [Serializable]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_MemberInfo))]
-#pragma warning disable 618
-    [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
     [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class MemberInfo : ICustomAttributeProvider, _MemberInfo
     {
@@ -116,33 +113,5 @@ namespace System.Reflection
         {
             return base.GetHashCode();
         }
-
-#if !FEATURE_CORECLR
-        // this method is required so Object.GetType is not made final virtual by the compiler
-        Type _MemberInfo.GetType()
-        { 
-            return base.GetType();
-        }
-
-        void _MemberInfo.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MemberInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MemberInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MemberInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 }
index ac524bd..20ff376 100644 (file)
@@ -86,7 +86,6 @@ namespace System.Reflection
         #endregion
 
         #region ISerializable
-        [System.Security.SecurityCritical]  // auto-generated
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context) 
         {
             throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Method));
@@ -94,7 +93,6 @@ namespace System.Reflection
         #endregion
     
         #region IObjectReference
-        [System.Security.SecurityCritical]  // auto-generated
         public virtual Object GetRealObject(StreamingContext context) 
         {
             if (m_memberName == null || m_reflectedType == null || m_memberType == 0)
index 7df9529..388e4f4 100644 (file)
@@ -11,7 +11,6 @@ namespace System.Reflection.Metadata
     public static class AssemblyExtensions
     {
         [DllImport(JitHelpers.QCall)]
-        [SecurityCritical] // unsafe method
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length);
@@ -24,7 +23,6 @@ namespace System.Reflection.Metadata
         //     associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the
         //     metadata blob.
         [CLSCompliant(false)] // out byte* blob
-        [SecurityCritical] // unsafe method
         public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length)
         {
             if (assembly == null)
index 6a9778b..644a1ac 100644 (file)
@@ -50,9 +50,6 @@ namespace System.Reflection
     [Serializable]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_MethodBase))]
-#pragma warning disable 618
-    [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
     [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class MethodBase : MemberInfo, _MethodBase
     {
@@ -131,7 +128,6 @@ namespace System.Reflection
 
         #region Internal Members
         // used by EE
-        [System.Security.SecurityCritical]
         private IntPtr GetMethodDesc() { return MethodHandle.Value; }
 
 #if FEATURE_APPX
@@ -243,7 +239,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecuritySafeCritical]
 #pragma warning disable 618
         [ReflectionPermissionAttribute(SecurityAction.Demand, Flags=ReflectionPermissionFlag.MemberAccess)]            
 #pragma warning restore 618
@@ -329,7 +324,6 @@ namespace System.Reflection
             return parameterTypes;
         }
 
-        [System.Security.SecuritySafeCritical]
         internal Object[] CheckArguments(Object[] parameters, Binder binder, 
             BindingFlags invokeAttr, CultureInfo culture, Signature sig)
         {
@@ -356,47 +350,5 @@ namespace System.Reflection
             return copyOfParameters;
         }
         #endregion
-
-        #region _MethodBase Implementation
-#if !FEATURE_CORECLR
-        Type _MethodBase.GetType() { return base.GetType(); }
-        bool _MethodBase.IsPublic { get { return IsPublic; } }
-        bool _MethodBase.IsPrivate { get { return IsPrivate; } }
-        bool _MethodBase.IsFamily { get { return IsFamily; } }
-        bool _MethodBase.IsAssembly { get { return IsAssembly; } }
-        bool _MethodBase.IsFamilyAndAssembly { get { return IsFamilyAndAssembly; } }
-        bool _MethodBase.IsFamilyOrAssembly { get { return IsFamilyOrAssembly; } }
-        bool _MethodBase.IsStatic { get { return IsStatic; } }
-        bool _MethodBase.IsFinal { get { return IsFinal; } }
-        bool _MethodBase.IsVirtual { get { return IsVirtual; } }
-        bool _MethodBase.IsHideBySig { get { return IsHideBySig; } }
-        bool _MethodBase.IsAbstract { get { return IsAbstract; } }
-        bool _MethodBase.IsSpecialName { get { return IsSpecialName; } }
-        bool _MethodBase.IsConstructor { get { return IsConstructor; } }
-
-        void _MethodBase.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MethodBase.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MethodBase.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        // If you implement this method, make sure to include _MethodBase.Invoke in VM\DangerousAPIs.h and 
-        // include _MethodBase in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
-        void _MethodBase.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-        #endregion
     }
-
 }
index 81d7a9e..4634623 100644 (file)
@@ -7,6 +7,7 @@
 using System;
 using System.Globalization;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Reflection
@@ -160,7 +161,7 @@ namespace System.Reflection
         #endregion
 
         #region Public Members
-        public virtual Type LocalType { get { Contract.Assert(m_type != null, "type must be set!"); return m_type; } }
+        public virtual Type LocalType { get { Debug.Assert(m_type != null, "type must be set!"); return m_type; } }
         public virtual bool IsPinned { get { return m_isPinned != 0; } }
         public virtual int LocalIndex { get { return m_localIndex; } }
         #endregion
index 8a67d42..39387b1 100644 (file)
@@ -14,9 +14,6 @@ namespace System.Reflection
     using System.Runtime;
     using System.Runtime.InteropServices;
     using System.Runtime.ConstrainedExecution;
-#if FEATURE_REMOTING
-    using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
     using System.Runtime.Serialization;
     using System.Security;
     using System.Security.Permissions;
@@ -29,9 +26,6 @@ namespace System.Reflection
     [Serializable]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_MethodInfo))]
-#pragma warning disable 618
-    [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
     [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class MethodInfo : MethodBase, _MethodInfo
     {
@@ -91,35 +85,6 @@ namespace System.Reflection
         public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
         public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
         #endregion
-
-#if !FEATURE_CORECLR
-        Type _MethodInfo.GetType()
-        {
-            return base.GetType();
-        }
-
-        void _MethodInfo.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MethodInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _MethodInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        // If you implement this method, make sure to include _MethodInfo.Invoke in VM\DangerousAPIs.h and 
-        // include _MethodInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
-        void _MethodInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 
     [Serializable]
@@ -180,7 +145,6 @@ namespace System.Reflection
 
         internal INVOCATION_FLAGS InvocationFlags
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
@@ -243,15 +207,14 @@ namespace System.Reflection
         #endregion
 
         #region Constructor
-        [System.Security.SecurityCritical]  // auto-generated
         internal RuntimeMethodInfo(
             RuntimeMethodHandleInternal handle, RuntimeType declaringType, 
             RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive)
         {
             Contract.Ensures(!m_handle.IsNull());
 
-            Contract.Assert(!handle.IsNullHandle());
-            Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));            
+            Debug.Assert(!handle.IsNullHandle());
+            Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));            
 
             m_bindingFlags = bindingFlags;
             m_declaringType = declaringType;
@@ -262,40 +225,9 @@ namespace System.Reflection
         }
         #endregion
 
-#if FEATURE_REMOTING
-        #region Legacy Remoting Cache
-        // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
-        // This member is currently being used by Remoting for caching remoting data. If you
-        // need to cache data here, talk to the Remoting team to work out a mechanism, so that
-        // both caching systems can happily work together.
-        private RemotingMethodCachedData m_cachedData;
-
-        internal RemotingMethodCachedData RemotingCache
-        {
-            get
-            {
-                // This grabs an internal copy of m_cachedData and uses
-                // that instead of looking at m_cachedData directly because
-                // the cache may get cleared asynchronously.  This prevents
-                // us from having to take a lock.
-                RemotingMethodCachedData cache = m_cachedData;
-                if (cache == null)
-                {
-                    cache = new RemotingMethodCachedData(this);
-                    RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
-                    if (ret != null)
-                        cache = ret;
-                }
-                return cache;
-            }
-        }
-        #endregion
-#endif //FEATURE_REMOTING
-
         #region Private Methods
         RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
                 return new RuntimeMethodHandleInternal(m_handle);
@@ -310,7 +242,6 @@ namespace System.Reflection
             } 
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private ParameterInfo[] FetchNonReturnParameters()
         {
             if (m_parameters == null)
@@ -319,7 +250,6 @@ namespace System.Reflection
             return m_parameters;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private ParameterInfo FetchReturnParameter()
         {
             if (m_returnParameter == null)
@@ -379,7 +309,6 @@ namespace System.Reflection
             return new RuntimeMethodHandle(this);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal RuntimeMethodInfo GetParentDefinition()
         {
             if (!IsVirtual || m_declaringType.IsInterface)
@@ -424,7 +353,6 @@ namespace System.Reflection
                 return base.GetHashCode();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool Equals(object obj)
         {
             if (!IsGenericMethod)
@@ -469,13 +397,11 @@ namespace System.Reflection
         #endregion
 
         #region ICustomAttributeProvider
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Object[] GetCustomAttributes(bool inherit)
         {
             return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
         {
             if (attributeType == null)
@@ -513,7 +439,6 @@ namespace System.Reflection
         #region MemberInfo Overrides
         public override String Name 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (m_name == null)
@@ -548,7 +473,6 @@ namespace System.Reflection
         public override MemberTypes MemberType { get { return MemberTypes.Method; } }
         public override int MetadataToken
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return RuntimeMethodHandle.GetMethodDef(this); }
         }        
         public override Module Module { get { return GetRuntimeModule(); } }
@@ -558,32 +482,19 @@ namespace System.Reflection
 
         public override bool IsSecurityCritical 
         {
-#if FEATURE_CORECLR
             get { return true; }
-#else
-            get { return RuntimeMethodHandle.IsSecurityCritical(this); }
-#endif
         }
         public override bool IsSecuritySafeCritical
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
-#endif
         }
         public override bool IsSecurityTransparent
         {
-#if FEATURE_CORECLR
             get { return false; }
-#else
-            get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
-#endif
         }
 #endregion
 
 #region MethodBase Overrides
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal override ParameterInfo[] GetParametersNoCopy()
         {
             FetchNonReturnParameters();
@@ -591,7 +502,6 @@ namespace System.Reflection
             return m_parameters;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Diagnostics.Contracts.Pure]
         public override ParameterInfo[] GetParameters()
         {
@@ -641,12 +551,6 @@ namespace System.Reflection
             } 
         }
 
-        [System.Security.SecuritySafeCritical] // overrides SafeCritical member
-#if !FEATURE_CORECLR
-#pragma warning disable 618
-        [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)]
-#pragma warning restore 618
-#endif
         public override MethodBody GetMethodBody()
         {
             MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
@@ -672,7 +576,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         private void ThrowNoInvokeException()
         {
             // method is ReflectionOnly
@@ -710,7 +613,6 @@ namespace System.Reflection
             throw new TargetException();
         }
         
-        [System.Security.SecuritySafeCritical]
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
@@ -730,23 +632,11 @@ namespace System.Reflection
                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
             }
 #endif
-
-#if !FEATURE_CORECLR
-            if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
-            {
-                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
-                    CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
-
-                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
-                    RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags);
-            }
-#endif // !FEATURE_CORECLR
 #endregion
 
             return UnsafeInvokeInternal(obj, parameters, arguments);
         }
 
-        [System.Security.SecurityCritical]
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
@@ -756,7 +646,6 @@ namespace System.Reflection
             return UnsafeInvokeInternal(obj, parameters, arguments);
         }
 
-        [System.Security.SecurityCritical]
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
@@ -820,7 +709,6 @@ namespace System.Reflection
 
         public override ParameterInfo ReturnParameter 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 Contract.Ensures(m_returnParameter != null);
@@ -830,7 +718,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override MethodInfo GetBaseDefinition()
         {
             if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
@@ -856,7 +743,6 @@ namespace System.Reflection
             return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
         }
 
-        [System.Security.SecuritySafeCritical]
         public override Delegate CreateDelegate(Type delegateType)
         {
             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -876,7 +762,6 @@ namespace System.Reflection
                 ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]
         public override Delegate CreateDelegate(Type delegateType, Object target)
         {
             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -893,7 +778,6 @@ namespace System.Reflection
                 ref stackMark);
         }
 
-        [System.Security.SecurityCritical]
         private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark)
         {
             // Validate the parameters.
@@ -920,7 +804,6 @@ namespace System.Reflection
 #endregion
 
 #region Generics
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
         {
           if (methodInstantiation == null)
@@ -1032,7 +915,6 @@ namespace System.Reflection
 #endregion
 
 #region ISerializable Implementation
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
index 8d93e1e..24bf77b 100644 (file)
@@ -24,7 +24,6 @@ namespace System.Reflection
         #endregion
 
         #region ISerializable
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
index e19a569..b6be38e 100644 (file)
@@ -59,9 +59,6 @@ namespace System.Reflection
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_Module))]
     [System.Runtime.InteropServices.ComVisible(true)]
-#pragma warning disable 618
-    [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
     public abstract class Module : _Module, ISerializable, ICustomAttributeProvider
     {   
         #region Static Constructor
@@ -274,7 +271,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             throw new NotImplementedException();
@@ -299,9 +295,6 @@ namespace System.Reflection
 
         public virtual String FullyQualifiedName 
         {
-#if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-#endif
             get
             {
                 throw new NotImplementedException();
@@ -543,36 +536,7 @@ namespace System.Reflection
         {
             return ModuleHandle.EmptyHandle;
         }
-
-#if FEATURE_X509 && FEATURE_CAS_POLICY
-        public virtual System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
-        {
-            throw new NotImplementedException();
-        }
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
         #endregion
-
-#if !FEATURE_CORECLR
-        void _Module.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 
     [Serializable]
@@ -581,46 +545,32 @@ namespace System.Reflection
         internal RuntimeModule() { throw new NotSupportedException(); }
 
         #region FCalls
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive);
 
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall)]
         [SuppressUnmanagedCodeSecurity]
         private static extern bool nIsTransientInternal(RuntimeModule module);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static RuntimeType[] GetTypes(RuntimeModule module);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal RuntimeType[] GetDefinedTypes()
         {
             return GetTypes(GetNativeHandle());
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static bool IsResource(RuntimeModule module);
-
-#if FEATURE_X509 && FEATURE_CAS_POLICY
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SuppressUnmanagedCodeSecurity]
-        static private extern void GetSignerCertificate(RuntimeModule module, ObjectHandleOnStack retData);
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
         #endregion
 
         #region Module overrides
@@ -646,7 +596,6 @@ namespace System.Reflection
             return typeHandleArgs;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override byte[] ResolveSignature(int metadataToken)
         {
             MetadataToken tk = new MetadataToken(metadataToken);
@@ -673,7 +622,6 @@ namespace System.Reflection
             return sig;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
         {
             MetadataToken tk = new MetadataToken(metadataToken);
@@ -724,7 +672,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
         {
             MetadataToken tk = new MetadataToken(metadataToken);
@@ -756,7 +703,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
         {
             MetadataToken tk = new MetadataToken(metadataToken);
@@ -811,7 +757,6 @@ namespace System.Reflection
             }           
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
         {
             MetadataToken tk = new MetadataToken(metadataToken);
@@ -844,7 +789,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
         {
             MetadataToken tk = new MetadataToken(metadataToken);
@@ -889,7 +833,6 @@ namespace System.Reflection
                 nameof(metadataToken));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override string ResolveString(int metadataToken)
         {
             MetadataToken tk = new MetadataToken(metadataToken);
@@ -917,7 +860,6 @@ namespace System.Reflection
 
         public override int MDStreamVersion
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return ModuleHandle.GetMDStreamVersion(GetNativeHandle());
@@ -973,7 +915,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         internal bool IsTransientInternal()
         {
             return RuntimeModule.nIsTransientInternal(this.GetNativeHandle());
@@ -981,7 +922,6 @@ namespace System.Reflection
         
         internal MetadataImport MetadataImport
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 unsafe
@@ -1012,7 +952,6 @@ namespace System.Reflection
             return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsDefined(Type attributeType, bool inherit)
         {
             if (attributeType == null)
@@ -1034,7 +973,6 @@ namespace System.Reflection
         #endregion
 
         #region Public Virtuals
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
@@ -1045,7 +983,6 @@ namespace System.Reflection
             UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly());
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         public override Type GetType(String className, bool throwOnError, bool ignoreCase)
         {
@@ -1060,7 +997,6 @@ namespace System.Reflection
             return retType;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal string GetFullyQualifiedName()
         {
             String fullyQualifiedName = null;
@@ -1070,11 +1006,6 @@ namespace System.Reflection
 
         public override String FullyQualifiedName
         {
-#if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-#else
-            [System.Security.SecuritySafeCritical]
-#endif
             get
             {
                 String fullyQualifiedName = GetFullyQualifiedName();
@@ -1096,7 +1027,6 @@ namespace System.Reflection
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Type[] GetTypes()
         {
             return GetTypes(GetNativeHandle());
@@ -1108,7 +1038,6 @@ namespace System.Reflection
 
         public override Guid ModuleVersionId
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 unsafe
@@ -1122,7 +1051,6 @@ namespace System.Reflection
 
         public override int MetadataToken
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return ModuleHandle.GetToken(GetNativeHandle());
@@ -1163,7 +1091,6 @@ namespace System.Reflection
 
         public override String ScopeName
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 string scopeName = null;
@@ -1174,7 +1101,6 @@ namespace System.Reflection
 
         public override String Name
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 String s = GetFullyQualifiedName();
@@ -1215,16 +1141,6 @@ namespace System.Reflection
         {
             return this;
         }
-
-#if FEATURE_X509 && FEATURE_CAS_POLICY
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
-        {
-            byte[] data = null;
-            GetSignerCertificate(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref data));
-            return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate(data) : null;
-        }
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
         #endregion
     }
 }
index 5186e69..6592e5a 100644 (file)
@@ -8,13 +8,11 @@ namespace System.Reflection
 {
     using System;
     using System.Collections.Generic;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Runtime.InteropServices;
     using System.Runtime.Serialization;
     using System.Runtime.CompilerServices;
-#if FEATURE_REMOTING
-    using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
     using System.Security.Permissions;
     using System.Threading;
     using MdToken = System.Reflection.MetadataToken;
@@ -180,35 +178,12 @@ namespace System.Reflection
 
         #region _ParameterInfo implementation
 
-#if !FEATURE_CORECLR
-        void _ParameterInfo.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ParameterInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ParameterInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _ParameterInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
         #endregion
 
         #region IObjectReference
         // In V4 RuntimeParameterInfo is introduced. 
         // To support deserializing ParameterInfo instances serialized in earlier versions
         // we need to implement IObjectReference.
-        [System.Security.SecurityCritical]
         public object GetRealObject(StreamingContext context)
         {
             Contract.Ensures(Contract.Result<Object>() != null);
@@ -261,26 +236,23 @@ namespace System.Reflection
     internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable
     {
         #region Static Members
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
         {
-            Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
+            Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
 
             ParameterInfo dummy;
             return GetParameters(method, member, sig, out dummy, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
         {
-            Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
+            Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
 
             ParameterInfo returnParameter;
             GetParameters(method, member, sig, out returnParameter, true);
             return returnParameter;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static ParameterInfo[] GetParameters(
             IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter)
         {
@@ -392,14 +364,13 @@ namespace System.Reflection
             get
             {
                 MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase;
-                Contract.Assert(result != null);
+                Debug.Assert(result != null);
                 return result;
             }
         }
         #endregion
 
         #region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints.
-        [System.Security.SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
@@ -450,7 +421,7 @@ namespace System.Reflection
             // The original owner should always be a method, because this method is only used to 
             // change the owner from a method to a property.
             m_originalMember = accessor.MemberImpl as MethodBase;
-            Contract.Assert(m_originalMember != null);
+            Debug.Assert(m_originalMember != null);
 
             // Populate all the caches -- we inherit this behavior from RTM
             NameImpl = accessor.Name;
@@ -470,8 +441,8 @@ namespace System.Reflection
             int position, ParameterAttributes attributes, MemberInfo member)
         {
             Contract.Requires(member != null);
-            Contract.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport));
-            Contract.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef));
+            Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport));
+            Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef));
 
             PositionImpl = position;
             MemberImpl = member;
@@ -513,7 +484,7 @@ namespace System.Reflection
                     else
                         parameterType = m_signature.Arguments[PositionImpl];
 
-                    Contract.Assert(parameterType != null);
+                    Debug.Assert(parameterType != null);
                     // different thread could only write ClassImpl to the same value, so a race condition is not a problem here
                     ClassImpl = parameterType;
                 }
@@ -524,7 +495,6 @@ namespace System.Reflection
 
         public override String Name
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (!m_nameIsCached)
@@ -588,10 +558,9 @@ namespace System.Reflection
         }
 
         // returns DBNull.Value if the parameter doesn't have a default value
-        [System.Security.SecuritySafeCritical]
         private Object GetDefaultValueInternal(bool raw)
         {
-            Contract.Assert(!m_noMetadata);
+            Debug.Assert(!m_noMetadata);
 
             if (m_noDefaultValue)
                 return DBNull.Value;
@@ -742,7 +711,6 @@ namespace System.Reflection
             return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsDefined(Type attributeType, bool inherit)
         {
             if (attributeType == null)
@@ -765,31 +733,5 @@ namespace System.Reflection
             return CustomAttributeData.GetCustomAttributesInternal(this);
         }
         #endregion
-
-#if FEATURE_REMOTING
-        #region Remoting Cache
-        private RemotingParameterCachedData m_cachedData;
-
-        internal RemotingParameterCachedData RemotingCache
-        {
-            get
-            {
-                // This grabs an internal copy of m_cachedData and uses
-                // that instead of looking at m_cachedData directly because
-                // the cache may get cleared asynchronously.  This prevents
-                // us from having to take a lock.
-                RemotingParameterCachedData cache = m_cachedData;
-                if (cache == null)
-                {
-                    cache = new RemotingParameterCachedData(this);
-                    RemotingParameterCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
-                    if (ret != null)
-                        cache = ret;
-                }
-                return cache;
-            }
-        }
-        #endregion
-#endif //FEATURE_REMOTING
     }
 }
index f0127ef..95025b2 100644 (file)
@@ -22,13 +22,11 @@ namespace System.Reflection {
     [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class Pointer : ISerializable
     {
-    [SecurityCritical]
         unsafe private void* _ptr;
         private RuntimeType _ptrType;
 
         private Pointer() {}
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe Pointer(SerializationInfo info, StreamingContext context)
         {
             _ptr = ((IntPtr)(info.GetValue("_ptr", typeof(IntPtr)))).ToPointer();
@@ -38,7 +36,6 @@ namespace System.Reflection {
         // This method will box an pointer.  We save both the
         //    value and the type so we can access it from the native code
         //    during an Invoke.
-        [System.Security.SecurityCritical]  // auto-generated
         public static unsafe Object Box(void *ptr,Type type) {
             if (type == null)
                 throw new ArgumentNullException(nameof(type));
@@ -57,7 +54,6 @@ namespace System.Reflection {
         }
 
         // Returned the stored pointer.
-        [System.Security.SecurityCritical]  // auto-generated
         public static unsafe void* Unbox(Object ptr) {
             if (!(ptr is Pointer))
                 throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(ptr));
@@ -68,12 +64,10 @@ namespace System.Reflection {
             return _ptrType;
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe Object GetPointerValue() {
             return (IntPtr)_ptr;
         }
 
-        [System.Security.SecurityCritical]
         unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
             info.AddValue("_ptr", new IntPtr(_ptr));
             info.AddValue("_ptrType", _ptrType);
index 88de1ed..e31b378 100644 (file)
@@ -22,9 +22,6 @@ namespace System.Reflection
     [Serializable]
     [ClassInterface(ClassInterfaceType.None)]
     [ComDefaultInterface(typeof(_PropertyInfo))]
-#pragma warning disable 618
-    [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
     [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class PropertyInfo : MemberInfo, _PropertyInfo
     {
@@ -153,35 +150,6 @@ namespace System.Reflection
 
         public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } }
         #endregion
-
-#if !FEATURE_CORECLR
-        Type _PropertyInfo.GetType()
-        {
-            return base.GetType();
-        }
-
-        void _PropertyInfo.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _PropertyInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _PropertyInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        // If you implement this method, make sure to include _PropertyInfo.Invoke in VM\DangerousAPIs.h and 
-        // include _PropertyInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
-        void _PropertyInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
     }
 
     [Serializable]
@@ -190,7 +158,6 @@ namespace System.Reflection
         #region Private Data Members
         private int m_token;
         private string m_name;
-        [System.Security.SecurityCritical]
         private void* m_utf8name;
         private PropertyAttributes m_flags;
         private RuntimeTypeCache m_reflectedTypeCache;
@@ -204,13 +171,12 @@ namespace System.Reflection
         #endregion
 
         #region Constructor
-        [System.Security.SecurityCritical]  // auto-generated
         internal RuntimePropertyInfo(
             int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
         {
             Contract.Requires(declaredType != null);
             Contract.Requires(reflectedTypeCache != null);
-            Contract.Assert(!reflectedTypeCache.IsGlobal);
+            Debug.Assert(!reflectedTypeCache.IsGlobal);
 
             MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
 
@@ -245,7 +211,6 @@ namespace System.Reflection
 
         internal Signature Signature
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (m_signature == null)
@@ -343,7 +308,6 @@ namespace System.Reflection
             return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsDefined(Type attributeType, bool inherit)
         {
             if (attributeType == null)
@@ -368,7 +332,6 @@ namespace System.Reflection
         public override MemberTypes MemberType { get { return MemberTypes.Property; } }
         public override String Name 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get 
             {
                 if (m_name == null)
@@ -421,7 +384,6 @@ namespace System.Reflection
             return Signature.GetCustomModifiers(0, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal object GetConstantValue(bool raw)
         {
             Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
@@ -630,7 +592,6 @@ namespace System.Reflection
         #endregion
 
         #region ISerializable Implementation
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
index 37c93eb..7068113 100644 (file)
@@ -65,7 +65,6 @@ namespace System.Reflection {
             get {return _exceptions;}
         }    
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
index 1a38faf..8107cf4 100644 (file)
@@ -26,9 +26,6 @@ namespace System.Reflection
     using System.Runtime.Versioning;
     using Microsoft.Win32;
     using System.Diagnostics.Contracts;
-#if !FEATURE_CORECLR
-    using Microsoft.Runtime.Hosting;
-#endif
 
     [Serializable]
     [System.Runtime.InteropServices.ComVisible(true)]
@@ -40,10 +37,6 @@ namespace System.Reflection
         private byte[]  _publicKey;
 
         // Build key pair from file.
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         public StrongNameKeyPair(FileStream keyPairFile)
         {
             if (keyPairFile == null)
@@ -58,10 +51,6 @@ namespace System.Reflection
         }
 
         // Build key pair from byte array in memory.
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         public StrongNameKeyPair(byte[] keyPairArray)
         {
             if (keyPairArray == null)
@@ -74,10 +63,6 @@ namespace System.Reflection
             _keyPairExported = true;
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         protected StrongNameKeyPair (SerializationInfo info, StreamingContext context) {
             _keyPairExported = (bool) info.GetValue("_keyPairExported", typeof(bool));
             _keyPairArray = (byte[]) info.GetValue("_keyPairArray", typeof(byte[]));
@@ -85,89 +70,6 @@ namespace System.Reflection
             _publicKey = (byte[]) info.GetValue("_publicKey", typeof(byte[]));
         }
 
-#if! FEATURE_CORECLR
-        // Reference key pair in named key container.
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
-        public StrongNameKeyPair(String keyPairContainer)
-        {
-            if (keyPairContainer == null)
-                throw new ArgumentNullException(nameof(keyPairContainer));
-            Contract.EndContractBlock();
-
-            _keyPairContainer = keyPairContainer;
-
-            _keyPairExported = false;
-        }
-
-        // Get the public portion of the key pair.
-        public byte[] PublicKey
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            get
-            {
-                if (_publicKey == null)
-                {
-                    _publicKey = ComputePublicKey();
-                }
-
-                byte[] publicKey = new byte[_publicKey.Length];
-                Array.Copy(_publicKey, publicKey, _publicKey.Length);
-
-                return publicKey;
-            }
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private unsafe byte[] ComputePublicKey()
-        {
-            byte[] publicKey = null;
-
-            // Make sure pbPublicKey is not leaked with async exceptions
-            RuntimeHelpers.PrepareConstrainedRegions();
-            try {
-            }
-            finally
-            {
-                IntPtr pbPublicKey = IntPtr.Zero;
-                int cbPublicKey = 0;
-
-                try
-                {
-                    bool result;
-                    if (_keyPairExported)
-                    {
-                        result = StrongNameHelpers.StrongNameGetPublicKey(null, _keyPairArray, _keyPairArray.Length,
-                            out pbPublicKey, out cbPublicKey);
-                    }
-                    else
-                    {
-                        result = StrongNameHelpers.StrongNameGetPublicKey(_keyPairContainer, null, 0,
-                            out pbPublicKey, out cbPublicKey);
-                    }
-                    if (!result)
-                        throw new ArgumentException(Environment.GetResourceString("Argument_StrongNameGetPublicKey"));
-
-                    publicKey = new byte[cbPublicKey];
-                    Buffer.Memcpy(publicKey, 0, (byte*)(pbPublicKey.ToPointer()), 0, cbPublicKey);
-                }
-                finally
-                {
-                    if (pbPublicKey != IntPtr.Zero)
-                        StrongNameHelpers.StrongNameFreeBuffer(pbPublicKey);
-                }
-            }
-            return publicKey;
-        }
-        // Internal routine used to retrieve key pair info from unmanaged code.
-        private bool GetKeyPair(out Object arrayOrContainer)
-        {
-            arrayOrContainer = _keyPairExported ? (Object)_keyPairArray : (Object)_keyPairContainer;
-            return _keyPairExported;
-        }
-#else
         public StrongNameKeyPair(String keyPairContainer)
         {
             throw new PlatformNotSupportedException();
@@ -181,10 +83,7 @@ namespace System.Reflection
             }
         }
 
-#endif// FEATURE_CORECLR
-
         /// <internalonly/>
-        [System.Security.SecurityCritical]
         void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {
             info.AddValue("_keyPairExported", _keyPairExported);
             info.AddValue("_keyPairArray", _keyPairArray);
@@ -194,6 +93,5 @@ namespace System.Reflection
 
         /// <internalonly/>
         void IDeserializationCallback.OnDeserialization (Object sender) {}
-
     }
 }
index e94cfa2..d715df8 100644 (file)
@@ -24,9 +24,6 @@ namespace System.Reflection {
 
         protected Type typeImpl;
         
-        #if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-        #endif
         protected TypeDelegator() {}
         
         public TypeDelegator(Type delegatingType) {
index efd949f..76bf000 100644 (file)
@@ -23,6 +23,7 @@ namespace System.Resources {
     using System.Runtime.Versioning;
     using System.Text;
     using System.Threading;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     internal class FileBasedResourceGroveler : IResourceGroveler
@@ -31,17 +32,16 @@ namespace System.Resources {
 
         public FileBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator)
         {
-            Contract.Assert(mediator != null, "mediator shouldn't be null; check caller");
+            Debug.Assert(mediator != null, "mediator shouldn't be null; check caller");
             _mediator = mediator;
         }
 
         // Consider modifying IResourceGroveler interface (hence this method signature) when we figure out 
         // serialization compat story for moving ResourceManager members to either file-based or 
         // manifest-based classes. Want to continue tightening the design to get rid of unused params.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark) 
         {
-            Contract.Assert(culture != null, "culture shouldn't be null; check caller");
+            Debug.Assert(culture != null, "culture shouldn't be null; check caller");
 
             String fileName = null;
             ResourceSet rs = null;
@@ -79,24 +79,6 @@ namespace System.Resources {
             }
         }
 
-#if !FEATURE_CORECLR   // PAL doesn't support eventing, and we don't compile event providers for coreclr
-        public bool HasNeutralResources(CultureInfo culture, String defaultResName)
-        {
-            // Detect missing neutral locale resources.
-            String defaultResPath = FindResourceFile(culture, defaultResName);
-            if (defaultResPath == null || !File.Exists(defaultResPath))
-            {
-                String dir = _mediator.ModuleDir;
-                if (defaultResPath != null)
-                {
-                    dir = Path.GetDirectoryName(defaultResPath);
-                }
-                return false;
-            }
-            return true;
-        }
-#endif
-
         // Given a CultureInfo, it generates the path &; file name for 
         // the .resources file for that CultureInfo.  This method will grovel
         // the disk looking for the correct file name & path.  Uses CultureInfo's
@@ -107,8 +89,8 @@ namespace System.Resources {
 
         private String FindResourceFile(CultureInfo culture, String fileName)
         {
-            Contract.Assert(culture != null, "culture shouldn't be null; check caller");
-            Contract.Assert(fileName != null, "fileName shouldn't be null; check caller");
+            Debug.Assert(culture != null, "culture shouldn't be null; check caller");
+            Debug.Assert(fileName != null, "fileName shouldn't be null; check caller");
 
             // If we have a moduleDir, check there first.  Get module fully 
             // qualified name, append path to that.
@@ -145,10 +127,9 @@ namespace System.Resources {
         // Constructs a new ResourceSet for a given file name.  The logic in
         // here avoids a ReflectionPermission check for our RuntimeResourceSet
         // for perf and working set reasons.
-        [System.Security.SecurityCritical]
         private ResourceSet CreateResourceSet(String file)
         {
-            Contract.Assert(file != null, "file shouldn't be null; check caller");
+            Debug.Assert(file != null, "file shouldn't be null; check caller");
 
             if (_mediator.UserResourceSet == null)
             {
index 983fd12..77c5c95 100644 (file)
@@ -23,10 +23,5 @@ namespace System.Resources {
     {
         ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, 
             bool createIfNotExists, ref StackCrawlMark stackMark);
-
-#if !FEATURE_CORECLR  // PAL doesn't support eventing, and we don't compile event providers for coreclr
-
-            bool HasNeutralResources(CultureInfo culture, String defaultResName);
-#endif
     }
 }
index 5fd0daa..78e961a 100644 (file)
@@ -26,13 +26,10 @@ namespace System.Resources {
     using System.Runtime.Versioning;
     using System.Text;
     using System.Threading;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using Microsoft.Win32;
 
-#if !FEATURE_CORECLR
-    using System.Diagnostics.Tracing;
-#endif
-
     //
     // Note: this type is integral to the construction of exception objects,
     // and sometimes this has to be done in low memory situtations (OOM) or
@@ -55,12 +52,11 @@ namespace System.Resources {
             _mediator = mediator;
         }
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
         public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
         {
-            Contract.Assert(culture != null, "culture shouldn't be null; check caller");
-            Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
+            Debug.Assert(culture != null, "culture shouldn't be null; check caller");
+            Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
 
             ResourceSet rs = null;
             Stream stream = null;
@@ -110,43 +106,15 @@ namespace System.Resources {
                 // want to add it twice.
                 lock (localResourceSets)
                 {
-                    if (localResourceSets.TryGetValue(culture.Name, out rs))
-                    {
-#if !FEATURE_CORECLR
-                        if (FrameworkEventSource.IsInitialized)
-                        {
-                            FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCacheUnexpected(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
-                        }
-#endif
-                    }
+                    localResourceSets.TryGetValue(culture.Name, out rs);
                 }
 
                 stream = GetManifestResourceStream(satellite, fileName, ref stackMark);
             }
 
-#if !FEATURE_CORECLR
-            if (FrameworkEventSource.IsInitialized)
-            {
-                if (stream != null)
-                {
-                    FrameworkEventSource.Log.ResourceManagerStreamFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
-                }
-                else
-                {
-                    FrameworkEventSource.Log.ResourceManagerStreamNotFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
-                }
-            }
-#endif
-
             // 4a. Found a stream; create a ResourceSet if possible
             if (createIfNotExists && stream != null && rs == null)
             {
-#if !FEATURE_CORECLR
-                if (FrameworkEventSource.IsInitialized)
-                {
-                    FrameworkEventSource.Log.ResourceManagerCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name, fileName);
-                }
-#endif
                 rs = CreateResourceSet(stream, satellite);
             }
             else if (stream == null && tryParents)
@@ -159,36 +127,9 @@ namespace System.Resources {
                 }
             }
 
-#if !FEATURE_CORECLR
-            if (!createIfNotExists && stream != null && rs == null) 
-            {
-                if (FrameworkEventSource.IsInitialized)
-                {
-                    FrameworkEventSource.Log.ResourceManagerNotCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
-                }
-            }
-#endif
-
             return rs;
         }
 
-#if !FEATURE_CORECLR
-        // Returns whether or not the main assembly contains a particular resource
-        // file in it's assembly manifest.  Used to verify that the neutral 
-        // Culture's .resources file is present in the main assembly
-        public bool HasNeutralResources(CultureInfo culture, String defaultResName)
-        {
-            String resName = defaultResName;
-            if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
-                resName = _mediator.LocationInfo.Namespace + Type.Delimiter + defaultResName;
-            String[] resourceFiles = _mediator.MainAssembly.GetManifestResourceNames();
-            foreach(String s in resourceFiles)
-                if (s.Equals(resName))
-                    return true;
-            return false;
-        }
-#endif
-
         private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture)
         {
 
@@ -199,13 +140,6 @@ namespace System.Resources {
             if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name &&
                 _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
             {
-#if !FEATURE_CORECLR
-                if (FrameworkEventSource.IsInitialized)
-                {
-                    FrameworkEventSource.Log.ResourceManagerNeutralResourcesSufficient(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name);
-                }
-#endif
-
                 returnCulture = CultureInfo.InvariantCulture;
             }
             else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)
@@ -214,13 +148,11 @@ namespace System.Resources {
             }
 
             return returnCulture;
-
         }
 
-        [System.Security.SecurityCritical]
         internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation)
         {
-            Contract.Assert(a != null, "assembly != null");
+            Debug.Assert(a != null, "assembly != null");
             string cultureName = null;
             short fallback = 0;
             if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(), 
@@ -232,11 +164,6 @@ namespace System.Resources {
                 fallbackLocation = (UltimateResourceFallbackLocation)fallback;
             }
             else {
-#if !FEATURE_CORECLR
-                if (FrameworkEventSource.IsInitialized) {
-                    FrameworkEventSource.Log.ResourceManagerNeutralResourceAttributeMissing(a);
-                }
-#endif
                 fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
                 return CultureInfo.InvariantCulture;
             }
@@ -253,7 +180,7 @@ namespace System.Resources {
                 // fires, please fix the build process for the BCL directory.
                 if (a == typeof(Object).Assembly)
                 {
-                    Contract.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\"  Exception: " + e);
+                    Debug.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\"  Exception: " + e);
                     return CultureInfo.InvariantCulture;
                 }
 
@@ -267,10 +194,9 @@ namespace System.Resources {
         // Use the assembly to resolve assembly manifest resource references.
         // Note that is can be null, but probably shouldn't be.
         // This method could use some refactoring. One thing at a time.
-        [System.Security.SecurityCritical]
         internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
         {
-            Contract.Assert(store != null, "I need a Stream!");
+            Debug.Assert(store != null, "I need a Stream!");
             // Check to see if this is a Stream the ResourceManager understands,
             // and check for the correct resource reader type.
             if (store.CanSeek && store.Length > 4)
@@ -350,7 +276,7 @@ namespace System.Resources {
                         Type resSetType;
                         if (_mediator.UserResourceSet == null)
                         {
-                            Contract.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
+                            Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
                             resSetType = Type.GetType(resSetTypeName, true, false);
                         }
                         else
@@ -413,7 +339,6 @@ namespace System.Resources {
             }
         }
 
-        [System.Security.SecurityCritical]
         private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark)
         {
             Contract.Requires(satellite != null, "satellite shouldn't be null; check caller");
@@ -437,7 +362,6 @@ namespace System.Resources {
         // case-insensitive lookup rules.  Yes, this is slow.  The metadata
         // dev lead refuses to make all assembly manifest resource lookups case-insensitive,
         // even optionally case-insensitive.        
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
         private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name)
         {
@@ -475,48 +399,19 @@ namespace System.Resources {
                 }
             }
 
-#if !FEATURE_CORECLR
-            if (FrameworkEventSource.IsInitialized)
-            {
-                if (canonicalName != null)
-                {
-                    FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName);
-                }
-                else
-                {
-                    FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupFailed(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName);
-                }
-            }
-#endif
-
             if (canonicalName == null)
             {
                 return null;
             }
+
             // If we're looking in the main assembly AND if the main
             // assembly was the person who created the ResourceManager,
             // skip a security check for private manifest resources.
             bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly;
             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-            Stream s = satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck);
-            // GetManifestResourceStream will return null if we don't have 
-            // permission to read this stream from the assembly.  For example,
-            // if the stream is private and we're trying to access it from another
-            // assembly (ie, ResMgr in mscorlib accessing anything else), we 
-            // require Reflection TypeInformation permission to be able to read 
-            // this. 
-#if !FEATURE_CORECLR
-            if (s!=null) {
-                if (FrameworkEventSource.IsInitialized)
-                {
-                    FrameworkEventSource.Log.ResourceManagerManifestResourceAccessDenied(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), canonicalName);
-                }
-            }
-#endif
-            return s;
+            return satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck);
         }
 
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
         private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark)
         {
@@ -548,30 +443,16 @@ namespace System.Resources {
                 int hr = fle._HResult;
                 if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED))
                 {
-                    Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
+                    Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
                 }
             }
 
             // Don't throw for zero-length satellite assemblies, for compat with v1
             catch (BadImageFormatException bife)
             {
-                Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
+                Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
             }
 
-#if !FEATURE_CORECLR
-            if (FrameworkEventSource.IsInitialized)
-            {
-                if (satellite != null)
-                {
-                    FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblySucceeded(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName);
-                }
-                else
-                {
-                    FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblyFailed(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName);
-                }
-            }
-#endif
-
             return satellite;
         }
 
@@ -583,8 +464,8 @@ namespace System.Resources {
         // and causes partially trusted localized apps to fail.
         private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName)
         {
-            Contract.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
-            Contract.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
+            Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
+            Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
 
             if (_mediator.UserResourceSet != null)
                 return false;
@@ -609,7 +490,6 @@ namespace System.Resources {
             return true;
         }
 
-        [System.Security.SecurityCritical]
         private String GetSatelliteAssemblyName()
         {
             String satAssemblyName = _mediator.MainAssembly.GetSimpleName();
@@ -617,7 +497,6 @@ namespace System.Resources {
             return satAssemblyName;
         }
 
-        [System.Security.SecurityCritical]
         private void HandleSatelliteMissing()
         {
             String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll";
@@ -646,14 +525,13 @@ namespace System.Resources {
             throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void HandleResourceStreamMissing(String fileName)
         {
             // Keep people from bothering me about resources problems
             if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name))
             {
                 // This would break CultureInfo & all our exceptions.
-                Contract.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine?  Chances are the BCL directory didn't build correctly.  Type 'build -c' in the BCL directory.  If you get build errors, look at buildd.log.  If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
+                Debug.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine?  Chances are the BCL directory didn't build correctly.  Type 'build -c' in the BCL directory.  If you get build errors, look at buildd.log.  If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
                 
                 // We cannot continue further - simply FailFast.
                 string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found!  Large parts of the BCL won't work!";
@@ -669,7 +547,6 @@ namespace System.Resources {
         }
 
             [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-            [System.Security.SecurityCritical]  // Our security team doesn't yet allow safe-critical P/Invoke methods.
             [System.Security.SuppressUnmanagedCodeSecurity]
             [return: MarshalAs(UnmanagedType.Bool)]
             internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation);
index def7836..de50ccc 100644 (file)
@@ -17,9 +17,6 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
-#if FEATURE_CORECLR
-using System.Diagnostics.Contracts;
-#endif
 using System.Globalization;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
@@ -33,8 +30,6 @@ namespace System.Resources
         private CultureInfo m_neutralResourcesCulture;
         private bool m_useParents;
 
-// Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
-#if FEATURE_CORECLR
         // 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.
@@ -43,7 +38,6 @@ namespace System.Resources
         // as well to avoid differences across threads.
         [ThreadStatic]
         private static CultureInfo[] cachedOsFallbackArray;
-#endif // FEATURE_CORECLR
 
         internal ResourceFallbackManager(CultureInfo startingCulture, CultureInfo neutralResourcesCulture, bool useParents)
         {
@@ -91,8 +85,6 @@ namespace System.Resources
                 yield break;
             }
 
-// Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
-#if FEATURE_CORECLR
             // 2. user preferred cultures, omitting starting culture if tried already
             //    Compat note: For console apps, this API will return cultures like Arabic
             //    or Hebrew that are displayed right-to-left.  These don't work with today's 
@@ -118,7 +110,6 @@ namespace System.Resources
                     }
                 }
             }
-#endif // FEATURE_CORECLR
 
             // 3. invariant
             //    Don't return invariant twice though.
@@ -128,8 +119,6 @@ namespace System.Resources
             yield return CultureInfo.InvariantCulture;
         }
 
-// Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
-#if FEATURE_CORECLR
         private static CultureInfo[] LoadPreferredCultures()
         {
             // The list of preferred cultures includes thread, process, user, and OS
@@ -190,7 +179,6 @@ namespace System.Resources
 
 
         // Note: May return null.
-        [System.Security.SecuritySafeCritical] // auto-generated
         private static String[] GetResourceFallbackArray()
         {
             // AppCompat note:  We've added this feature for desktop V4 but we ripped it out
@@ -272,7 +260,5 @@ namespace System.Resources
             return CultureInfo.nativeGetResourceFallbackArray();
 #endif
         }
-
-#endif // FEATURE_CORECLR
     }
 }
index 9de91a0..15f6af7 100644 (file)
@@ -30,10 +30,8 @@ namespace System.Resources {
     using Microsoft.Win32;
     using System.Collections.Generic;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
-#if !FEATURE_CORECLR
-    using System.Diagnostics.Tracing;
-#endif
 
 #if FEATURE_APPX
     //
@@ -45,21 +43,16 @@ namespace System.Resources {
     // Also using interface or abstract class will not play nice with FriendAccessAllowed.
     //
     [FriendAccessAllowed]
-    [SecurityCritical]
     internal class WindowsRuntimeResourceManagerBase
     {
-        [SecurityCritical]
         public virtual bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo){exceptionInfo = null; return false;}
 
-        [SecurityCritical]
         public virtual String GetString(String stringName, String startingCulture, String neutralResourcesCulture){return null;}
 
         public virtual CultureInfo GlobalResourceContextBestFitCultureInfo { 
-            [SecurityCritical]
             get { return null; } 
         }
         
-        [SecurityCritical]
         public virtual bool SetGlobalResourceContextDefaultCulture(CultureInfo ci) { return false; }
     }
 
@@ -266,13 +259,6 @@ namespace System.Resources {
 
         protected ResourceManager() 
         {
-#if !FEATURE_CORECLR
-            // This constructor is not designed to be used under AppX and is not in the Win8 profile.
-            // However designers may use them even if they are running under AppX since they are
-            // not subject to the restrictions of the Win8 profile.
-            Contract.Assert(!AppDomain.IsAppXModel() || AppDomain.IsAppXDesignMode());
-#endif
-
             Init();
 
             _lastUsedResourceCache = new CultureNameResourceSetPair();
@@ -297,13 +283,6 @@ namespace System.Resources {
                 throw new ArgumentNullException(nameof(resourceDir));
             Contract.EndContractBlock();
 
-#if !FEATURE_CORECLR
-            // This constructor is not designed to be used under AppX and is not in the Win8 profile.
-            // However designers may use them even if they are running under AppX since they are
-            // not subject to the restrictions of the Win8 profile.
-            Contract.Assert(!AppDomain.IsAppXModel() || AppDomain.IsAppXDesignMode());
-#endif
-
             BaseNameField = baseName;
 
             moduleDir = resourceDir;
@@ -317,22 +296,8 @@ namespace System.Resources {
 
             ResourceManagerMediator mediator = new ResourceManagerMediator(this);
             resourceGroveler = new FileBasedResourceGroveler(mediator);
-
-#if !FEATURE_CORECLR   // PAL doesn't support eventing, and we don't compile event providers for coreclr
-            if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled()) {
-                CultureInfo culture = CultureInfo.InvariantCulture;
-                String defaultResName = GetResourceFileName(culture);
-
-                if (resourceGroveler.HasNeutralResources(culture, defaultResName)) {
-                    FrameworkEventSource.Log.ResourceManagerNeutralResourcesFound(BaseNameField, MainAssembly, defaultResName);
-                }
-                else {
-                    FrameworkEventSource.Log.ResourceManagerNeutralResourcesNotFound(BaseNameField, MainAssembly, defaultResName);
-                }
-            }           
-#endif
         }
-    
+
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
         public ResourceManager(String baseName, Assembly assembly)
         {
@@ -373,13 +338,6 @@ namespace System.Resources {
                 throw new ArgumentNullException(nameof(assembly));
             Contract.EndContractBlock();
 
-#if !FEATURE_CORECLR
-            // This constructor is not designed to be used under AppX and is not in the Win8 profile.
-            // However designers may use them even if they are running under AppX since they are
-            // not subject to the restrictions of the Win8 profile.
-            Contract.Assert(!AppDomain.IsAppXModel() || AppDomain.IsAppXDesignMode());
-#endif
-
             if (!(assembly is RuntimeAssembly))
                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
 
@@ -434,7 +392,6 @@ namespace System.Resources {
             this._lastUsedResourceCache = null;
         }
 
-        [System.Security.SecuritySafeCritical]
         [OnDeserialized]
         private void OnDeserialized(StreamingContext ctx)
         {
@@ -479,7 +436,6 @@ namespace System.Resources {
 
         // Trying to unify code as much as possible, even though having to do a
         // security check in each constructor prevents it.
-        [System.Security.SecuritySafeCritical]
         private void CommonAssemblyInit()
         {
             if (_bUsingModernResourceManagement == false)
@@ -496,30 +452,6 @@ namespace System.Resources {
             }
 
             _neutralResourcesCulture = ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(MainAssembly, ref _fallbackLoc);
-
-#if !FEATURE_CORECLR   // PAL doesn't support eventing, and we don't compile event providers for coreclr
-            if (_bUsingModernResourceManagement == false)
-            {
-                if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled()) {
-                    CultureInfo culture = CultureInfo.InvariantCulture;
-                    String defaultResName = GetResourceFileName(culture);
-
-                    if (resourceGroveler.HasNeutralResources(culture, defaultResName)) {
-                        FrameworkEventSource.Log.ResourceManagerNeutralResourcesFound(BaseNameField, MainAssembly, defaultResName);
-                    }
-                    else {
-                        String outputResName = defaultResName;
-                        if (_locationInfo != null && _locationInfo.Namespace != null)
-                            outputResName = _locationInfo.Namespace + Type.Delimiter + defaultResName;
-                        FrameworkEventSource.Log.ResourceManagerNeutralResourcesNotFound(BaseNameField, MainAssembly, outputResName);
-                    }
-                }
-
-#pragma warning disable 618
-                ResourceSets = new Hashtable(); // for backward compatibility
-#pragma warning restore 618
-            }
-#endif
         }
 
         // Gets the base name for the ResourceManager.
@@ -557,12 +489,6 @@ namespace System.Resources {
         // creating a new ResourceManager isn't quite the correct behavior.
         public virtual void ReleaseAllResources()
         {
-#if !FEATURE_CORECLR
-            if (FrameworkEventSource.IsInitialized)
-            {
-                FrameworkEventSource.Log.ResourceManagerReleasingResources(BaseNameField, MainAssembly);
-            }
-#endif
             Dictionary<String, ResourceSet> localResourceSets = _resourceSets;
 
             // If any calls to Close throw, at least leave ourselves in a
@@ -573,27 +499,9 @@ namespace System.Resources {
             lock(localResourceSets) {
                 IDictionaryEnumerator setEnum = localResourceSets.GetEnumerator();
 
-#if !FEATURE_CORECLR
-                IDictionaryEnumerator setEnum2 = null;
-#pragma warning disable 618
-                if (ResourceSets != null) {
-                    setEnum2 = ResourceSets.GetEnumerator();
-                }
-                ResourceSets = new Hashtable(); // for backwards compat
-#pragma warning restore 618
-#endif
-
                 while (setEnum.MoveNext()) {
                     ((ResourceSet)setEnum.Value).Close();
                 }
-
-#if !FEATURE_CORECLR
-                if (setEnum2 != null) {
-                    while (setEnum2.MoveNext()) {
-                        ((ResourceSet)setEnum2.Value).Close();
-                    }
-                }
-#endif
             }
         }
 
@@ -677,7 +585,6 @@ namespace System.Resources {
         // if it hasn't yet been loaded and if parent CultureInfos should be 
         // loaded as well for resource inheritance.
         //         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
         public virtual ResourceSet GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) {
             if (null==culture)
@@ -721,11 +628,10 @@ namespace System.Resources {
         // for getting a resource set lives.  Access to it is controlled by
         // threadsafe methods such as GetResourceSet, GetString, & GetObject.  
         // This will take a minimal number of locks.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) 
         {
-            Contract.Assert(culture != null, "culture != null");
+            Debug.Assert(culture != null, "culture != null");
 
             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
             return InternalGetResourceSet(culture,createIfNotExists,tryParents, ref stackMark);
@@ -735,7 +641,6 @@ namespace System.Resources {
         // for getting a resource set lives.  Access to it is controlled by
         // threadsafe methods such as GetResourceSet, GetString, & GetObject.  
         // This will take a minimal number of locks.
-        [System.Security.SecurityCritical]
         private ResourceSet InternalGetResourceSet(CultureInfo requestedCulture, bool createIfNotExists, bool tryParents, ref StackCrawlMark stackMark)
         {
             Dictionary<String, ResourceSet> localResourceSets = _resourceSets;
@@ -743,11 +648,6 @@ namespace System.Resources {
             CultureInfo foundCulture = null;
             lock (localResourceSets) {
                 if (localResourceSets.TryGetValue(requestedCulture.Name, out rs)) {
-#if !FEATURE_CORECLR
-                    if (FrameworkEventSource.IsInitialized) {
-                        FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCache(BaseNameField, MainAssembly, requestedCulture.Name);
-                    }
-#endif
                     return rs;
                 }
             }
@@ -756,20 +656,8 @@ namespace System.Resources {
 
             foreach (CultureInfo currentCultureInfo in mgr)
             {
-#if !FEATURE_CORECLR
-                if (FrameworkEventSource.IsInitialized)
-                {
-                    FrameworkEventSource.Log.ResourceManagerLookingForResourceSet(BaseNameField, MainAssembly, currentCultureInfo.Name);
-                }
-#endif
                 lock(localResourceSets) {
                     if (localResourceSets.TryGetValue(currentCultureInfo.Name, out rs)) {
-#if !FEATURE_CORECLR
-                        if (FrameworkEventSource.IsInitialized)
-                        {
-                            FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCache(BaseNameField, MainAssembly, currentCultureInfo.Name);
-                        }
-#endif
                         // we need to update the cache if we fellback
                         if(requestedCulture != currentCultureInfo) foundCulture = currentCultureInfo;
                         break;
@@ -867,7 +755,7 @@ namespace System.Resources {
                 Object[] attrs = a.GetCustomAttributes(typeof(SatelliteContractVersionAttribute), false);
                 if (attrs.Length == 0)
                     return null;
-                Contract.Assert(attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!");
+                Debug.Assert(attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!");
                 v = ((SatelliteContractVersionAttribute)attrs[0]).Version;
             }
             Version ver;
@@ -880,7 +768,7 @@ namespace System.Resources {
                 // If this assert fires, please fix the build process for the
                 // BCL directory.
                 if (a == typeof(Object).Assembly) {
-                    Contract.Assert(false, System.CoreLib.Name+"'s SatelliteContractVersionAttribute is a malformed version string!");
+                    Debug.Assert(false, System.CoreLib.Name+"'s SatelliteContractVersionAttribute is a malformed version string!");
                     return null;
                 }
 
@@ -894,7 +782,6 @@ namespace System.Resources {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected static CultureInfo GetNeutralResourcesLanguage(Assembly a)
         {
             // This method should be obsolete - replace it with the one below.
@@ -909,7 +796,7 @@ namespace System.Resources {
                                           String typeName2, 
                                           AssemblyName asmName2)
         {
-            Contract.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null");
+            Debug.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null");
 
             // First, compare type names
             int comma = asmTypeName1.IndexOf(',');
@@ -961,13 +848,11 @@ namespace System.Resources {
         }
 
 #if FEATURE_APPX
-        [SecuritySafeCritical]
-        // Throws WinRT hresults
         private string GetStringFromPRI(String stringName, String startingCulture, String neutralResourcesCulture) {
-            Contract.Assert(_bUsingModernResourceManagement);
-            Contract.Assert(_WinRTResourceManager != null);
-            Contract.Assert(_PRIonAppXInitialized);
-            Contract.Assert(AppDomain.IsAppXModel());
+            Debug.Assert(_bUsingModernResourceManagement);
+            Debug.Assert(_WinRTResourceManager != null);
+            Debug.Assert(_PRIonAppXInitialized);
+            Debug.Assert(AppDomain.IsAppXModel());
         
             if (stringName.Length == 0)
                 return null;
@@ -987,7 +872,6 @@ namespace System.Resources {
         // Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the type via reflection.
         // It would be better if we could just implement WindowsRuntimeResourceManager in mscorlib, but we can't, because
         // we can do very little with WinRT in mscorlib.
-        [SecurityCritical]
         internal static WindowsRuntimeResourceManagerBase GetWinRTResourceManager()
         {
             Type WinRTResourceManagerType = Type.GetType("System.Resources.WindowsRuntimeResourceManager, " + AssemblyRef.SystemRuntimeWindowsRuntime, true);
@@ -1000,7 +884,6 @@ namespace System.Resources {
 
 #if FEATURE_APPX
         [NonSerialized]
-        [SecurityCritical]
         private WindowsRuntimeResourceManagerBase _WinRTResourceManager; // Written only by SetAppXConfiguration
 
         [NonSerialized]
@@ -1029,12 +912,10 @@ namespace System.Resources {
         //   
         //    b) For any other non-FX assembly, we will use the modern resource manager with the premise that app package
         //       contains the PRI resources.
-        [SecuritySafeCritical]
         private bool ShouldUseSatelliteAssemblyResourceLookupUnderAppX(RuntimeAssembly resourcesAssembly)
         {
             bool fUseSatelliteAssemblyResourceLookupUnderAppX = resourcesAssembly.IsFrameworkAssembly();
-            
-#if FEATURE_CORECLR     
+
             if (!fUseSatelliteAssemblyResourceLookupUnderAppX)
             {
                 // Check to see if the assembly is under PLATFORM_RESOURCE_ROOTS. If it is, then we should use satellite assembly lookup for it.
@@ -1055,23 +936,21 @@ namespace System.Resources {
                     }
                 }
             }
-#endif // FEATURE_CORECLR
+
             return fUseSatelliteAssemblyResourceLookupUnderAppX;
-            
         }
-        
-        [SecuritySafeCritical]
+
 #endif // FEATURE_APPX
         // Only call SetAppXConfiguration from ResourceManager constructors, and nowhere else.
         // Throws MissingManifestResourceException and WinRT HResults
 
         private void SetAppXConfiguration()
         {
-            Contract.Assert(_bUsingModernResourceManagement == false); // Only this function writes to this member
+            Debug.Assert(_bUsingModernResourceManagement == false); // Only this function writes to this member
 #if FEATURE_APPX
-            Contract.Assert(_WinRTResourceManager == null); // Only this function writes to this member
-            Contract.Assert(_PRIonAppXInitialized == false); // Only this function writes to this member
-            Contract.Assert(_PRIExceptionInfo == null); // Only this function writes to this member
+            Debug.Assert(_WinRTResourceManager == null); // Only this function writes to this member
+            Debug.Assert(_PRIonAppXInitialized == false); // Only this function writes to this member
+            Debug.Assert(_PRIExceptionInfo == null); // Only this function writes to this member
 
             bool bUsingSatelliteAssembliesUnderAppX = false;
 
@@ -1267,13 +1146,7 @@ namespace System.Resources {
                     // This line behaves the same way as CultureInfo.CurrentUICulture would have in .NET 4
                     culture = Thread.CurrentThread.GetCurrentUICultureNoAppX();
                 }
-    
-#if !FEATURE_CORECLR
-                if (FrameworkEventSource.IsInitialized)
-                {
-                    FrameworkEventSource.Log.ResourceManagerLookupStarted(BaseNameField, MainAssembly, culture.Name);
-                }
-#endif
+
                 ResourceSet last = GetFirstResourceSet(culture);
 
                 if (last != null)
@@ -1311,13 +1184,6 @@ namespace System.Resources {
                         last = rs;
                     }
                 }
-
-#if !FEATURE_CORECLR
-                if (FrameworkEventSource.IsInitialized)
-                {
-                    FrameworkEventSource.Log.ResourceManagerLookupFailed(BaseNameField, MainAssembly, culture.Name);
-                }
-#endif
             }
 
             return null;
@@ -1364,12 +1230,6 @@ namespace System.Resources {
                 culture = Thread.CurrentThread.GetCurrentUICultureNoAppX();
             }
 
-#if !FEATURE_CORECLR
-            if (FrameworkEventSource.IsInitialized)
-            {
-                FrameworkEventSource.Log.ResourceManagerLookupStarted(BaseNameField, MainAssembly, culture.Name);
-            }
-#endif
             ResourceSet last = GetFirstResourceSet(culture);
             if (last != null)
             {
@@ -1442,7 +1302,6 @@ namespace System.Resources {
 #if RESOURCE_SATELLITE_CONFIG
         // Internal helper method - gives an end user the ability to prevent
         // satellite assembly probes for certain cultures via a config file.
-        [System.Security.SecurityCritical]  // auto-generated
         private bool TryLookingForSatellite(CultureInfo lookForCulture)
         {
             if (!_checkedConfigFile) {
@@ -1470,7 +1329,6 @@ namespace System.Resources {
 
         // Note: There is one config file per appdomain.  This is not 
         // per-process nor per-assembly.
-        [System.Security.SecurityCritical]  // auto-generated
         private Hashtable GetSatelliteAssembliesFromConfig()
         {
             return null;
@@ -1566,7 +1424,6 @@ namespace System.Resources {
 
 
 #if RESOURCE_SATELLITE_CONFIG
-            [System.Security.SecurityCritical]  // auto-generated
             internal bool TryLookingForSatellite(CultureInfo lookForCulture)
             {
                 return _rm.TryLookingForSatellite(lookForCulture);
index 64b0f0b..89cfdb1 100644 (file)
@@ -31,6 +31,7 @@ namespace System.Resources {
     using System.Globalization;
     using System.Configuration.Assemblies;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // Provides the default implementation of IResourceReader, reading
@@ -66,7 +67,7 @@ namespace System.Resources {
 
         internal static bool CanCache(ResourceTypeCode value)
         {
-            Contract.Assert(value >= 0, "negative ResourceTypeCode.  What?");
+            Debug.Assert(value >= 0, "negative ResourceTypeCode.  What?");
             return value <= ResourceTypeCode.LastPrimitive;
         }   
     }
@@ -94,10 +95,8 @@ namespace System.Resources {
         // of the assembly.  The pointers here are pointers into that block of
         // memory controlled by the OS's loader.
         private int[] _nameHashes;    // hash values for all names.
-        [SecurityCritical]
         private unsafe int* _nameHashesPtr;  // In case we're using UnmanagedMemoryStream
         private int[] _namePositions; // relative locations of names
-        [SecurityCritical]
         private unsafe int* _namePositionsPtr;  // If we're using UnmanagedMemoryStream
         private RuntimeType[] _typeTable;    // Lazy array of Types for resource values.
         private int[] _typeNamePositions;  // To delay initialize type table
@@ -152,11 +151,6 @@ namespace System.Resources {
         };
 #endif // FEATURE_SERIALIZATION
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
         public ResourceReader(String fileName)
         {
             _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
@@ -172,7 +166,6 @@ namespace System.Resources {
             }
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public ResourceReader(Stream stream)
         {
             if (stream==null)
@@ -194,7 +187,6 @@ namespace System.Resources {
         // passing in the stream to read from and the RuntimeResourceSet's 
         // internal hash table (hash table of names with file offsets
         // and values, coupled to this ResourceReader).
-        [System.Security.SecurityCritical]  // auto-generated
         internal ResourceReader(Stream stream, Dictionary<String, ResourceLocator> resCache)
         {
             Contract.Requires(stream != null, "Need a stream!");
@@ -221,7 +213,6 @@ namespace System.Resources {
             Close();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe void Dispose(bool disposing)
         {
             if (_store != null) {
@@ -243,7 +234,6 @@ namespace System.Resources {
             }
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal static unsafe int ReadUnalignedI4(int* p)
         {
             byte* buffer = (byte*)p;
@@ -264,11 +254,10 @@ namespace System.Resources {
             _store.BaseStream.Seek(stringLength, SeekOrigin.Current);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe int GetNameHash(int index)
         {
-            Contract.Assert(index >=0 && index < _numResources, "Bad index into hash array.  index: "+index);
-            Contract.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) || 
+            Debug.Assert(index >=0 && index < _numResources, "Bad index into hash array.  index: "+index);
+            Debug.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) || 
                             (_ums != null && _nameHashes == null && _nameHashesPtr != null), "Internal state mangled.");
             if (_ums == null)
                 return _nameHashes[index];
@@ -276,11 +265,10 @@ namespace System.Resources {
                 return ReadUnalignedI4(&_nameHashesPtr[index]);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe int GetNamePosition(int index)
         {
-            Contract.Assert(index >=0 && index < _numResources, "Bad index into name position array.  index: "+index);
-            Contract.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) || 
+            Debug.Assert(index >=0 && index < _numResources, "Bad index into name position array.  index: "+index);
+            Debug.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) || 
                             (_ums != null && _namePositions == null && _namePositionsPtr != null), "Internal state mangled.");
             int r;
             if (_ums == null)
@@ -316,7 +304,7 @@ namespace System.Resources {
         // This does a binary search through the names.
         internal int FindPosForResource(String name)
         {
-            Contract.Assert(_store != null, "ResourceReader is closed!");
+            Debug.Assert(_store != null, "ResourceReader is closed!");
             int hash = FastResourceComparer.HashFunction(name);
             BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for "+name+"  hash: "+hash.ToString("x", CultureInfo.InvariantCulture));
             // Binary search over the hashes.  Use the _namePositions array to 
@@ -395,10 +383,9 @@ namespace System.Resources {
         // with the string you pass in. 
         // Whoever calls this method should make sure that they take a lock
         // so no one else can cause us to seek in the stream.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe bool CompareStringEqualsName(String name)
         {
-            Contract.Assert(_store != null, "ResourceReader is closed!");
+            Debug.Assert(_store != null, "ResourceReader is closed!");
             int byteLen = _store.Read7BitEncodedInt();
             if (byteLen < 0) {
                 throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength"));
@@ -433,10 +420,9 @@ namespace System.Resources {
         // This is used in the enumerator.  The enumerator iterates from 0 to n
         // of our resources and this returns the resource name for a particular
         // index.  The parameter is NOT a virtual offset.
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe String AllocateStringForNameIndex(int index, out int dataOffset)
         {
-            Contract.Assert(_store != null, "ResourceReader is closed!");
+            Debug.Assert(_store != null, "ResourceReader is closed!");
             byte[] bytes;
             int byteLen;
             long nameVA = GetNamePosition(index);
@@ -500,7 +486,7 @@ namespace System.Resources {
         // index.  The parameter is NOT a virtual offset.
         private Object GetValueForNameIndex(int index)
         {
-            Contract.Assert(_store != null, "ResourceReader is closed!");
+            Debug.Assert(_store != null, "ResourceReader is closed!");
             long nameVA = GetNamePosition(index);
             lock(this) {
                 _store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
@@ -525,7 +511,7 @@ namespace System.Resources {
         // no one can cause us to do a seek in here.
         internal String LoadString(int pos)
         {
-            Contract.Assert(_store != null, "ResourceReader is closed!");
+            Debug.Assert(_store != null, "ResourceReader is closed!");
             _store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
             String s = null;
             int typeIndex = _store.Read7BitEncodedInt();
@@ -578,8 +564,8 @@ namespace System.Resources {
         // no one can cause us to do a seek in here.
         internal Object LoadObjectV1(int pos)
         {
-            Contract.Assert(_store != null, "ResourceReader is closed!");
-            Contract.Assert(_version == 1, ".resources file was not a V1 .resources file!");
+            Debug.Assert(_store != null, "ResourceReader is closed!");
+            Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!");
 
             try {
                 // mega try-catch performs exceptionally bad on x64; factored out body into 
@@ -595,7 +581,6 @@ namespace System.Resources {
         }
 
 #if FEATURE_SERIALIZATION
-        [SecuritySafeCritical]
 #endif
         private Object _LoadObjectV1(int pos) {
             _store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
@@ -654,8 +639,8 @@ namespace System.Resources {
 
         internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode)
         {
-            Contract.Assert(_store != null, "ResourceReader is closed!");
-            Contract.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!");
+            Debug.Assert(_store != null, "ResourceReader is closed!");
+            Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!");
 
             try {
                 // mega try-catch performs exceptionally bad on x64; factored out body into 
@@ -670,7 +655,6 @@ namespace System.Resources {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private Object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) {
             _store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
             typeCode = (ResourceTypeCode) _store.Read7BitEncodedInt();
@@ -752,7 +736,7 @@ namespace System.Resources {
 
                     byte[] bytes = new byte[len];
                     int r = _ums.Read(bytes, 0, len);
-                    Contract.Assert(r == len, "ResourceReader needs to use a blocking read here.  (Call _store.ReadBytes(len)?)");
+                    Debug.Assert(r == len, "ResourceReader needs to use a blocking read here.  (Call _store.ReadBytes(len)?)");
                     return bytes;
                 }
 
@@ -801,7 +785,6 @@ namespace System.Resources {
         // deserialization binder to simulate a type-limiting deserializer.
         // This method handles types that are safe to deserialize, as well as
         // ensuring we only get back what we expect.
-        [System.Security.SecurityCritical]  // auto-generated
         private Object DeserializeObject(int typeIndex)
         {
             RuntimeType type = FindType(typeIndex);
@@ -843,10 +826,9 @@ namespace System.Resources {
         // Reads in the header information for a .resources file.  Verifies some
         // of the assumptions about this resource set, and builds the class table
         // for the default resource file format.
-        [System.Security.SecurityCritical]  // auto-generated
         private void ReadResources()
         {
-            Contract.Assert(_store != null, "ResourceReader is closed!");
+            Debug.Assert(_store != null, "ResourceReader is closed!");
 #if FEATURE_SERIALIZATION
             BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence));
             _typeLimitingBinder = new TypeLimitingDeserializationBinder();
@@ -867,7 +849,6 @@ namespace System.Resources {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void _ReadResources()
         {
             // Read ResourceManager header
@@ -1088,12 +1069,11 @@ namespace System.Resources {
                     _store.BaseStream.Position = oldPos;
                 }
             }
-            Contract.Assert(_typeTable[typeIndex] != null, "Should have found a type!");
+            Debug.Assert(_typeTable[typeIndex] != null, "Should have found a type!");
             return _typeTable[typeIndex];
         }
 
 #if FEATURE_SERIALIZATION
-        [System.Security.SecurityCritical]  // auto-generated
         private void InitSafeToDeserializeArray()
         {
             _safeToDeserialize = new bool[_typeTable.Length];
@@ -1200,10 +1180,10 @@ namespace System.Resources {
                 Array.Sort(sortedDataPositions);
 
                 int index = Array.BinarySearch(sortedDataPositions, dataPos);
-                Contract.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!");
+                Debug.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!");
                 long nextData = (index < _numResources - 1) ? sortedDataPositions[index + 1] + _dataSectionOffset : _store.BaseStream.Length;
                 int len = (int) (nextData - (dataPos + _dataSectionOffset));
-                Contract.Assert(len >= 0 && len <= (int) _store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!");
+                Debug.Assert(len >= 0 && len <= (int) _store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!");
 
                 // Read type code then byte[]
                 _store.BaseStream.Position = _dataSectionOffset + dataPos;
@@ -1227,12 +1207,12 @@ namespace System.Resources {
         {
             Contract.Requires(typeCode >= 0, "can't be negative");
             if (typeCode < ResourceTypeCode.StartOfUserTypes) {
-                Contract.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers.");
+                Debug.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers.");
                 return "ResourceTypeCode." + typeCode.ToString();
             }
             else {
                 int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes;
-                Contract.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!");
+                Debug.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!");
                 long oldPos = _store.BaseStream.Position;
                 try {
                     _store.BaseStream.Position = _typeNamePositions[typeIndex];
@@ -1277,7 +1257,6 @@ namespace System.Resources {
                 _typeToDeserialize = type;
             }
             
-            [System.Security.SecuritySafeCritical] // overrides transparent public member
             public override Type BindToType(string assemblyName, string typeName)
             {
                 // BinaryObjectReader::Bind tries us first, then its own code.
@@ -1343,7 +1322,6 @@ namespace System.Resources {
             }
         
             public Object Key {
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 get {
                     if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
                     if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
@@ -1367,7 +1345,6 @@ namespace System.Resources {
             }
 
             public DictionaryEntry Entry {
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 get {
                     if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
                     if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
index 314cb8d..1b272fc 100644 (file)
@@ -31,15 +31,11 @@ namespace System.Resources {
     // stores them in a hash table.  Custom IResourceReaders can be used.
     // 
     [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public class ResourceSet : IDisposable, IEnumerable
     {
         [NonSerialized] protected IResourceReader Reader;
-#if FEATURE_CORECLR
         internal Hashtable Table;
-#else
-        protected Hashtable Table;
-#endif
 
         private Hashtable _caseInsensitiveTable;  // For case-insensitive lookups.
 
@@ -65,9 +61,6 @@ namespace System.Resources {
         // implementation.  Use this constructor to open & read from a file 
         // on disk.
         // 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public ResourceSet(String fileName)
         {
             Reader = new ResourceReader(fileName);
@@ -89,7 +82,6 @@ namespace System.Resources {
         // implementation.  Use this constructor to read from an open stream 
         // of data.
         // 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public ResourceSet(Stream stream)
         {
             Reader = new ResourceReader(stream);
@@ -98,7 +90,6 @@ namespace System.Resources {
         }
 
 #if LOOSELY_LINKED_RESOURCE_REFERENCE
-        [System.Security.SecurityCritical]  // auto_generated_required
         public ResourceSet(Stream stream, Assembly assembly)
         {
             Reader = new ResourceReader(stream);
@@ -187,11 +178,7 @@ namespace System.Resources {
         // GetDefaultReader and GetDefaultWriter.
         public virtual Type GetDefaultWriter()
         {
-#if FEATURE_CORECLR
             return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, throwOnError: true);
-#else
-            return typeof(ResourceWriter);
-#endif
         }
 
         [ComVisible(false)]
index 7c7414c..a94ac82 100644 (file)
@@ -20,6 +20,7 @@ namespace System.Resources {
     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 
@@ -184,7 +185,6 @@ namespace System.Resources {
         // the resources once, adding them into the table.
         private bool _haveReadFromReader;
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal RuntimeResourceSet(String fileName) : base(false)
         {
             BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(String)");
@@ -204,7 +204,6 @@ namespace System.Resources {
             Assembly = assembly;
         }
 #else
-        [System.Security.SecurityCritical]  // auto-generated
         internal RuntimeResourceSet(Stream stream) : base(false)
         {
             BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(Stream)");
@@ -312,7 +311,7 @@ namespace System.Resources {
                     }
 
                     if (dataPos != -1 && value == null) {
-                        Contract.Assert(dataPos >= 0, "data section offset cannot be negative!");
+                        Debug.Assert(dataPos >= 0, "data section offset cannot be negative!");
                         // Normally calling LoadString or LoadObject requires
                         // taking a lock.  Note that in this case, we took a
                         // lock on the entire RuntimeResourceSet, which is 
@@ -373,7 +372,7 @@ namespace System.Resources {
                             Reader.Close();
                     }
                     else {
-                        Contract.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
+                        Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
                         ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
                         while (en.MoveNext()) {
                             // Note: Always ask for the resource key before the data position.
index 5bc7333..e0911fa 100644 (file)
@@ -17,6 +17,7 @@ namespace System.Resources {
     using System;
     using System.Collections;
     using System.Collections.Generic;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer<String>, IEqualityComparer<String>
@@ -78,11 +79,10 @@ namespace System.Resources {
 
         // Input is one string to compare with, and a byte[] containing chars in 
         // little endian unicode.  Pass in the number of valid chars.
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe static int CompareOrdinal(String a, byte[] bytes, int bCharLength)
         {
-            Contract.Assert(a != null && bytes != null, "FastResourceComparer::CompareOrdinal must have non-null params");
-            Contract.Assert(bCharLength * 2 <= bytes.Length, "FastResourceComparer::CompareOrdinal - numChars is too big!");
+            Debug.Assert(a != null && bytes != null, "FastResourceComparer::CompareOrdinal must have non-null params");
+            Debug.Assert(bCharLength * 2 <= bytes.Length, "FastResourceComparer::CompareOrdinal - numChars is too big!");
             // This is a managed version of strcmp, but I can't take advantage
             // of a terminating 0, unlike strcmp in C.
             int i = 0;
@@ -107,7 +107,6 @@ namespace System.Resources {
             return a.Length - bCharLength;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public static int CompareOrdinal(byte[] bytes, int aCharLength, String b)
         {
             return -CompareOrdinal(b, bytes, aCharLength);
@@ -115,12 +114,11 @@ namespace System.Resources {
 
         // This method is to handle potentially misaligned data accesses.
         // The byte* must point to little endian Unicode characters.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static int CompareOrdinal(byte* a, int byteLen, String b)
         {
-            Contract.Assert((byteLen & 1) == 0, "CompareOrdinal is expecting a UTF-16 string length, which must be even!");
-            Contract.Assert(a != null && b != null, "Null args not allowed.");
-            Contract.Assert(byteLen >= 0, "byteLen must be non-negative.");
+            Debug.Assert((byteLen & 1) == 0, "CompareOrdinal is expecting a UTF-16 string length, which must be even!");
+            Debug.Assert(a != null && b != null, "Null args not allowed.");
+            Debug.Assert(byteLen >= 0, "byteLen must be non-negative.");
 
             int r = 0;
             int i = 0;
index 6558338..168beef 100644 (file)
@@ -25,12 +25,6 @@ using System.Runtime.CompilerServices;
 using System.Security;
 using System.Text;
 using System.Runtime.Remoting;
-#if FEATURE_REMOTING
-using System.Runtime.Remoting.Proxies;
-using System.Runtime.Remoting.Messaging;
-using System.Runtime.Remoting.Activation;
-using System.Runtime.Remoting.Metadata;
-#endif
 using MdSigCallingConvention = System.Signature.MdSigCallingConvention;
 using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
 using System.Runtime.InteropServices;
@@ -203,7 +197,6 @@ namespace System
                 private MemberListType m_listType;
                 private uint m_nameHash;
 
-                [System.Security.SecurityCritical]  // auto-generated
                 public unsafe Filter(byte* pUtf8Name, int cUtf8Name, MemberListType listType)
                 {
                     this.m_name = new Utf8String((void*) pUtf8Name, cUtf8Name);
@@ -227,7 +220,7 @@ namespace System
 
                     // Currently the callers of UsesStringComparison assume that if it returns false
                     // then the match always succeeds and can be skipped.  Assert that this is maintained.
-                    Contract.Assert(retVal || RequiresStringComparison());
+                    Debug.Assert(retVal || RequiresStringComparison());
 
                     return retVal;
                 }
@@ -248,7 +241,7 @@ namespace System
 
                 public uint GetHashToMatch()
                 {
-                    Contract.Assert(RequiresStringComparison());
+                    Debug.Assert(RequiresStringComparison());
 
                     return m_nameHash;
                 }
@@ -272,7 +265,6 @@ namespace System
 
                 #region Constructor
 #if MDA_SUPPORTED
-                [System.Security.SecuritySafeCritical]  // auto-generated
 #endif
                 internal MemberInfoCache(RuntimeTypeCache runtimeTypeCache)
                 {
@@ -282,7 +274,6 @@ namespace System
                     m_runtimeTypeCache = runtimeTypeCache;
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 internal MethodBase AddMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method, CacheType cacheType)
                 {
                     T[] list = null;
@@ -310,7 +301,6 @@ namespace System
                     return (MethodBase)(object)list[0];
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 internal FieldInfo AddField(RuntimeFieldHandleInternal field)
                 {
                     // create the runtime field info
@@ -333,7 +323,6 @@ namespace System
                     return (FieldInfo)(object)list[0];
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe T[] Populate(string name, MemberListType listType, CacheType cacheType)
                 {
                     T[] list = null;
@@ -372,7 +361,6 @@ namespace System
                     return list;
                 }
 
-                [System.Security.SecurityCritical]  // auto-generated
                 private unsafe T[] GetListByName(char* pName, int cNameLen, byte* pUtf8Name, int cUtf8Name, MemberListType listType, CacheType cacheType)
                 {
                     if (cNameLen != 0)
@@ -415,7 +403,6 @@ namespace System
                 // May replace the list with a new one if certain cache
                 // lookups succeed.  Also, may modify the contents of the list
                 // after merging these new data structures with cached ones.
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
                 internal void Insert(ref T[] list, string name, MemberListType listType)
                 {
@@ -545,7 +532,7 @@ namespace System
                                     // Grow the list by exactly one element in this case to avoid null entries at the end.
                                     //
 
-                                    Contract.Assert(false);
+                                    Debug.Assert(false);
 
                                     newSize = cachedMembers.Length + 1;
                                 }
@@ -560,7 +547,7 @@ namespace System
                                 cachedMembers = cachedMembers2;
                             }
 
-                            Contract.Assert(cachedMembers[freeSlotIndex] == null);
+                            Debug.Assert(cachedMembers[freeSlotIndex] == null);
                             cachedMembers[freeSlotIndex] = newMemberInfo;
                             freeSlotIndex++;
                         }
@@ -572,13 +559,12 @@ namespace System
 
                 #region Population Logic
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe RuntimeMethodInfo[] PopulateMethods(Filter filter)
                 {
                     ListBuilder<RuntimeMethodInfo> list = new ListBuilder<RuntimeMethodInfo>();
 
                     RuntimeType declaringType = ReflectedType;
-                    Contract.Assert(declaringType != null);
+                    Debug.Assert(declaringType != null);
 
                     if (RuntimeTypeHandle.IsInterface(declaringType))
                     {
@@ -590,7 +576,7 @@ namespace System
                             {
                                 if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
                                 {
-                                    Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
+                                    Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
                                     continue;
                                 }
 
@@ -599,10 +585,10 @@ namespace System
                             }
 
                             #region Loop through all methods on the interface
-                            Contract.Assert(!methodHandle.IsNullHandle());
+                            Debug.Assert(!methodHandle.IsNullHandle());
                             // Except for .ctor, .cctor, IL_STUB*, and static methods, all interface methods should be abstract, virtual, and non-RTSpecialName.
                             // Note that this assumption will become invalid when we add support for non-abstract or static methods on interfaces.
-                            Contract.Assert(
+                            Debug.Assert(
                                 (RuntimeMethodHandle.GetAttributes(methodHandle) & (MethodAttributes.RTSpecialName | MethodAttributes.Abstract | MethodAttributes.Virtual)) == (MethodAttributes.Abstract | MethodAttributes.Virtual) ||
                                 (RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.Static) == MethodAttributes.Static ||
                                 RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") ||
@@ -650,7 +636,7 @@ namespace System
                                 {
                                     if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
                                     {
-                                        Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
+                                        Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
                                         continue;
                                     }
 
@@ -659,13 +645,13 @@ namespace System
                                 }
 
                                 #region Loop through all methods on the current type
-                                Contract.Assert(!methodHandle.IsNullHandle());
+                                Debug.Assert(!methodHandle.IsNullHandle());
 
                                 MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle);
                                 MethodAttributes methodAccess = methodAttributes & MethodAttributes.MemberAccessMask;
 
                                 #region Continue if this is a constructor
-                                Contract.Assert(
+                                Debug.Assert(
                                     (RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.RTSpecialName) == 0 ||
                                     RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") ||
                                     RuntimeMethodHandle.GetName(methodHandle).Equals(".cctor"));
@@ -697,7 +683,7 @@ namespace System
                                 #region Continue if this is a virtual and is already overridden
                                 if (isVirtual)
                                 {
-                                    Contract.Assert(
+                                    Debug.Assert(
                                         (methodAttributes & MethodAttributes.Abstract) != 0 ||
                                         (methodAttributes & MethodAttributes.Virtual) != 0 ||
                                         RuntimeMethodHandle.GetDeclaringType(methodHandle) != declaringType);
@@ -714,7 +700,7 @@ namespace System
                                 }
                                 else
                                 {
-                                    Contract.Assert((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0);
+                                    Debug.Assert((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0);
                                 }
                                 #endregion
 
@@ -742,7 +728,6 @@ namespace System
                     return list.ToArray();
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private RuntimeConstructorInfo[] PopulateConstructors(Filter filter)
                 {
                     if (ReflectedType.IsGenericParameter)
@@ -760,7 +745,7 @@ namespace System
                         {
                             if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
                             {
-                                Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
+                                Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
                                 continue;
                             }
 
@@ -770,13 +755,13 @@ namespace System
 
                         MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle);
 
-                        Contract.Assert(!methodHandle.IsNullHandle());
+                        Debug.Assert(!methodHandle.IsNullHandle());
 
                         if ((methodAttributes & MethodAttributes.RTSpecialName) == 0)
                             continue;
 
                         // Constructors should not be virtual or abstract
-                        Contract.Assert(
+                        Debug.Assert(
                             (methodAttributes & MethodAttributes.Abstract) == 0 &&
                             (methodAttributes & MethodAttributes.Virtual) == 0);
 
@@ -799,7 +784,6 @@ namespace System
                     return list.ToArray();
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe RuntimeFieldInfo[] PopulateFields(Filter filter)
                 {
                     ListBuilder<RuntimeFieldInfo> list = new ListBuilder<RuntimeFieldInfo>();
@@ -851,7 +835,6 @@ namespace System
                     return list.ToArray();
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe void PopulateRtFields(Filter filter, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
                 {
                     IntPtr* pResult = stackalloc IntPtr[64];
@@ -871,7 +854,6 @@ namespace System
                     }
                 }
                     
-                [System.Security.SecurityCritical]  // auto-generated
                 private unsafe void PopulateRtFields(Filter filter,
                     IntPtr* ppFieldHandles, int count, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
                 {
@@ -889,7 +871,7 @@ namespace System
                         {
                             if (!RuntimeFieldHandle.MatchesNameHash(runtimeFieldHandle, filter.GetHashToMatch()))
                             {
-                                Contract.Assert(!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle)));
+                                Debug.Assert(!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle)));
                                 continue;
                             }
 
@@ -897,7 +879,7 @@ namespace System
                                 continue;
                         }
 
-                        Contract.Assert(!runtimeFieldHandle.IsNullHandle());
+                        Debug.Assert(!runtimeFieldHandle.IsNullHandle());
 
                         FieldAttributes fieldAttributes = RuntimeFieldHandle.GetAttributes(runtimeFieldHandle);
                         FieldAttributes fieldAccess = fieldAttributes & FieldAttributes.FieldAccessMask;
@@ -925,7 +907,6 @@ namespace System
                     }
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe void PopulateLiteralFields(Filter filter, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
                 {
                     Contract.Requires(declaringType != null);
@@ -945,8 +926,8 @@ namespace System
                     for (int i = 0; i < tkFields.Length; i++)
                     {
                         int tkField = tkFields[i];
-                        Contract.Assert(MdToken.IsTokenOfType(tkField, MetadataTokenType.FieldDef));
-                        Contract.Assert(!MdToken.IsNullToken(tkField));
+                        Debug.Assert(MdToken.IsTokenOfType(tkField, MetadataTokenType.FieldDef));
+                        Debug.Assert(!MdToken.IsNullToken(tkField));
 
                         FieldAttributes fieldAttributes;
                         scope.GetFieldDefProps(tkField, out fieldAttributes);
@@ -1030,7 +1011,6 @@ namespace System
 
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private RuntimeType[] PopulateInterfaces(Filter filter)
                 {
                     ListBuilder<RuntimeType> list = new ListBuilder<RuntimeType>();
@@ -1053,7 +1033,7 @@ namespace System
                                         continue;
                                 }
                             
-                                Contract.Assert(interfaceType.IsInterface);
+                                Debug.Assert(interfaceType.IsInterface);
                                 list.Add(interfaceType);
                             }
                         }
@@ -1120,7 +1100,6 @@ namespace System
                     return list.ToArray();
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe RuntimeType[] PopulateNestedClasses(Filter filter)
                 {
                     RuntimeType declaringType = ReflectedType;
@@ -1171,7 +1150,6 @@ namespace System
                     return list.ToArray();
                 }
                 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe RuntimeEventInfo[] PopulateEvents(Filter filter)
                 {
                     Contract.Requires(ReflectedType != null);
@@ -1204,7 +1182,6 @@ namespace System
                     return list.ToArray();
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe void PopulateEvents(
                     Filter filter, RuntimeType declaringType, Dictionary<String, RuntimeEventInfo> csEventInfos, ref ListBuilder<RuntimeEventInfo> list)
                 {
@@ -1224,8 +1201,8 @@ namespace System
                         int tkEvent = tkEvents[i];
                         bool isPrivate;
 
-                        Contract.Assert(!MdToken.IsNullToken(tkEvent));
-                        Contract.Assert(MdToken.IsTokenOfType(tkEvent, MetadataTokenType.Event));
+                        Debug.Assert(!MdToken.IsNullToken(tkEvent));
+                        Debug.Assert(MdToken.IsTokenOfType(tkEvent, MetadataTokenType.Event));
 
                         if (filter.RequiresStringComparison())
                         {
@@ -1265,7 +1242,6 @@ namespace System
                     }
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe RuntimePropertyInfo[] PopulateProperties(Filter filter)
                 {
                     Contract.Requires(ReflectedType != null);
@@ -1274,7 +1250,7 @@ namespace System
                     // is called in Populate after this returns.
 
                     RuntimeType declaringType = ReflectedType;
-                    Contract.Assert(declaringType != null);
+                    Debug.Assert(declaringType != null);
 
                     ListBuilder<RuntimePropertyInfo> list = new ListBuilder<RuntimePropertyInfo>();
 
@@ -1306,7 +1282,6 @@ namespace System
                     return list.ToArray();
                 }
 
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 private unsafe void PopulateProperties(
                     Filter filter, 
                     RuntimeType declaringType, 
@@ -1329,7 +1304,7 @@ namespace System
 
                     int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType);
 
-                    Contract.Assert((declaringType.IsInterface && usedSlots == null && csPropertyInfos == null) ||
+                    Debug.Assert((declaringType.IsInterface && usedSlots == null && csPropertyInfos == null) ||
                                     (!declaringType.IsInterface && usedSlots != null && usedSlots.Length >= numVirtuals));
 
                     for (int i = 0; i < tkProperties.Length; i++)
@@ -1337,14 +1312,14 @@ namespace System
                         int tkProperty = tkProperties[i];
                         bool isPrivate;
 
-                        Contract.Assert(!MdToken.IsNullToken(tkProperty));
-                        Contract.Assert(MdToken.IsTokenOfType(tkProperty, MetadataTokenType.Property));
+                        Debug.Assert(!MdToken.IsNullToken(tkProperty));
+                        Debug.Assert(MdToken.IsTokenOfType(tkProperty, MetadataTokenType.Property));
 
                         if (filter.RequiresStringComparison())
                         {
                             if (!ModuleHandle.ContainsPropertyMatchingHash(declaringModuleHandle, tkProperty, filter.GetHashToMatch()))
                             {
-                                Contract.Assert(!filter.Match(declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty)));
+                                Debug.Assert(!filter.Match(declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty)));
                                 continue;
                             }
 
@@ -1389,7 +1364,7 @@ namespace System
 
                                 if (slot < numVirtuals)
                                 {
-                                    Contract.Assert(associateMethod.IsVirtual);
+                                    Debug.Assert(associateMethod.IsVirtual);
                                     if (usedSlots[slot] == true)
                                         continue;
                                     else
@@ -1475,7 +1450,7 @@ namespace System
                             return Populate(name, listType, cacheType);
 
                         default:
-                            Contract.Assert(listType == MemberListType.All);
+                            Debug.Assert(listType == MemberListType.All);
                             if (Volatile.Read(ref m_cacheComplete))
                                 return m_allMembers;
 
@@ -1514,9 +1489,6 @@ namespace System
             private MemberInfoCache<RuntimeEventInfo> m_eventInfoCache;
             private static CerHashtable<RuntimeMethodInfo, RuntimeMethodInfo> s_methodInstantiations;
             private static Object s_methodInstantiationsLock;
-#if !FEATURE_CORECLR
-            private RuntimeConstructorInfo m_serializationCtor;
-#endif
             private string m_defaultMemberName;
             private Object m_genericCache; // Generic cache for rare scenario specific data. It is used to cache Enum names and values.
             #endregion
@@ -1614,7 +1586,6 @@ namespace System
                 }
             }
 
-            [System.Security.SecuritySafeCritical]
             internal unsafe string GetNameSpace()
             {
                 // @Optimization - Use ConstructName to populate m_namespace
@@ -1638,14 +1609,13 @@ namespace System
                 set { m_typeCode = value; } 
             }
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
             internal unsafe RuntimeType GetEnclosingType()
             { 
                 if (m_enclosingType == null)
                 {
                     // Use void as a marker of null enclosing type
                     RuntimeType enclosingType = RuntimeTypeHandle.GetDeclaringType(GetRuntimeType());
-                    Contract.Assert(enclosingType != typeof(void));
+                    Debug.Assert(enclosingType != typeof(void));
                     m_enclosingType = enclosingType ?? (RuntimeType)typeof(void);
                 }
 
@@ -1668,26 +1638,6 @@ namespace System
                 m_nestedClassesCache = null;
             }
 
-#if !FEATURE_CORECLR
-            internal RuntimeConstructorInfo GetSerializationCtor()
-            {
-                if (m_serializationCtor == null)
-                {
-                    if (s_SICtorParamTypes == null)
-                        s_SICtorParamTypes = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) };
-
-                    m_serializationCtor = m_runtimeType.GetConstructor(
-                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
-                        null,
-                        CallingConventions.Any,
-                        s_SICtorParamTypes,
-                        null) as RuntimeConstructorInfo;
-                }
-
-                return m_serializationCtor;
-            }
-#endif //!FEATURE_CORECLR
-
             internal string GetDefaultMemberName()
             {
                 if (m_defaultMemberName == null)
@@ -1719,7 +1669,6 @@ namespace System
             #endregion
 
             #region Caches Accessors
-            [System.Security.SecurityCritical]  // auto-generated
             internal MethodInfo GetGenericMethodInfo(RuntimeMethodHandleInternal genericMethod)
             {
                 LoaderAllocator la = RuntimeMethodHandle.GetLoaderAllocator(genericMethod);
@@ -1832,36 +1781,6 @@ namespace System
         }
         #endregion
 
-#if FEATURE_REMOTING
-        #region Legacy Remoting Cache
-        // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
-        // This member is currently being used by Remoting for caching remoting data. If you
-        // need to cache data here, talk to the Remoting team to work out a mechanism, so that
-        // both caching systems can happily work together.
-        private RemotingTypeCachedData m_cachedData;
-
-        internal RemotingTypeCachedData RemotingCache
-        {
-            get
-            {
-                // This grabs an internal copy of m_cachedData and uses
-                // that instead of looking at m_cachedData directly because
-                // the cache may get cleared asynchronously.  This prevents
-                // us from having to take a lock.
-                RemotingTypeCachedData cache = m_cachedData;
-                if (cache == null)
-                {
-                    cache = new RemotingTypeCachedData(this);
-                    RemotingTypeCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
-                    if (ret != null)
-                        cache = ret;
-                }
-                return cache;
-            }
-        }
-        #endregion
-#endif //FEATURE_REMOTING
-
         #region Static Members
 
         #region Internal
@@ -1886,7 +1805,6 @@ namespace System
             return GetMethodBase(null, methodHandle);
         }
 
-        [System.Security.SecuritySafeCritical]
         internal static MethodBase GetMethodBase(RuntimeType reflectedType, IRuntimeMethodInfo methodHandle)
         {
             MethodBase retval = RuntimeType.GetMethodBase(reflectedType, methodHandle.Value);
@@ -1894,10 +1812,9 @@ namespace System
             return retval;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static MethodBase GetMethodBase(RuntimeType reflectedType, RuntimeMethodHandleInternal methodHandle)
         {
-            Contract.Assert(!methodHandle.IsNullHandle());
+            Debug.Assert(!methodHandle.IsNullHandle());
 
             if (RuntimeMethodHandle.IsDynamicMethod(methodHandle))
             {
@@ -2037,13 +1954,11 @@ namespace System
             set { Cache.DomainInitialized = value; }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static FieldInfo GetFieldInfo(IRuntimeFieldInfo fieldHandle)
         {
             return GetFieldInfo(RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle), fieldHandle);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static FieldInfo GetFieldInfo(RuntimeType reflectedType, IRuntimeFieldInfo field)
         {
             RuntimeFieldHandleInternal fieldHandle = field.Value;
@@ -2119,7 +2034,6 @@ namespace System
                     Environment.GetResourceString("Argument_NotEnoughGenArguments", genericArguments.Length, genericParamters.Length));
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static void ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
         {
             RuntimeType[] typeContext = null;
@@ -2178,7 +2092,7 @@ namespace System
                     name = fullname.Substring(nsDelimiter + 1, nameLength);
                 else
                     name = "";
-                Contract.Assert(fullname.Equals(ns + "." + name));
+                Debug.Assert(fullname.Equals(ns + "." + name));
             }
             else
             {
@@ -2270,7 +2184,7 @@ namespace System
         // Most of the plural GetXXX methods allow prefix lookups while the singular GetXXX methods mostly do not.
         private static bool FilterApplyPrefixLookup(MemberInfo memberInfo, string name, bool ignoreCase)
         {
-            Contract.Assert(name != null);
+            Debug.Assert(name != null);
 
             if (ignoreCase)
             {
@@ -2376,7 +2290,7 @@ namespace System
             Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns)
         {
             Contract.Requires((object)type != null);
-            Contract.Assert(type is RuntimeType);
+            Debug.Assert(type is RuntimeType);
 
             bool isPublic = type.IsNestedPublic || type.IsPublic;
             bool isStatic = false;
@@ -2461,7 +2375,7 @@ namespace System
                         {
                             // If Binding flags did not include varargs we would have filtered this vararg method.
                             // This Invariant established during callConv check.
-                            Contract.Assert((callConv & CallingConventions.VarArgs) != 0);
+                            Debug.Assert((callConv & CallingConventions.VarArgs) != 0);
                         }
                         #endregion
                     }
@@ -2632,7 +2546,6 @@ namespace System
 
         private RuntimeTypeCache Cache
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (m_cache.IsNull())
@@ -2654,7 +2567,7 @@ namespace System
                         cache = existingCache;
                 }
 
-                Contract.Assert(cache != null);
+                Debug.Assert(cache != null);
                 return cache;
             }
         }
@@ -2681,13 +2594,6 @@ namespace System
         {
             return Cache.GetDefaultMemberName();
         }
-
-#if !FEATURE_CORECLR
-        internal RuntimeConstructorInfo GetSerializationCtor()
-        {
-            return Cache.GetSerializationCtor();
-        }
-#endif
         #endregion
 
         #region Type Overrides
@@ -2868,7 +2774,6 @@ namespace System
             return GetFieldCandidates(null, bindingAttr, false).ToArray();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Type[] GetInterfaces()
         {
               RuntimeType[] candidates = this.Cache.GetInterfaceList(MemberListType.All, null);
@@ -2909,12 +2814,11 @@ namespace System
             events.CopyTo(members, i); i += events.Count;
             fields.CopyTo(members, i); i += fields.Count;
             nestedTypes.CopyTo(members, i); i += nestedTypes.Count;
-            Contract.Assert(i == members.Length);
+            Debug.Assert(i == members.Length);
 
             return members;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override InterfaceMapping GetInterfaceMap(Type ifaceType)
         {
             if (IsGenericParameter)
@@ -2932,8 +2836,8 @@ namespace System
             RuntimeTypeHandle ifaceRtTypeHandle = ifaceRtType.GetTypeHandleInternal();
 
             GetTypeHandleInternal().VerifyInterfaceIsImplemented(ifaceRtTypeHandle);
-            Contract.Assert(ifaceType.IsInterface);  // VerifyInterfaceIsImplemented enforces this invariant
-            Contract.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
+            Debug.Assert(ifaceType.IsInterface);  // VerifyInterfaceIsImplemented enforces this invariant
+            Debug.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
 
             // SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with
             // SZArrayHelper and some runtime magic. We don't have accurate interface maps for them.
@@ -2954,7 +2858,7 @@ namespace System
 
                 // GetMethodBase will convert this to the instantiating/unboxing stub if necessary
                 MethodBase ifaceMethodBase = RuntimeType.GetMethodBase(ifaceRtType, ifaceRtMethodHandle);
-                Contract.Assert(ifaceMethodBase is RuntimeMethodInfo);
+                Debug.Assert(ifaceMethodBase is RuntimeMethodInfo);
                 im.InterfaceMethods[i] = (MethodInfo)ifaceMethodBase;
 
                 // If the slot is -1, then virtual stub dispatch is active.
@@ -2967,7 +2871,7 @@ namespace System
                 // GetMethodBase will convert this to the instantiating/unboxing stub if necessary
                 MethodBase rtTypeMethodBase = RuntimeType.GetMethodBase(this, classRtMethodHandle);
                 // a class may not implement all the methods of an interface (abstract class) so null is a valid value 
-                Contract.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo);
+                Debug.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo);
                 im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase;
             }
 
@@ -3301,7 +3205,7 @@ namespace System
             events.CopyTo(compressMembers, i); i += events.Count;
             fields.CopyTo(compressMembers, i); i += fields.Count;
             nestedTypes.CopyTo(compressMembers, i); i += nestedTypes.Count;
-            Contract.Assert(i == compressMembers.Length);
+            Debug.Assert(i == compressMembers.Length);
 
             return compressMembers;
         }
@@ -3348,13 +3252,11 @@ namespace System
             return new RuntimeTypeHandle(this);
         }
 
-        [System.Security.SecuritySafeCritical]
         internal bool IsCollectible()
         {
             return RuntimeTypeHandle.IsCollectible(GetTypeHandleInternal());
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected override TypeCode GetTypeCodeImpl() 
         {
             TypeCode typeCode = Cache.TypeCode;
@@ -3435,7 +3337,6 @@ namespace System
         #endregion
 
         #region Hierarchy
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsInstanceOfType(Object o)
         {
             return RuntimeTypeHandle.IsInstanceOfType(this, o);
@@ -3519,23 +3420,6 @@ namespace System
             return false;
         }
 
-#if !FEATURE_CORECLR
-        // Reflexive, symmetric, transitive.
-        public override bool IsEquivalentTo(Type other)
-        {
-            RuntimeType otherRtType = other as RuntimeType;
-            if ((object)otherRtType == null)
-                return false;
-
-            if (otherRtType == this)
-                return true;
-
-            // It's not worth trying to perform further checks in managed
-            // as they would lead to FCalls anyway.
-            return RuntimeTypeHandle.IsEquivalentTo(this, otherRtType);
-        }
-#endif // FEATURE_CORECLR
-
         public override Type BaseType 
         {
             get 
@@ -3636,7 +3520,6 @@ namespace System
         #endregion
 
         #region Attributes
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected override TypeAttributes GetAttributeFlagsImpl() 
         {
             return RuntimeTypeHandle.GetAttributes(this);
@@ -3644,7 +3527,6 @@ namespace System
 
         public override Guid GUID 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get 
             {
                 Guid result = new Guid ();
@@ -3653,27 +3535,14 @@ namespace System
             }
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void GetGUID(ref Guid result);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected override bool IsContextfulImpl() 
         {
-#if FEATURE_REMOTING
-            return RuntimeTypeHandle.IsContextful(this);
-#else
             return false;
-#endif
         }
 
-        /*
-        protected override bool IsMarshalByRefImpl() 
-        {
-            return GetTypeHandleInternal().IsMarshalByRef();
-        }
-        */
-
         protected override bool IsByRefImpl() 
         {
             return RuntimeTypeHandle.IsByRef(this);
@@ -3689,36 +3558,30 @@ namespace System
             return RuntimeTypeHandle.IsPointer(this);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected override bool IsCOMObjectImpl() 
         {
             return RuntimeTypeHandle.IsComObject(this, false);
         }
 
 #if FEATURE_COMINTEROP
-        [SecuritySafeCritical]
         internal override bool IsWindowsRuntimeObjectImpl()
         {
             return IsWindowsRuntimeObjectType(this);
         }
 
-        [SecuritySafeCritical]
         internal override bool IsExportedToWindowsRuntimeImpl()
         {
             return IsTypeExportedToWindowsRuntime(this);
         }
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecurityCritical]
         private static extern bool IsWindowsRuntimeObjectType(RuntimeType type);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecurityCritical]
         private static extern bool IsTypeExportedToWindowsRuntime(RuntimeType type);
 
 #endif // FEATURE_COMINTEROP
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal override bool HasProxyAttributeImpl() 
         {
             return RuntimeTypeHandle.HasProxyAttribute(this);
@@ -3740,16 +3603,6 @@ namespace System
             return IsSubclassOf(typeof(ValueType));
         }
 
-#if !FEATURE_CORECLR
-        public override bool IsEnum
-        {
-            get
-            {
-                return GetBaseType() == RuntimeType.EnumType; 
-            }
-        }
-#endif
-
         protected override bool HasElementTypeImpl() 
         {
             return RuntimeTypeHandle.HasElementType(this);
@@ -3757,7 +3610,6 @@ namespace System
 
         public override GenericParameterAttributes GenericParameterAttributes
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 if (!IsGenericParameter)
@@ -3800,7 +3652,6 @@ namespace System
             return RuntimeTypeHandle.IsArray(this);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override int GetArrayRank() 
         {
             if (!IsArrayImpl())
@@ -3832,7 +3683,6 @@ namespace System
             return retVal;
         }
 
-        [SecuritySafeCritical]
         public override Array GetEnumValues()
         {
             if (!IsEnum)
@@ -3943,7 +3793,6 @@ namespace System
             return types;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Type MakeGenericType(Type[] instantiation)
         {
             if (instantiation == null)
@@ -4059,7 +3908,6 @@ namespace System
         #endregion
 
         #region Misc
-        [System.Security.SecuritySafeCritical]  // auto-generated
         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(); }
@@ -4073,7 +3921,6 @@ namespace System
         }
         public override StructLayoutAttribute StructLayoutAttribute
         {
-            [System.Security.SecuritySafeCritical] // overrides transparent public member             
             get 
             { 
                 return (StructLayoutAttribute)StructLayoutAttribute.GetCustomAttribute(this); 
@@ -4095,15 +3942,12 @@ namespace System
             BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty;
         private static RuntimeType s_typedRef = (RuntimeType)typeof(TypedReference);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static private extern bool CanValueSpecialCast(RuntimeType valueType, RuntimeType targetType);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static private extern Object AllocateValueType(RuntimeType type, object value, bool fForceTypeChange); 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe Object CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr) 
         {
             // this method is used by invocation in reflection to check whether a value can be assigned to type.
@@ -4111,26 +3955,9 @@ namespace System
             {
                 // Since this cannot be a generic parameter, we use RuntimeTypeHandle.IsValueType here
                 // because it is faster than RuntimeType.IsValueType
-                Contract.Assert(!IsGenericParameter);
-
-                Type type = null;
-
-#if FEATURE_REMOTING
-                // For the remoting objects Object.GetType goes through proxy. Avoid the proxy call and just get
-                // the type directly. It is necessary to support proxies that do not handle GetType.
-                RealProxy realProxy = System.Runtime.Remoting.RemotingServices.GetRealProxy(value);
+                Debug.Assert(!IsGenericParameter);
 
-                if (realProxy != null)
-                {
-                    type = realProxy.GetProxiedType();
-                }
-                else
-                {
-                    type = value.GetType();
-                }
-#else
-                type = value.GetType();
-#endif
+                Type type = value.GetType();
 
                 if (!Object.ReferenceEquals(type, this) && RuntimeTypeHandle.IsValueType(this))
                 {
@@ -4190,7 +4017,6 @@ namespace System
         }
 
         // Factored out of CheckValue to reduce code complexity.
-        [System.Security.SecurityCritical]
         private Object TryChangeType(Object value, Binder binder, CultureInfo culture, bool needsSpecialCast)
         {
             if (binder != null && binder != Type.DefaultBinder) 
@@ -4249,7 +4075,6 @@ namespace System
         }
 
 #if FEATURE_COMINTEROP
-        [System.Security.SecuritySafeCritical]  // auto-generated
 #endif
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
@@ -4317,9 +4142,6 @@ namespace System
                     throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), nameof(bindingFlags));
                 #endregion
 
-#if FEATURE_REMOTING
-                if(!RemotingServices.IsTransparentProxy(target))
-#endif
                 {
                     #region Non-TransparentProxy case
                     if (name == null)
@@ -4333,14 +4155,6 @@ namespace System
                     return InvokeDispMethod(name, bindingFlags, target, providedArgs, isByRef, lcid, namedParams);
                     #endregion
                 }
-#if FEATURE_REMOTING
-                else
-                {
-                    #region TransparentProxy case
-                    return ((MarshalByRefObject)target).InvokeMember(name, bindingFlags, binder, providedArgs, modifiers, culture, namedParams);
-                    #endregion
-                }
-#endif // FEATURE_REMOTING
             }
 #endif // FEATURE_COMINTEROP && FEATURE_USE_LCID
             #endregion
@@ -4410,7 +4224,7 @@ namespace System
                 }
                 else
                 {
-                    Contract.Assert(IsSetField);
+                    Debug.Assert(IsSetField);
 
                     if (providedArgs == null) 
                         throw new ArgumentNullException(nameof(providedArgs));
@@ -4429,7 +4243,7 @@ namespace System
                 FieldInfo selFld = null;                
                 FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];
 
-                Contract.Assert(flds != null);
+                Debug.Assert(flds != null);
 
                 if (flds.Length == 1)
                 {
@@ -4552,16 +4366,16 @@ namespace System
                 #region Preconditions
                 if (isGetProperty)
                 {
-                    Contract.Assert(!IsSetField);
+                    Debug.Assert(!IsSetField);
 
                     if (isSetProperty)
                         throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), nameof(bindingFlags));
                 }
                 else
                 {
-                    Contract.Assert(isSetProperty);
+                    Debug.Assert(isSetProperty);
 
-                    Contract.Assert(!IsGetField);
+                    Debug.Assert(!IsGetField);
                     
                     if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
                         throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), nameof(bindingFlags));
@@ -4583,7 +4397,7 @@ namespace System
                 for(int i = 0; i < semiFinalists.Length; i ++)
                 {
                     MethodInfo semiFinalist = semiFinalists[i];
-                    Contract.Assert(semiFinalist != null);
+                    Debug.Assert(semiFinalist != null);
 
                     if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt]))
                         continue;
@@ -4606,7 +4420,7 @@ namespace System
                 
                 if (results != null)
                 {
-                    Contract.Assert(results.Count > 1);
+                    Debug.Assert(results.Count > 1);
                     finalists = new MethodInfo[results.Count];
                     results.CopyTo(finalists);
                 }
@@ -4614,7 +4428,7 @@ namespace System
             }
             #endregion
             
-            Contract.Assert(finalists == null || finalist != null);
+            Debug.Assert(finalists == null || finalist != null);
 
             #region BindingFlags.GetProperty or BindingFlags.SetProperty
             if (finalist == null && isGetProperty || isSetProperty) 
@@ -4660,7 +4474,7 @@ namespace System
 
                 if (results != null)
                 {
-                    Contract.Assert(results.Count > 1);
+                    Debug.Assert(results.Count > 1);
                     finalists = new MethodInfo[results.Count];
                     results.CopyTo(finalists);
                 }
@@ -4730,18 +4544,6 @@ namespace System
             return RuntimeHelpers.GetHashCode(this);
         }
 
-#if !FEATURE_CORECLR
-        public static bool operator ==(RuntimeType left, RuntimeType right)
-        {
-            return object.ReferenceEquals(left, right);
-        }
-
-        public static bool operator !=(RuntimeType left, RuntimeType right)
-        {
-            return !object.ReferenceEquals(left, right);
-        }
-#endif // !FEATURE_CORECLR
-
         public override String ToString() 
         {
             return GetCachedName(TypeNameKind.ToString);
@@ -4756,7 +4558,6 @@ namespace System
         #endregion
 
         #region ISerializable
-        [System.Security.SecurityCritical]  // auto-generated
         public void GetObjectData(SerializationInfo info, StreamingContext context) 
         {
             if (info==null) 
@@ -4768,13 +4569,11 @@ namespace System
         #endregion
 
         #region ICustomAttributeProvider
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Object[] GetCustomAttributes(bool inherit)
         {
             return CustomAttribute.GetCustomAttributes(this, RuntimeType.ObjectType, inherit);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
         {
             if ((object)attributeType == null)
@@ -4789,7 +4588,6 @@ namespace System
             return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsDefined(Type attributeType, bool inherit)
         {
             if ((object)attributeType == null)
@@ -4891,7 +4689,6 @@ namespace System
 
         public override int MetadataToken
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get 
             {
                 return RuntimeTypeHandle.GetToken(this);
@@ -4919,7 +4716,6 @@ namespace System
                 throw new NotSupportedException(Environment.GetResourceString("Acc_CreateVoid"));
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal Object CreateInstanceImpl(
             BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, ref StackCrawlMark stackMark)
         {            
@@ -4927,170 +4723,117 @@ namespace System
             
             Object server = null;
 
-            try
-            {
-                try
-                {
-                    // Store the activation attributes in thread local storage.
-                    // These attributes are later picked up by specialized 
-                    // activation services like remote activation services to
-                    // influence the activation.
-#if FEATURE_REMOTING                                    
-                    if(null != activationAttributes)
-                    {
-                        ActivationServices.PushActivationAttributes(this, activationAttributes);
-                    }
-#endif                    
-                    
-                    if (args == null)
-                        args = EmptyArray<Object>.Value;
+            if (args == null)
+                args = EmptyArray<Object>.Value;
 
-                    int argCnt = args.Length;
+            int argCnt = args.Length;
 
-                    // Without a binder we need to do use the default binder...
-                    if (binder == null)
-                        binder = DefaultBinder;
+            // Without a binder we need to do use the default binder...
+            if (binder == null)
+                binder = DefaultBinder;
+
+            // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors
+            // so a call to GetMemberCons would fail
+            if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0
+                && (IsGenericCOMObjectImpl() || IsValueType)) 
+            {
+                server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0 , false, true, ref stackMark);
+            }
+            else
+            {
+                ConstructorInfo[] candidates = GetConstructors(bindingAttr);
+                List<MethodBase> matches = new List<MethodBase>(candidates.Length);
 
-                    // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors
-                    // so a call to GetMemberCons would fail
-                    if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0
-                        && (IsGenericCOMObjectImpl() || IsValueType)) 
+                // We cannot use Type.GetTypeArray here because some of the args might be null
+                Type[] argsType = new Type[argCnt];
+                for (int i = 0; i < argCnt; i++)
+                {
+                    if (args[i] != null)
                     {
-                        server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0 , false, true, ref stackMark);
+                        argsType[i] = args[i].GetType();
                     }
-                    else 
-                    {
-                        ConstructorInfo[] candidates = GetConstructors(bindingAttr);
-                        List<MethodBase> matches = new List<MethodBase>(candidates.Length);
-
-                        // We cannot use Type.GetTypeArray here because some of the args might be null
-                        Type[] argsType = new Type[argCnt];
-                        for (int i = 0; i < argCnt; i++)
-                        {
-                            if (args[i] != null)
-                            {
-                                argsType[i] = args[i].GetType();
-                            }
-                        }
-
-                        for(int i = 0; i < candidates.Length; i ++)
-                        {
-                            if (FilterApplyConstructorInfo((RuntimeConstructorInfo)candidates[i], bindingAttr, CallingConventions.Any, argsType))
-                                matches.Add(candidates[i]);
-                        }
+                }
 
-                        MethodBase[] cons = new MethodBase[matches.Count];
-                        matches.CopyTo(cons);
-                        if (cons != null && cons.Length == 0)
-                            cons = null;
+                for(int i = 0; i < candidates.Length; i ++)
+                {
+                    if (FilterApplyConstructorInfo((RuntimeConstructorInfo)candidates[i], bindingAttr, CallingConventions.Any, argsType))
+                        matches.Add(candidates[i]);
+                }
 
-                        if (cons == null) 
-                        {
-                            // Null out activation attributes before throwing exception
-#if FEATURE_REMOTING                                            
-                            if(null != activationAttributes)
-                            {
-                                ActivationServices.PopActivationAttributes(this);
-                                activationAttributes = null;
-                            }
-#endif                            
-                            throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
-                        }
+                MethodBase[] cons = new MethodBase[matches.Count];
+                matches.CopyTo(cons);
+                if (cons != null && cons.Length == 0)
+                    cons = null;
 
-                        MethodBase invokeMethod;
-                        Object state = null;
+                if (cons == null)
+                {
+                    throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
+                }
 
-                        try
-                        {
-                            invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state);
-                        }
-                        catch (MissingMethodException) { invokeMethod = null; }
+                MethodBase invokeMethod;
+                Object state = null;
 
-                        if (invokeMethod == null)
-                        {
-#if FEATURE_REMOTING                                            
-                            // Null out activation attributes before throwing exception
-                            if(null != activationAttributes)
-                            {
-                                ActivationServices.PopActivationAttributes(this);
-                                activationAttributes = null;
-                            }                  
-#endif                                
-                            throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
-                        }
+                try
+                {
+                    invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state);
+                }
+                catch (MissingMethodException) { invokeMethod = null; }
 
-                        // If we're creating a delegate, we're about to call a
-                        // constructor taking an integer to represent a target
-                        // method. Since this is very difficult (and expensive)
-                        // to verify, we're just going to demand UnmanagedCode
-                        // permission before allowing this. Partially trusted
-                        // clients can instead use Delegate.CreateDelegate,
-                        // which allows specification of the target method via
-                        // name or MethodInfo.
-                        //if (isDelegate)
-                        if (RuntimeType.DelegateType.IsAssignableFrom(invokeMethod.DeclaringType))
-                        {
-#if FEATURE_CORECLR
-                            // In CoreCLR, CAS is not exposed externally. So what we really are looking
-                            // for is to see if the external caller of this API is transparent or not.
-                            // We get that information from the fact that a Demand will succeed only if
-                            // the external caller is not transparent. 
-                            try
-                            {
+                if (invokeMethod == null)
+                {
+                    throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
+                }
+
+                // If we're creating a delegate, we're about to call a
+                // constructor taking an integer to represent a target
+                // method. Since this is very difficult (and expensive)
+                // to verify, we're just going to demand UnmanagedCode
+                // permission before allowing this. Partially trusted
+                // clients can instead use Delegate.CreateDelegate,
+                // which allows specification of the target method via
+                // name or MethodInfo.
+                //if (isDelegate)
+                if (RuntimeType.DelegateType.IsAssignableFrom(invokeMethod.DeclaringType))
+                {
+                    // In CoreCLR, CAS is not exposed externally. So what we really are looking
+                    // for is to see if the external caller of this API is transparent or not.
+                    // We get that information from the fact that a Demand will succeed only if
+                    // the external caller is not transparent. 
+                    try
+                    {
 #pragma warning disable 618
-                                new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
+                        new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
 #pragma warning restore 618
-                            }
-                            catch
-                            {
-                                throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_DelegateCreationFromPT")));
-                            }
-#else // FEATURE_CORECLR
-                            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#endif // FEATURE_CORECLR
-                        }
-
-                        if (invokeMethod.GetParametersNoCopy().Length == 0)
-                        {
-                            if (args.Length != 0)
-                            {
-
-                                Contract.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) == 
-                                                 CallingConventions.VarArgs); 
-                                throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, 
-                                    Environment.GetResourceString("NotSupported_CallToVarArg")));
-                            }
-
-                            // fast path??
-                            server = Activator.CreateInstance(this, true);
-                        }
-                        else
-                        {
-                            server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture);
-                            if (state != null)
-                                binder.ReorderArgumentArray(ref args, state);
-                        }
                     }
-                }                    
-                finally
+                    catch
+                    {
+                        throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_DelegateCreationFromPT")));
+                    }
+                }
+
+                if (invokeMethod.GetParametersNoCopy().Length == 0)
                 {
-#if FEATURE_REMOTING                
-                    // Reset the TLS to null
-                    if(null != activationAttributes)
+                    if (args.Length != 0)
                     {
-                          ActivationServices.PopActivationAttributes(this);
-                          activationAttributes = null;
+
+                        Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) == 
+                                            CallingConventions.VarArgs); 
+                        throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, 
+                            Environment.GetResourceString("NotSupported_CallToVarArg")));
                     }
-#endif                    
+
+                    // fast path??
+                    server = Activator.CreateInstance(this, true);
+                }
+                else
+                {
+                    server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture);
+                    if (state != null)
+                        binder.ReorderArgumentArray(ref args, state);
                 }
             }
-            catch (Exception)
-            {
-                throw;
-            }
-            
-            //Console.WriteLine(server);
-            return server;                                
+
+            return server;
         }
 
         // the cache entry
@@ -5107,7 +4850,6 @@ namespace System
             // Lazy initialization was performed
             internal volatile bool m_bFullyInitialized;
 
-            [System.Security.SecurityCritical]
             internal ActivatorCacheEntry(RuntimeType t, RuntimeMethodHandleInternal rmh, bool bNeedSecurityCheck)
             {
                 m_type = t;
@@ -5141,12 +4883,11 @@ namespace System
                 delegateCtorInfo = ctorInfo; // this assignment should be last
             }
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
             private void InitializeCacheEntry(ActivatorCacheEntry ace)
             {
                 if (!ace.m_type.IsValueType)
                 {
-                    Contract.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type.");
+                    Debug.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type.");
                     
                     if (delegateCtorInfo == null)
                         InitializeDelegateCreator();
@@ -5188,7 +4929,6 @@ namespace System
         private static volatile ActivatorCache s_ActivatorCache;
 
         // the slow path of CreateInstanceDefaultCtor
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal Object CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
         {
             RuntimeMethodHandleInternal runtime_ctor = default(RuntimeMethodHandleInternal);
@@ -5216,9 +4956,7 @@ namespace System
                 bCanBeCached = false;
             }
 #endif
-#if FEATURE_CORECLR
             bSecurityCheckOff = true;       // CoreCLR does not use security at all.   
-#endif
 
             Object instance = RuntimeTypeHandle.CreateInstance(this, publicOnly, bSecurityCheckOff, ref bCanBeCached, ref runtime_ctor, ref bNeedSecurityCheck);
 
@@ -5242,7 +4980,6 @@ namespace System
 
         // Helper to invoke the default (parameterless) ctor.
         // fillCache is set in the SL2/3 compat mode or when called from Marshal.PtrToStructure.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         internal Object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
@@ -5269,16 +5006,10 @@ namespace System
                     Object instance = RuntimeTypeHandle.Allocate(this);
                     
                     // if m_ctor is null, this type doesn't have a default ctor
-                    Contract.Assert(ace.m_ctor != null || this.IsValueType);
+                    Debug.Assert(ace.m_ctor != null || this.IsValueType);
 
                     if (ace.m_ctor != null)
                     {
-#if !FEATURE_CORECLR
-                        // Perform security checks if needed
-                        if (ace.m_bNeedSecurityCheck)
-                            RuntimeMethodHandle.PerformSecurityCheck(instance, ace.m_hCtorMethodHandle, this, (uint)INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE);
-#endif
-
                         // Call ctor (value types wont have any)
                         try
                         {
@@ -5300,7 +5031,6 @@ namespace System
             Cache.InvalidateCachedNestedType();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsGenericCOMObjectImpl()
         {
             return RuntimeTypeHandle.IsComObject(this, true);
@@ -5308,27 +5038,22 @@ namespace System
         #endregion
 
         #region Legacy Static Internal
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern Object _CreateEnum(RuntimeType enumType, long value);
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Object CreateEnum(RuntimeType enumType, long value)
         {
             return _CreateEnum(enumType, value);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern Object InvokeDispMethod(
             String name, BindingFlags invokeAttr, Object target, Object[] args,
             bool[] byrefModifiers, int culture, String[] namedParameters);
 
 #if FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern Type GetTypeFromProgIDImpl(String progID, String server, bool throwOnError);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern Type GetTypeFromCLSIDImpl(Guid clsid, String server, bool throwOnError);
 #else // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
@@ -5346,213 +5071,6 @@ namespace System
         #endregion
 
         #region COM
-#if FEATURE_COMINTEROP && FEATURE_REMOTING
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        private Object ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, int[] aWrapperTypes, ref MessageData msgData)
-        {
-            ParameterModifier[] aParamMod = null;
-            Object ret = null;
-
-            // Allocate a new message
-            Message reqMsg = new Message();
-            reqMsg.InitFields(msgData);
-
-            // Retrieve the required information from the message object.
-            MethodInfo meth = (MethodInfo)reqMsg.GetMethodBase();
-            Object[] aArgs = reqMsg.Args;
-            int cArgs = aArgs.Length;
-
-            // Retrieve information from the method we are invoking on.
-            ParameterInfo[] aParams = meth.GetParametersNoCopy();
-
-            // If we have arguments, then set the byref flags to true for byref arguments. 
-            // We also wrap the arguments that require wrapping.
-            if (cArgs > 0)
-            {
-                ParameterModifier paramMod = new ParameterModifier(cArgs);
-                for (int i = 0; i < cArgs; i++)
-                {
-                    if (aParams[i].ParameterType.IsByRef)
-                        paramMod[i] = true;
-                }
-
-                aParamMod = new ParameterModifier[1];
-                aParamMod[0] = paramMod;
-
-                if (aWrapperTypes != null)
-                    WrapArgsForInvokeCall(aArgs, aWrapperTypes);
-            }
-            
-            // If the method has a void return type, then set the IgnoreReturn binding flag.
-            if (Object.ReferenceEquals(meth.ReturnType, typeof(void)))
-                flags |= BindingFlags.IgnoreReturn;
-
-            try
-            {
-                // Invoke the method using InvokeMember().
-                ret = InvokeMember(memberName, flags, null, target, aArgs, aParamMod, null, null);
-            }
-            catch (TargetInvocationException e)
-            {
-                // For target invocation exceptions, we need to unwrap the inner exception and
-                // re-throw it.
-                throw e.InnerException;
-            }
-
-            // Convert each byref argument that is not of the proper type to
-            // the parameter type using the OleAutBinder.
-            for (int i = 0; i < cArgs; i++)
-            {
-                if (aParamMod[0][i] && aArgs[i] != null)
-                {
-                    // The parameter is byref.
-                    Type paramType = aParams[i].ParameterType.GetElementType();
-                    if (!Object.ReferenceEquals(paramType, aArgs[i].GetType()))
-                        aArgs[i] = ForwardCallBinder.ChangeType(aArgs[i], paramType, null);
-                }
-            }
-
-            // If the return type is not of the proper type, then convert it
-            // to the proper type using the OleAutBinder.
-            if (ret != null)
-            {
-                Type retType = meth.ReturnType;
-                if (!Object.ReferenceEquals(retType, ret.GetType()))
-                    ret = ForwardCallBinder.ChangeType(ret, retType, null);
-            }
-
-            // Propagate the out parameters
-            RealProxy.PropagateOutParameters(reqMsg, aArgs, ret);
-
-            // Return the value returned by the InvokeMember call.
-            return ret;
-        }
-
-        [SecuritySafeCritical]
-        private void WrapArgsForInvokeCall(Object[] aArgs, int[] aWrapperTypes)
-        {
-            int cArgs = aArgs.Length;
-            for (int i = 0; i < cArgs; i++)
-            {
-                if (aWrapperTypes[i] == 0)
-                    continue;
-
-                if (((DispatchWrapperType)aWrapperTypes[i] & DispatchWrapperType.SafeArray) != 0)
-                {
-                    Type wrapperType = null;
-                    bool isString = false;
-
-                    // Determine the type of wrapper to use.
-                    switch ((DispatchWrapperType)aWrapperTypes[i] & ~DispatchWrapperType.SafeArray)
-                    {
-                        case DispatchWrapperType.Unknown:
-                            wrapperType = typeof(UnknownWrapper);
-                            break;
-                        case DispatchWrapperType.Dispatch:
-                            wrapperType = typeof(DispatchWrapper);
-                            break;
-                        case DispatchWrapperType.Error:   
-                            wrapperType = typeof(ErrorWrapper);
-                            break;
-                        case DispatchWrapperType.Currency:
-                            wrapperType = typeof(CurrencyWrapper);
-                            break;
-                        case DispatchWrapperType.BStr:
-                            wrapperType = typeof(BStrWrapper);
-                            isString = true;
-                            break;
-                        default:
-                            Contract.Assert(false, "[RuntimeType.WrapArgsForInvokeCall]Invalid safe array wrapper type specified.");
-                            break;
-                    }
-
-                    // Allocate the new array of wrappers.
-                    Array oldArray = (Array)aArgs[i];
-                    int numElems = oldArray.Length;
-                    Object[] newArray = (Object[])Array.UnsafeCreateInstance(wrapperType, numElems);
-
-                    // Retrieve the ConstructorInfo for the wrapper type.
-                    ConstructorInfo wrapperCons;
-                    if(isString)
-                    {
-                         wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(String)});
-                    }
-                    else
-                    {
-                         wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(Object)});
-                    }
-                
-                    // Wrap each of the elements of the array.
-                    for (int currElem = 0; currElem < numElems; currElem++)
-                    {
-                        if(isString)
-                        {
-                            newArray[currElem] = wrapperCons.Invoke(new Object[] {(String)oldArray.GetValue(currElem)});
-                        }
-                        else
-                        {
-                            newArray[currElem] = wrapperCons.Invoke(new Object[] {oldArray.GetValue(currElem)});
-                        }
-                    }
-
-                    // Update the argument.
-                    aArgs[i] = newArray;
-                }
-                else
-                {                           
-                    // Determine the wrapper to use and then wrap the argument.
-                    switch ((DispatchWrapperType)aWrapperTypes[i])
-                    {
-                        case DispatchWrapperType.Unknown:
-                            aArgs[i] = new UnknownWrapper(aArgs[i]);
-                            break;
-                        case DispatchWrapperType.Dispatch:
-                            aArgs[i] = new DispatchWrapper(aArgs[i]);
-                            break;
-                        case DispatchWrapperType.Error:   
-                            aArgs[i] = new ErrorWrapper(aArgs[i]);
-                            break;
-                        case DispatchWrapperType.Currency:
-                            aArgs[i] = new CurrencyWrapper(aArgs[i]);
-                            break;
-                        case DispatchWrapperType.BStr:
-                            aArgs[i] = new BStrWrapper((String)aArgs[i]);
-                            break;
-                        default:
-                            Contract.Assert(false, "[RuntimeType.WrapArgsForInvokeCall]Invalid wrapper type specified.");
-                            break;
-                    }
-                }
-            }
-        }
-
-        private OleAutBinder ForwardCallBinder 
-        {
-            get 
-            {
-                // Synchronization is not required.
-                if (s_ForwardCallBinder == null)
-                    s_ForwardCallBinder = new OleAutBinder();
-
-                return s_ForwardCallBinder;
-            }
-        }
-
-        [Flags]
-        private enum DispatchWrapperType : int
-        {
-            // This enum must stay in sync with the DispatchWrapperType enum defined in MLInfo.h
-            Unknown         = 0x00000001,
-            Dispatch        = 0x00000002,
-            Record          = 0x00000004,
-            Error           = 0x00000008,
-            Currency        = 0x00000010,
-            BStr            = 0x00000020,
-            SafeArray       = 0x00010000
-        }
-
-        private static volatile OleAutBinder s_ForwardCallBinder;
-#endif // FEATURE_COMINTEROP && FEATURE_REMOTING
         #endregion
     }
 
@@ -5584,21 +5102,17 @@ namespace System
     #region Library
     internal unsafe struct Utf8String
     {
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern unsafe bool EqualsCaseSensitive(void* szLhs, void* szRhs, int cSz);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern unsafe bool EqualsCaseInsensitive(void* szLhs, void* szRhs, int cSz);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern unsafe uint HashCaseInsensitive(void* sz, int cSz);
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static int GetUtf8StringByteLength(void* pUtf8String)
         {
             int len = 0;
@@ -5617,11 +5131,9 @@ namespace System
             return len;
         }
 
-        [SecurityCritical]
         private void* m_pStringHeap;        // This is the raw UTF8 string.
         private int m_StringHeapByteLength;
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal Utf8String(void* pStringHeap)
         {
             m_pStringHeap = pStringHeap;
@@ -5635,14 +5147,12 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe Utf8String(void* pUtf8String, int cUtf8String)
         {
             m_pStringHeap = pUtf8String;
             m_StringHeapByteLength = cUtf8String;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe bool Equals(Utf8String s)
         {
             if (m_pStringHeap == null)
@@ -5656,7 +5166,6 @@ namespace System
             return false;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe bool EqualsCaseInsensitive(Utf8String s)
         {
             if (m_pStringHeap == null)
@@ -5670,13 +5179,11 @@ namespace System
             return false;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe uint HashCaseInsensitive()
         {
             return Utf8String.HashCaseInsensitive(m_pStringHeap, m_StringHeapByteLength);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override string ToString()
         {
             unsafe
@@ -5754,7 +5261,7 @@ namespace System.Reflection
                     }
                     else
                     {
-                        Contract.Assert(!hit.Equals(key), "Key was already in CerHashtable!  Potential race condition (or bug) in the Reflection cache?");
+                        Debug.Assert(!hit.Equals(key), "Key was already in CerHashtable!  Potential race condition (or bug) in the Reflection cache?");
 
                         index++;
                         if (index >= keys.Length)
index 11f5327..6a16462 100644 (file)
@@ -32,7 +32,6 @@ namespace System.Runtime.CompilerServices
     /// Provides a builder for asynchronous methods that return void.
     /// This type is intended for compiler use only.
     /// </summary>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public struct AsyncVoidMethodBuilder
     {
         /// <summary>The synchronization context associated with this operation.</summary>
@@ -59,7 +58,6 @@ namespace System.Runtime.CompilerServices
         /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
         /// <param name="stateMachine">The state machine instance, passed by reference.</param>
         /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
-        [SecuritySafeCritical]
         [DebuggerStepThrough]
         public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
         {
@@ -112,7 +110,7 @@ namespace System.Runtime.CompilerServices
             {
                 AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
                 var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
-                Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+                Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
 
                 // If this is our first await, such that we've not yet boxed the state machine, do so now.
                 if (m_coreState.m_stateMachine == null)
@@ -149,7 +147,6 @@ namespace System.Runtime.CompilerServices
         /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
         /// <param name="awaiter">The awaiter.</param>
         /// <param name="stateMachine">The state machine.</param>
-        [SecuritySafeCritical]
         public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
             ref TAwaiter awaiter, ref TStateMachine stateMachine)
             where TAwaiter : ICriticalNotifyCompletion
@@ -159,7 +156,7 @@ namespace System.Runtime.CompilerServices
             {
                 AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
                 var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
-                Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+                Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
 
                 // If this is our first await, such that we've not yet boxed the state machine, do so now.
                 if (m_coreState.m_stateMachine == null)
@@ -231,7 +228,7 @@ namespace System.Runtime.CompilerServices
         /// <summary>Notifies the current synchronization context that the operation completed.</summary>
         private void NotifySynchronizationContextOfCompletion()
         {
-            Contract.Assert(m_synchronizationContext != null, "Must only be used with a non-null context.");
+            Debug.Assert(m_synchronizationContext != null, "Must only be used with a non-null context.");
             try
             {
                 m_synchronizationContext.OperationCompleted();
@@ -273,7 +270,6 @@ namespace System.Runtime.CompilerServices
     /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed,
     /// or else the copies may end up building distinct Task instances.
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public struct AsyncTaskMethodBuilder
     {
         /// <summary>A cached VoidTaskResult task used for builders that complete synchronously.</summary>
@@ -294,7 +290,6 @@ namespace System.Runtime.CompilerServices
         /// <summary>Initiates the builder's execution with the associated state machine.</summary>
         /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
         /// <param name="stateMachine">The state machine instance, passed by reference.</param>
-        [SecuritySafeCritical]
         [DebuggerStepThrough]
         public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
         {
@@ -421,7 +416,6 @@ namespace System.Runtime.CompilerServices
     /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed,
     /// or else the copies may end up building distinct Task instances.
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public struct AsyncTaskMethodBuilder<TResult>
     {
         /// <summary>A cached task for default(TResult).</summary>
@@ -450,7 +444,6 @@ namespace System.Runtime.CompilerServices
         /// <summary>Initiates the builder's execution with the associated state machine.</summary>
         /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
         /// <param name="stateMachine">The state machine instance, passed by reference.</param>
-        [SecuritySafeCritical]
         [DebuggerStepThrough]
         public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
         {
@@ -503,7 +496,7 @@ namespace System.Runtime.CompilerServices
             {
                 AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
                 var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
-                Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+                Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
 
                 // If this is our first await, such that we've not yet boxed the state machine, do so now.
                 if (m_coreState.m_stateMachine == null)
@@ -534,7 +527,6 @@ namespace System.Runtime.CompilerServices
         /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
         /// <param name="awaiter">The awaiter.</param>
         /// <param name="stateMachine">The state machine.</param>
-        [SecuritySafeCritical]
         public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
             ref TAwaiter awaiter, ref TStateMachine stateMachine)
             where TAwaiter : ICriticalNotifyCompletion
@@ -544,7 +536,7 @@ namespace System.Runtime.CompilerServices
             {
                 AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
                 var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
-                Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+                Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
 
                 // If this is our first await, such that we've not yet boxed the state machine, do so now.
                 if (m_coreState.m_stateMachine == null)
@@ -595,7 +587,7 @@ namespace System.Runtime.CompilerServices
             if (task == null)
             {
                 m_task = GetTaskForResult(result);
-                Contract.Assert(m_task != null, "GetTaskForResult should never return null");
+                Debug.Assert(m_task != null, "GetTaskForResult should never return null");
             }
             // Slow path: complete the existing task.
             else
@@ -713,7 +705,6 @@ namespace System.Runtime.CompilerServices
         /// </summary>
         /// <param name="result">The result for which we need a task.</param>
         /// <returns>The completed task containing the result.</returns>
-        [SecuritySafeCritical] // for JitHelpers.UnsafeCast
         private Task<TResult> GetTaskForResult(TResult result)
         {
             Contract.Ensures(
@@ -819,7 +810,7 @@ namespace System.Runtime.CompilerServices
         /// <summary>Creates an array of cached tasks for the values in the range [INCLUSIVE_MIN,EXCLUSIVE_MAX).</summary>
         private static Task<Int32>[] CreateInt32Tasks()
         {
-            Contract.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min");
+            Debug.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min");
             var tasks = new Task<Int32>[EXCLUSIVE_INT32_MAX - INCLUSIVE_INT32_MIN];
             for (int i = 0; i < tasks.Length; i++)
             {
@@ -854,7 +845,6 @@ namespace System.Runtime.CompilerServices
         /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
         /// <param name="stateMachine">The state machine instance, passed by reference.</param>
         /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument is null (Nothing in Visual Basic).</exception>
-        [SecuritySafeCritical]
         [DebuggerStepThrough]
         internal static void Start<TStateMachine>(ref TStateMachine stateMachine)
             where TStateMachine : IAsyncStateMachine
@@ -902,10 +892,9 @@ namespace System.Runtime.CompilerServices
         /// <param name="builder">The builder.</param>
         /// <param name="stateMachine">The state machine.</param>
         /// <returns>An Action to provide to the awaiter.</returns>
-        [SecuritySafeCritical]
         internal Action GetCompletionAction(Task taskForTracing, ref MoveNextRunner runnerToInitialize)
         {
-            Contract.Assert(m_defaultContextAction == null || m_stateMachine != null,
+            Debug.Assert(m_defaultContextAction == null || m_stateMachine != null,
                 "Expected non-null m_stateMachine on non-null m_defaultContextAction");
 
             // Alert a listening debugger that we can't make forward progress unless it slips threads.
@@ -928,7 +917,7 @@ namespace System.Runtime.CompilerServices
                 action = m_defaultContextAction;
                 if (action != null)
                 {
-                    Contract.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well.");
+                    Debug.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well.");
                     return action;
                 }
 
@@ -994,8 +983,8 @@ namespace System.Runtime.CompilerServices
             m_stateMachine = stateMachine;
             m_stateMachine.SetStateMachine(m_stateMachine);
 
-            Contract.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated.");
-            Contract.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized.");
+            Debug.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated.");
+            Debug.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized.");
 
             // Now that we have the state machine, store it into the runner that the action delegate points to.
             // And return the action.
@@ -1045,17 +1034,15 @@ namespace System.Runtime.CompilerServices
 
             /// <summary>Initializes the runner.</summary>
             /// <param name="context">The context with which to run MoveNext.</param>
-            [SecurityCritical] // Run needs to be SSC to map to Action delegate, so to prevent misuse, we only allow construction through SC
             internal MoveNextRunnerWithContext(ExecutionContext context, IAsyncStateMachine stateMachine) : base(stateMachine)
             {
                 m_context = context;
             }
 
             /// <summary>Invokes MoveNext under the provided context.</summary>
-            [SecuritySafeCritical]
             internal void RunWithCapturedContext()
             {
-                Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
+                Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
 
                 if (m_context != null)
                 {
@@ -1080,34 +1067,29 @@ namespace System.Runtime.CompilerServices
             internal IAsyncStateMachine m_stateMachine;
 
             /// <summary>Initializes the runner.</summary>
-            [SecurityCritical] // Run needs to be SSC to map to Action delegate, so to prevent misuse, we only allow construction through SC
             internal MoveNextRunner(IAsyncStateMachine stateMachine)
             {
                 m_stateMachine = stateMachine;
             }
 
             /// <summary>Invokes MoveNext under the default context.</summary>
-            [SecuritySafeCritical]
             internal void RunWithDefaultContext()
             {
-                Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
+                Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
                 ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, InvokeMoveNextCallback, m_stateMachine, preserveSyncCtx: true);
             }
 
             /// <summary>Gets a delegate to the InvokeMoveNext method.</summary>
             protected static ContextCallback InvokeMoveNextCallback
             {
-                [SecuritySafeCritical]
                 get { return s_invokeMoveNext ?? (s_invokeMoveNext = InvokeMoveNext); }
             }
 
             /// <summary>Cached delegate used with ExecutionContext.Run.</summary>
-            [SecurityCritical]
             private static ContextCallback s_invokeMoveNext; // lazily-initialized due to SecurityCritical attribution
 
             /// <summary>Invokes the MoveNext method on the supplied IAsyncStateMachine.</summary>
             /// <param name="stateMachine">The IAsyncStateMachine machine instance.</param>
-            [SecurityCritical] // necessary for ContextCallback in CoreCLR
             private static void InvokeMoveNext(object stateMachine)
             {
                 ((IAsyncStateMachine)stateMachine).MoveNext();
index 5531e4a..7455967 100644 (file)
 **    may be delayed until appdomain shutdown.
 ===========================================================*/
 
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Threading;
+
 namespace System.Runtime.CompilerServices
 {
-    using System;
-    using System.Collections.Generic;
-    using System.Runtime.Versioning;
-    using System.Runtime.InteropServices;
-
-
     #region ConditionalWeakTable
-    [System.Runtime.InteropServices.ComVisible(false)]
+    [ComVisible(false)]
     public sealed class ConditionalWeakTable<TKey, TValue>
         where TKey : class
         where TValue : class
     {
+        #region Fields
+        private const int InitialCapacity = 8;  // Initial length of the table. Must be a power of two.
+        private readonly object _lock;          // This lock protects all mutation of data in the table.  Readers do not take this lock.
+        private volatile Container _container;  // The actual storage for the table; swapped out as the table grows.
+        #endregion
 
         #region Constructors
-        [System.Security.SecuritySafeCritical]
         public ConditionalWeakTable()
         {
-            _buckets = Array.Empty<int>();
-            _entries = Array.Empty<Entry>();
-            _freeList = -1;
-            _lock = new Object();
-
-            Resize();   // Resize at once (so won't need "if initialized" checks all over)
+            _lock = new object();
+            _container = new Container(this);
         }
         #endregion
 
@@ -99,18 +97,14 @@ namespace System.Runtime.CompilerServices
         // Note: The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue
         // may at its discretion, return "false" and set "value" to the default (as if the key was not present.)
         //--------------------------------------------------------------------------------------------
-        [System.Security.SecuritySafeCritical]
         public bool TryGetValue(TKey key, out TValue value)
         {
             if (key == null)
             {
                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
             }
-            lock(_lock)
-            {
-                VerifyIntegrity();
-                return TryGetValueWorker(key, out value);
-            }
+
+            return _container.TryGetValueWorker(key, out value);
         }
 
         //--------------------------------------------------------------------------------------------
@@ -123,7 +117,6 @@ namespace System.Runtime.CompilerServices
         // has the right to consider any prior entries successfully removed and add a new entry without
         // throwing an exception.
         //--------------------------------------------------------------------------------------------
-        [System.Security.SecuritySafeCritical]
         public void Add(TKey key, TValue value)
         {
             if (key == null)
@@ -131,22 +124,48 @@ namespace System.Runtime.CompilerServices
                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
             }
 
-            lock(_lock)
+            lock (_lock)
             {
-                VerifyIntegrity();
-                _invalid = true;
-
-                int entryIndex = FindEntry(key);
+                object otherValue;
+                int entryIndex = _container.FindEntry(key, out otherValue);
                 if (entryIndex != -1)
                 {
-                    _invalid = false;
                     ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
                 }
 
                 CreateEntry(key, value);
-                _invalid = false;
             }
+        }
+
+        //--------------------------------------------------------------------------------------------
+        // key: key to add or update. May not be null.
+        // value: value to associate with key.
+        //
+        // If the key is already entered into the dictionary, this method will update the value associated with key.
+        //--------------------------------------------------------------------------------------------
+        public void AddOrUpdate(TKey key, TValue value)
+        {
+            if (key == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+            }
+
+            lock (_lock)
+            {
+                object otherValue;
+                int entryIndex = _container.FindEntry(key, out otherValue);
+
+                // if we found a key we should just update, if no we should create a new entry.
+                if (entryIndex != -1)
+                {
+                    _container.UpdateValue(entryIndex, value);
+                }
+                else
+                {
+                    CreateEntry(key, value);
+                }
 
+            }
         }
 
         //--------------------------------------------------------------------------------------------
@@ -156,9 +175,8 @@ namespace System.Runtime.CompilerServices
         //
         // Note: The key may get garbage collected during the Remove() operation. If so,
         // Remove() will not fail or throw, however, the return value can be either true or false
-        // depending on the race condition.
+        // depending on who wins the race.
         //--------------------------------------------------------------------------------------------
-        [System.Security.SecuritySafeCritical]
         public bool Remove(TKey key)
         {
             if (key == null)
@@ -166,40 +184,9 @@ namespace System.Runtime.CompilerServices
                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
             }
 
-            lock(_lock)
+            lock (_lock)
             {
-                VerifyIntegrity();
-                _invalid = true;
-
-                int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
-                int bucket = hashCode % _buckets.Length;
-                int last = -1;
-                for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
-                {
-                    if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key)
-                    {
-                        if (last == -1)
-                        {
-                            _buckets[bucket] = _entries[entriesIndex].next;
-                        }
-                        else
-                        {
-                            _entries[last].next = _entries[entriesIndex].next;
-                        }
-    
-                        _entries[entriesIndex].depHnd.Free();
-                        _entries[entriesIndex].next = _freeList;
-
-                        _freeList = entriesIndex;
-
-                        _invalid = false;
-                        return true;
-                        
-                    }
-                    last = entriesIndex;
-                }
-                _invalid = false;
-                return false;
+                return _container.Remove(key);
             }
         }
 
@@ -219,15 +206,9 @@ namespace System.Runtime.CompilerServices
         // This rule permits the table to invoke createValueCallback outside the internal table lock
         // to prevent deadlocks.
         //--------------------------------------------------------------------------------------------
-        [System.Security.SecuritySafeCritical]
         public TValue GetValue(TKey key, CreateValueCallback createValueCallback)
         {
-            // Our call to TryGetValue() validates key so no need for us to.
-            //
-            //  if (key == null)
-            //  {
-            //      ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
-            //  }
+            // key is validated by TryGetValue
 
             if (createValueCallback == null)
             {
@@ -235,30 +216,29 @@ namespace System.Runtime.CompilerServices
             }
 
             TValue existingValue;
-            if (TryGetValue(key, out existingValue))
-            {
-                return existingValue;
-            }
+            return TryGetValue(key, out existingValue) ?
+                existingValue :
+                GetValueLocked(key, createValueCallback);
+        }
 
-            // If we got here, the key is not currently in table. Invoke the callback (outside the lock)
+        private TValue GetValueLocked(TKey key, CreateValueCallback createValueCallback)
+        {
+            // If we got here, the key was not in the table. Invoke the callback (outside the lock)
             // to generate the new value for the key. 
             TValue newValue = createValueCallback(key);
 
-            lock(_lock)
+            lock (_lock)
             {
-                VerifyIntegrity();
-                _invalid = true;
-                
-                // Now that we've retaken the lock, must recheck in case there was a race condition to add the key.
-                if (TryGetValueWorker(key, out existingValue))
+                // Now that we've taken the lock, must recheck in case we lost a race to add the key.
+                TValue existingValue;
+                if (_container.TryGetValueWorker(key, out existingValue))
                 {
-                    _invalid = false;
                     return existingValue;
                 }
                 else
                 {
+                    // Verified in-lock that we won the race to add the key. Add it now.
                     CreateEntry(key, newValue);
-                    _invalid = false;
                     return newValue;
                 }
             }
@@ -271,17 +251,15 @@ namespace System.Runtime.CompilerServices
         // to create new instances as needed.  If TValue does not have a default constructor, this will
         // throw.
         //--------------------------------------------------------------------------------------------
-        public TValue GetOrCreateValue(TKey key)
-        {
-            return GetValue(key, k => Activator.CreateInstance<TValue>());
-        }
+
+        public TValue GetOrCreateValue(TKey key) => GetValue(key, _ => Activator.CreateInstance<TValue>());
 
         public delegate TValue CreateValueCallback(TKey key);
-        
+
         #endregion
 
-        #region internal members
-        
+        #region Internal members
+
         //--------------------------------------------------------------------------------------------
         // Find a key that equals (value equality) with the given key - don't use in perf critical path
         // Note that it calls out to Object.Equals which may calls the override version of Equals
@@ -290,56 +268,26 @@ namespace System.Runtime.CompilerServices
         // if you know for sure that either you won't run into dead locks or you need to live with the
         // possiblity
         //--------------------------------------------------------------------------------------------
-        [System.Security.SecuritySafeCritical]
         [FriendAccessAllowed]
         internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value)
         {
             lock (_lock)
             {
-                for (int bucket = 0; bucket < _buckets.Length; ++bucket)
-                {
-                    for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
-                    {
-                        object thisKey, thisValue;
-                        _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue);
-                        if (Object.Equals(thisKey, key))
-                        {
-                            value = (TValue) thisValue;
-                            return (TKey) thisKey;
-                        }
-                    }
-                }
+                return _container.FindEquivalentKeyUnsafe(key, out value);
             }
-            
-            value = default(TValue);
-            return null;        
         }
-        
+
         //--------------------------------------------------------------------------------------------
         // Returns a collection of keys - don't use in perf critical path
         //--------------------------------------------------------------------------------------------
         internal ICollection<TKey> Keys
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
-                List<TKey> list = new List<TKey>();
                 lock (_lock)
                 {
-                    for (int bucket = 0; bucket < _buckets.Length; ++bucket)
-                    {
-                        for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
-                        {
-                            TKey thisKey = (TKey) _entries[entriesIndex].depHnd.GetPrimary();
-                            if (thisKey != null)
-                            {
-                                list.Add(thisKey);
-                            }
-                        }
-                    }
+                    return _container.Keys;
                 }
-                
-                return list;        
             }
         }
 
@@ -348,332 +296,500 @@ namespace System.Runtime.CompilerServices
         //--------------------------------------------------------------------------------------------
         internal ICollection<TValue> Values
         {
-            [System.Security.SecuritySafeCritical]
             get
             {
-                List<TValue> list = new List<TValue>();
                 lock (_lock)
                 {
-                    for (int bucket = 0; bucket < _buckets.Length; ++bucket)
-                    {
-                        for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
-                        {
-                            Object primary = null;
-                            Object secondary = null;
-
-                            _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, 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 condition where TryGetValue misreports an
-                            // expired key as a live key with a null value.)
-                            if (primary != null)
-                            {
-                                list.Add((TValue)secondary);
-                            }
-                        }
-                    }
+                    return _container.Values;
                 }
-                
-                return list;        
             }
         }
-        
+
         //--------------------------------------------------------------------------------------------
         // Clear all the key/value pairs
         //--------------------------------------------------------------------------------------------
-        [System.Security.SecuritySafeCritical]
         internal void Clear()
         {
             lock (_lock)
             {
-                // Clear the buckets
-                for (int bucketIndex = 0; bucketIndex < _buckets.Length; bucketIndex++)
-                {
-                    _buckets[bucketIndex] = -1;
-                }
-
-                // Clear the entries and link them backwards together as part of free list
-                int entriesIndex;
-                for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
-                {
-                    if (_entries[entriesIndex].depHnd.IsAllocated)
-                    {
-                        _entries[entriesIndex].depHnd.Free();
-                    }
-
-                    // Link back wards as free list
-                    _entries[entriesIndex].next = entriesIndex - 1;
-                }
-
-                _freeList = entriesIndex - 1;
-            }            
+                _container = new Container(this);
+            }
         }
 
         #endregion
-        
+
         #region Private Members
-        [System.Security.SecurityCritical]
+
         //----------------------------------------------------------------------------------------
-        // Worker for finding a key/value pair
+        // Worker for adding a new key/value pair.
+        // Will resize the container if it is full
         //
         // Preconditions:
         //     Must hold _lock.
-        //     Key already validated as non-null
+        //     Key already validated as non-null and not already in table.
         //----------------------------------------------------------------------------------------
-        private bool TryGetValueWorker(TKey key, out TValue value)
+        private void CreateEntry(TKey key, TValue value)
         {
-            int entryIndex = FindEntry(key);
-            if (entryIndex != -1)
+            Debug.Assert(Monitor.IsEntered(_lock));
+
+            Container c = _container;
+            if (!c.HasCapacity)
             {
-                Object primary = null;
-                Object secondary = null;
-                _entries[entryIndex].depHnd.GetPrimaryAndSecondary(out primary, 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 condition where TryGetValue misreports an
-                // expired key as a live key with a null value.)
-                if (primary != null)
-                {
-                    value = (TValue)secondary;
-                    return true;
-                }
+                _container = c = c.Resize();
             }
+            c.CreateEntryNoResize(key, value);
+        }
+
+        private static bool IsPowerOfTwo(int value) => (value > 0) && ((value & (value - 1)) == 0);
 
-            value = default(TValue);
-            return false;
+        #endregion
+
+        #region Private Data Members
+        //--------------------------------------------------------------------------------------------
+        // Entry can be in one of four states:
+        //
+        //    - Unused (stored with an index _firstFreeEntry and above)
+        //         depHnd.IsAllocated == false
+        //         hashCode == <dontcare>
+        //         next == <dontcare>)
+        //
+        //    - Used with live key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry)
+        //         depHnd.IsAllocated == true, depHnd.GetPrimary() != null
+        //         hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue
+        //         next links to next Entry in bucket. 
+        //                          
+        //    - Used with dead key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry)
+        //         depHnd.IsAllocated == true, depHnd.GetPrimary() == null
+        //         hashCode == <notcare> 
+        //         next links to next Entry in bucket. 
+        //
+        //    - Has been removed from the table (by a call to Remove)
+        //         depHnd.IsAllocated == true, depHnd.GetPrimary() == <notcare>
+        //         hashCode == -1 
+        //         next links to next Entry in bucket. 
+        //
+        // The only difference between "used with live key" and "used with dead key" is that
+        // depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key"
+        // happens asynchronously as a result of normal garbage collection. The dictionary itself
+        // receives no notification when this happens.
+        //
+        // When the dictionary grows the _entries table, it scours it for expired keys and does not
+        // add those to the new container.
+        //--------------------------------------------------------------------------------------------
+        private struct Entry
+        {
+            public DependentHandle depHnd;      // Holds key and value using a weak reference for the key and a strong reference
+                                                // for the value that is traversed only if the key is reachable without going through the value.
+            public int HashCode;    // Cached copy of key's hashcode
+            public int Next;        // Index of next entry, -1 if last
         }
 
-        //----------------------------------------------------------------------------------------
-        // Worker for adding a new key/value pair.
         //
-        // Preconditions:
-        //     Must hold _lock.
-        //     Key already validated as non-null and not already in table.
-        //----------------------------------------------------------------------------------------
-        [System.Security.SecurityCritical]
-        private void CreateEntry(TKey key, TValue value)
+        // Container holds the actual data for the table.  A given instance of Container always has the same capacity.  When we need
+        // more capacity, we create a new Container, copy the old one into the new one, and discard the old one.  This helps enable lock-free
+        // reads from the table, as readers never need to deal with motion of entries due to rehashing.
+        //
+        private sealed class Container
         {
-            if (_freeList == -1)
+            private readonly ConditionalWeakTable<TKey, TValue> _parent;  // the ConditionalWeakTable with which this container is associated
+            private int[] _buckets;                // _buckets[hashcode & (_buckets.Length - 1)] contains index of the first entry in bucket (-1 if empty)
+            private Entry[] _entries;              // the table entries containing the stored dependency handles
+            private int _firstFreeEntry;           // _firstFreeEntry < _entries.Length => table has capacity,  entries grow from the bottom of the table.
+            private bool _invalid;                 // flag detects if OOM or other background exception threw us out of the lock.
+            private bool _finalized;               // set to true when initially finalized
+            private volatile object _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd
+
+            internal Container(ConditionalWeakTable<TKey, TValue> parent)
             {
-                Resize();
+                Debug.Assert(parent != null);
+                Debug.Assert(IsPowerOfTwo(InitialCapacity));
+
+                int size = InitialCapacity;
+                _buckets = new int[size];
+                for (int i = 0; i < _buckets.Length; i++)
+                {
+                    _buckets[i] = -1;
+                }
+                _entries = new Entry[size];
+
+                // Only store the parent after all of the allocations have happened successfully.
+                // Otherwise, as part of growing or clearing the container, we could end up allocating
+                // a new Container that fails (OOMs) part way through construction but that gets finalized
+                // and ends up clearing out some other container present in the associated CWT.
+                _parent = parent;
             }
 
-            int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
-            int bucket = hashCode % _buckets.Length;
+            private Container(ConditionalWeakTable<TKey, TValue> parent, int[] buckets, Entry[] entries, int firstFreeEntry)
+            {
+                Debug.Assert(parent != null);
+                Debug.Assert(buckets != null);
+                Debug.Assert(entries != null);
+                Debug.Assert(buckets.Length == entries.Length);
+                Debug.Assert(IsPowerOfTwo(buckets.Length));
+
+                _parent = parent;
+                _buckets = buckets;
+                _entries = entries;
+                _firstFreeEntry = firstFreeEntry;
+            }
 
-            int newEntry = _freeList;
-            _freeList = _entries[newEntry].next;
+            internal bool HasCapacity => _firstFreeEntry < _entries.Length;
 
-            _entries[newEntry].hashCode = hashCode;
-            _entries[newEntry].depHnd = new DependentHandle(key, value);
-            _entries[newEntry].next = _buckets[bucket];
+            //----------------------------------------------------------------------------------------
+            // Worker for adding a new key/value pair.
+            // Preconditions:
+            //     Container must NOT be full
+            //----------------------------------------------------------------------------------------
+            internal void CreateEntryNoResize(TKey key, TValue value)
+            {
+                Debug.Assert(HasCapacity);
 
-            _buckets[bucket] = newEntry;
+                VerifyIntegrity();
+                _invalid = true;
 
-        }
+                int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue;
+                int newEntry = _firstFreeEntry++;
 
-        //----------------------------------------------------------------------------------------
-        // This does two things: resize and scrub expired keys off bucket lists.
-        //
-        // Precondition:
-        //      Must hold _lock.
-        //
-        // Postcondition:
-        //      _freeList is non-empty on exit.
-        //----------------------------------------------------------------------------------------
-        [System.Security.SecurityCritical]
-        private void Resize()
-        {
-            // Start by assuming we won't resize.
-            int newSize = _buckets.Length;
+                _entries[newEntry].HashCode = hashCode;
+                _entries[newEntry].depHnd = new DependentHandle(key, value);
+                int bucket = hashCode & (_buckets.Length - 1);
+                _entries[newEntry].Next = _buckets[bucket];
+
+                // This write must be volatile, as we may be racing with concurrent readers.  If they see
+                // the new entry, they must also see all of the writes earlier in this method.
+                Volatile.Write(ref _buckets[bucket], newEntry);
+
+                _invalid = false;
+            }
 
-            // If any expired keys exist, we won't resize.
-            bool hasExpiredEntries = false;
-            int entriesIndex;
-            for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
+            //----------------------------------------------------------------------------------------
+            // Worker for finding a key/value pair
+            //
+            // Preconditions:
+            //     Must hold _lock.
+            //     Key already validated as non-null
+            //----------------------------------------------------------------------------------------
+            internal bool TryGetValueWorker(TKey key, out TValue value)
             {
-                if ( _entries[entriesIndex].depHnd.IsAllocated && _entries[entriesIndex].depHnd.GetPrimary() == null)
+                object secondary;
+                int entryIndex = FindEntry(key, out secondary);
+                value = JitHelpers.UnsafeCast<TValue>(secondary);
+                return entryIndex != -1;
+            }
+
+            //----------------------------------------------------------------------------------------
+            // Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.")
+            //
+            // Preconditions:
+            //     Must hold _lock, or be prepared to retry the search while holding _lock.
+            //     Key already validated as non-null.
+            //----------------------------------------------------------------------------------------
+            internal int FindEntry(TKey key, out object value)
+            {
+                int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue;
+                int bucket = hashCode & (_buckets.Length - 1);
+                for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
                 {
-                    hasExpiredEntries = true;
-                    break;
+                    if (_entries[entriesIndex].HashCode == hashCode)
+                    {
+                        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.
+                value = null;
+                return -1;
             }
 
-            if (!hasExpiredEntries)
+            internal bool Remove(TKey key)
             {
-                newSize = System.Collections.HashHelpers.GetPrime(_buckets.Length == 0 ? _initialCapacity + 1 : _buckets.Length * 2);
+                VerifyIntegrity();
+
+                object value;
+                int entryIndex = FindEntry(key, out value);
+                if (entryIndex != -1)
+                {
+                    ref Entry entry = ref _entries[entryIndex];
+
+                    // We do not free the handle here, as we may be racing with readers who already saw the hash code.
+                    // Instead, we simply overwrite the entry's hash code, so subsequent reads will ignore it.
+                    // The handle will be free'd in Container's finalizer, after the table is resized or discarded.
+                    Volatile.Write(ref entry.HashCode, -1);
+
+                    // Also, clear the key to allow GC to collect objects pointed to by the entry
+                    entry.depHnd.SetPrimary(null);
+
+                    return true;
+                }
+
+                return false;
             }
 
 
-            // Reallocate both buckets and entries and rebuild the bucket and freelists from scratch.
-            // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket.
-            int newFreeList = -1;
-            int[] newBuckets = new int[newSize];
-            for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++)
+            internal void UpdateValue(int entryIndex, TValue newValue)
             {
-                newBuckets[bucketIndex] = -1;
+                Debug.Assert(entryIndex != -1);
+
+                VerifyIntegrity();
+                _invalid = true;
+
+                _entries[entryIndex].depHnd.SetSecondary(newValue);
+
+                _invalid = false;
             }
-            Entry[] newEntries = new Entry[newSize];
 
-            // Migrate existing entries to the new table.
-            for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
+            //----------------------------------------------------------------------------------------
+            // This does two things: resize and scrub expired keys off bucket lists.
+            //
+            // Precondition:
+            //      Must hold _lock.
+            //
+            // Postcondition:
+            //      _firstEntry is less than _entries.Length on exit, that is, the table has at least one free entry.
+            //----------------------------------------------------------------------------------------
+            internal Container Resize()
             {
-                DependentHandle depHnd = _entries[entriesIndex].depHnd;
-                if (depHnd.IsAllocated && depHnd.GetPrimary() != null)
+                // Start by assuming we won't resize.
+                int newSize = _buckets.Length;
+
+                // If any expired or removed keys exist, we won't resize.
+                bool hasExpiredEntries = false;
+                for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
                 {
-                    // Entry is used and has not expired. Link it into the appropriate bucket list.
-                    int bucket = _entries[entriesIndex].hashCode % newSize;
-                    newEntries[entriesIndex].depHnd = depHnd;
-                    newEntries[entriesIndex].hashCode = _entries[entriesIndex].hashCode;
-                    newEntries[entriesIndex].next = newBuckets[bucket];
-                    newBuckets[bucket] = entriesIndex;
+                    if (_entries[entriesIndex].HashCode == -1)
+                    {
+                        // the entry was removed
+                        hasExpiredEntries = true;
+                        break;
+                    }
+
+                    if (_entries[entriesIndex].depHnd.IsAllocated && _entries[entriesIndex].depHnd.GetPrimary() == null)
+                    {
+                        // the entry has expired
+                        hasExpiredEntries = true;
+                        break;
+                    }
                 }
-                else
+
+                if (!hasExpiredEntries)
                 {
-                    // Entry has either expired or was on the freelist to begin with. Either way
-                    // insert it on the new freelist.
-                    _entries[entriesIndex].depHnd.Free();
-                    newEntries[entriesIndex].depHnd = new DependentHandle();
-                    newEntries[entriesIndex].next = newFreeList;
-                    newFreeList = entriesIndex;
+                    // Not necessary to check for overflow here, the attempt to allocate new arrays will throw
+                    newSize = _buckets.Length * 2;
                 }
+
+                return Resize(newSize);
             }
 
-            // Add remaining entries to freelist.
-            while (entriesIndex != newEntries.Length)
+            internal Container Resize(int newSize)
             {
-                newEntries[entriesIndex].depHnd = new DependentHandle();
-                newEntries[entriesIndex].next = newFreeList;
-                newFreeList = entriesIndex;
-                entriesIndex++;
-            }
+                Debug.Assert(IsPowerOfTwo(newSize));
 
-            _buckets = newBuckets;
-            _entries = newEntries;
-            _freeList = newFreeList;
-        }
+                // Reallocate both buckets and entries and rebuild the bucket and entries from scratch.
+                // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket.
+                int[] newBuckets = new int[newSize];
+                for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++)
+                {
+                    newBuckets[bucketIndex] = -1;
+                }
+                Entry[] newEntries = new Entry[newSize];
+                int newEntriesIndex = 0;
 
-        //----------------------------------------------------------------------------------------
-        // Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.")
-        //
-        // Preconditions:
-        //     Must hold _lock.
-        //     Key already validated as non-null.
-        //----------------------------------------------------------------------------------------
-        [System.Security.SecurityCritical]
-        private int FindEntry(TKey key)
-        {
-            int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
-            for (int entriesIndex = _buckets[hashCode % _buckets.Length]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
+                // Migrate existing entries to the new table.
+                for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
+                {
+                    int hashCode = _entries[entriesIndex].HashCode;
+                    DependentHandle depHnd = _entries[entriesIndex].depHnd;
+                    if (hashCode != -1 && depHnd.IsAllocated)
+                    {
+                        if (depHnd.GetPrimary() != null)
+                        {
+                            // Entry is used and has not expired. Link it into the appropriate bucket list.
+                            newEntries[newEntriesIndex].HashCode = hashCode;
+                            newEntries[newEntriesIndex].depHnd = depHnd;
+                            int bucket = hashCode & (newBuckets.Length - 1);
+                            newEntries[newEntriesIndex].Next = newBuckets[bucket];
+                            newBuckets[bucket] = newEntriesIndex;
+                            newEntriesIndex++;
+                        }
+                        else
+                        {
+                            // Pretend the item was removed, so that this container's finalizer
+                            // will clean up this dependent handle.
+                            Volatile.Write(ref _entries[entriesIndex].HashCode, -1);
+                        }
+                    }
+                }
+
+                // Create the new container.  We want to transfer the responsibility of freeing the handles from
+                // the old container to the new container, and also ensure that the new container isn't finalized
+                // while the old container may still be in use.  As such, we store a reference from the old container
+                // to the new one, which will keep the new container alive as long as the old one is.
+                var newContainer = new Container(_parent, newBuckets, newEntries, newEntriesIndex);
+                _oldKeepAlive = newContainer; // once this is set, the old container's finalizer will not free transferred dependent handles
+
+                GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+
+                return newContainer;
+            }
+
+            internal ICollection<TKey> Keys
             {
-                if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key)
+                get
                 {
-                    return entriesIndex;
+                    var list = new List<TKey>();
+
+                    for (int bucket = 0; bucket < _buckets.Length; ++bucket)
+                    {
+                        for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
+                        {
+                            TKey thisKey = JitHelpers.UnsafeCast<TKey>(_entries[entriesIndex].depHnd.GetPrimary());
+                            if (thisKey != null)
+                            {
+                                list.Add(thisKey);
+                            }
+                        }
+                    }
+
+                    GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+                    return list;
                 }
             }
-            return -1;
-        }
 
-        //----------------------------------------------------------------------------------------
-        // Precondition:
-        //     Must hold _lock.
-        //----------------------------------------------------------------------------------------
-        private void VerifyIntegrity()
-        {
-            if (_invalid)
+            internal ICollection<TValue> Values
             {
-                throw new InvalidOperationException(Environment.GetResourceString("CollectionCorrupted"));
+                get
+                {
+                    var list = new List<TValue>();
+
+                    for (int bucket = 0; bucket < _buckets.Length; ++bucket)
+                    {
+                        for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
+                        {
+                            object primary = null, secondary = null;
+                            _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, 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
+                            // expired key as a live key with a null value.)
+                            if (primary != null)
+                            {
+                                list.Add(JitHelpers.UnsafeCast<TValue>(secondary));
+                            }
+                        }
+                    }
+
+                    GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+                    return list;
+                }
             }
-        }
 
-        //----------------------------------------------------------------------------------------
-        // Finalizer.
-        //----------------------------------------------------------------------------------------
-        [System.Security.SecuritySafeCritical]
-        ~ConditionalWeakTable()
-        {
+            internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value)
+            {
+                for (int bucket = 0; bucket < _buckets.Length; ++bucket)
+                {
+                    for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
+                    {
+                        if (_entries[entriesIndex].HashCode == -1)
+                        {
+                            continue;   // removed entry whose handle is awaiting condemnation by the finalizer.
+                        }
 
-            // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD,
-            // don't bother.
-            //
-            // (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.)
-            if (Environment.HasShutdownStarted)
+                        object thisKey, thisValue;
+                        _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue);
+                        if (Equals(thisKey, key))
+                        {
+                            GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+                            value = JitHelpers.UnsafeCast<TValue>(thisValue);
+                            return JitHelpers.UnsafeCast<TKey>(thisKey);
+                        }
+                    }
+                }
+
+                GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+                value = default(TValue);
+                return null;
+            }
+
+            //----------------------------------------------------------------------------------------
+            // Precondition:
+            //     Must hold _lock.
+            //----------------------------------------------------------------------------------------
+            private void VerifyIntegrity()
             {
-                return;
+                if (_invalid)
+                {
+                    throw new InvalidOperationException(Environment.GetResourceString("CollectionCorrupted"));
+                }
             }
 
-            if (_lock != null)
+            //----------------------------------------------------------------------------------------
+            // Finalizer.
+            //----------------------------------------------------------------------------------------
+            ~Container()
             {
-                lock(_lock)
+                // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD,
+                // don't bother. (Despite its name, Environment.HasShutdownStart also returns true if the current
+                // AD is finalizing.)  We also skip doing anything if the container is invalid, including if someone
+                // the container object was allocated but its associated table never set.
+                if (Environment.HasShutdownStarted || _invalid || _parent == null)
                 {
-                    if (_invalid)
+                    return;
+                }
+
+                // It's possible that the ConditionalWeakTable could have been resurrected, in which case code could
+                // be accessing this Container as it's being finalized.  We don't support usage after finalization,
+                // but we also don't want to potentially corrupt state by allowing dependency handles to be used as
+                // or after they've been freed.  To avoid that, if it's at all possible that another thread has a
+                // reference to this container via the CWT, we remove such a reference and then re-register for
+                // finalization: the next time around, we can be sure that no references remain to this and we can
+                // clean up the dependency handles without fear of corruption.
+                if (!_finalized)
+                {
+                    _finalized = true;
+                    lock (_parent._lock)
                     {
-                        return;
+                        if (_parent._container == this)
+                        {
+                            _parent._container = null;
+                        }
                     }
-                    Entry[] entries = _entries;
+                    GC.ReRegisterForFinalize(this); // next time it's finalized, we'll be sure there are no remaining refs
+                    return;
+                }
 
-                    // Make sure anyone sneaking into the table post-resurrection
-                    // gets booted before they can damage the native handle table.
-                    _invalid = true;
-                    _entries = null;
-                    _buckets = null;
+                Entry[] entries = _entries;
+                _invalid = true;
+                _entries = null;
+                _buckets = null;
 
+                if (entries != null)
+                {
                     for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++)
                     {
-                        entries[entriesIndex].depHnd.Free();
+                        // We need to free handles in two cases:
+                        // - If this container still owns the dependency handle (meaning ownership hasn't been transferred
+                        //   to another container that replaced this one), then it should be freed.
+                        // - If this container had the entry removed, then even if in general ownership was transferred to
+                        //   another container, removed entries are not, therefore this container must free them.
+                        if (_oldKeepAlive == null || entries[entriesIndex].HashCode == -1)
+                        {
+                            entries[entriesIndex].depHnd.Free();
+                        }
                     }
                 }
             }
         }
         #endregion
-
-        #region Private Data Members
-        //--------------------------------------------------------------------------------------------
-        // Entry can be in one of three states:
-        //
-        //    - Linked into the freeList (_freeList points to first entry)
-        //         depHnd.IsAllocated == false
-        //         hashCode == <dontcare>
-        //         next links to next Entry on freelist)
-        //
-        //    - Used with live key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry)
-        //         depHnd.IsAllocated == true, depHnd.GetPrimary() != null
-        //         hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue
-        //         next links to next Entry in bucket. 
-        //                          
-        //    - Used with dead key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry)
-        //         depHnd.IsAllocated == true, depHnd.GetPrimary() == null
-        //         hashCode == <notcare> 
-        //         next links to next Entry in bucket. 
-        //
-        // The only difference between "used with live key" and "used with dead key" is that
-        // depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key"
-        // happens asynchronously as a result of normal garbage collection. The dictionary itself
-        // receives no notification when this happens.
-        //
-        // When the dictionary grows the _entries table, it scours it for expired keys and puts those
-        // entries back on the freelist.
-        //--------------------------------------------------------------------------------------------
-        private struct Entry
-        {
-            public DependentHandle depHnd;      // Holds key and value using a weak reference for the key and a strong reference
-                                                // for the value that is traversed only if the key is reachable without going through the value.
-            public int             hashCode;    // Cached copy of key's hashcode
-            public int             next;        // Index of next entry, -1 if last
-        }
-
-        private int[]     _buckets;             // _buckets[hashcode & _buckets.Length] contains index of first entry in bucket (-1 if empty)
-        private Entry[]   _entries;              
-        private int       _freeList;            // -1 = empty, else index of first unused Entry
-        private const int _initialCapacity = 5;
-        private readonly Object _lock;          // this could be a ReaderWriterLock but CoreCLR does not support RWLocks.
-        private bool      _invalid;             // flag detects if OOM or other background exception threw us out of the lock.
-        #endregion
     }
     #endregion
 
-
-
-
     #region DependentHandle
     //=========================================================================================
     // This struct collects all operations on native DependentHandles. The DependentHandle
@@ -700,15 +816,10 @@ namespace System.Runtime.CompilerServices
     // to use DependentHandles in a thread-safe way.
     //=========================================================================================
     [ComVisible(false)]
-    struct DependentHandle
+    internal struct DependentHandle
     {
         #region Constructors
-        #if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-        #else
-        [System.Security.SecurityCritical]
-        #endif
-        public DependentHandle(Object primary, Object secondary)
+        public DependentHandle(object primary, object secondary)
         {
             IntPtr handle = (IntPtr)0;
             nInitialize(primary, secondary, out handle);
@@ -718,44 +829,37 @@ namespace System.Runtime.CompilerServices
         #endregion
 
         #region Public Members
-        public bool IsAllocated
-        {
-            get
-            {
-                return _handle != (IntPtr)0;
-            }
-        }
+        public bool IsAllocated => _handle != IntPtr.Zero;
 
         // Getting the secondary object is more expensive than getting the first so
         // we provide a separate primary-only accessor for those times we only want the
         // primary.
-        #if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-        #else
-        [System.Security.SecurityCritical]
-        #endif
-        public Object GetPrimary()
+        public object GetPrimary()
         {
-            Object primary;
+            object primary;
             nGetPrimary(_handle, out primary);
             return primary;
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-        #else
-        [System.Security.SecurityCritical]
-        #endif
-        public void GetPrimaryAndSecondary(out Object primary, out Object secondary)
+        public void GetPrimaryAndSecondary(out object primary, out object secondary)
         {
             nGetPrimaryAndSecondary(_handle, out primary, out secondary);
         }
 
+        public void SetPrimary(object primary)
+        {
+            nSetPrimary(_handle, primary);
+        }
+
+        public void SetSecondary(object secondary)
+        {
+            nSetSecondary(_handle, secondary);
+        }
+
         //----------------------------------------------------------------------
         // Forces dependentHandle back to non-allocated state (if not already there)
         // and frees the handle if needed.
         //----------------------------------------------------------------------
-        [System.Security.SecurityCritical]
         public void Free()
         {
             if (_handle != (IntPtr)0)
@@ -768,20 +872,22 @@ namespace System.Runtime.CompilerServices
         #endregion
 
         #region Private Members
-        [System.Security.SecurityCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern void nInitialize(Object primary, Object secondary, out IntPtr dependentHandle);
+        [MethodImpl(MethodImplOptions.InternalCall)]
+        private static extern void nInitialize(object primary, object secondary, out IntPtr dependentHandle);
+
+        [MethodImpl(MethodImplOptions.InternalCall)]
+        private static extern void nGetPrimary(IntPtr dependentHandle, out object primary);
 
-        [System.Security.SecurityCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern void nGetPrimary(IntPtr dependentHandle, out Object primary);
+        [MethodImpl(MethodImplOptions.InternalCall)]
+        private static extern void nGetPrimaryAndSecondary(IntPtr dependentHandle, out object primary, out object secondary);
 
-        [System.Security.SecurityCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern void nGetPrimaryAndSecondary(IntPtr dependentHandle, out Object primary, out Object secondary);
+        [MethodImpl(MethodImplOptions.InternalCall)]
+        private static extern void nSetPrimary(IntPtr dependentHandle, object primary);
 
-        [System.Security.SecurityCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
+        [MethodImpl(MethodImplOptions.InternalCall)]
+        private static extern void nSetSecondary(IntPtr dependentHandle, object secondary);
+
+        [MethodImpl(MethodImplOptions.InternalCall)]
         private static extern void nFree(IntPtr dependentHandle);
         #endregion
 
@@ -792,4 +898,3 @@ namespace System.Runtime.CompilerServices
     } // struct DependentHandle
     #endregion
 }
-
index 39a4c86..7bfaa7a 100644 (file)
@@ -6,6 +6,7 @@
 // Note: If you add a new ctor overloads you need to update ParameterInfo.RawDefaultValue
 
 using System.Reflection;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Collections.Generic;
 
@@ -57,16 +58,16 @@ namespace System.Runtime.CompilerServices
                 if (namedArgument.MemberInfo.Name.Equals("Value"))
                 {
                     // This is not possible because Decimal cannot be represented directly in the metadata.
-                    Contract.Assert(false, "Decimal cannot be represented directly in the metadata.");
+                    Debug.Assert(false, "Decimal cannot be represented directly in the metadata.");
                     return (Decimal)namedArgument.TypedValue.Value;
                 }
             }
 
             ParameterInfo[] parameters = attr.Constructor.GetParameters();
-            Contract.Assert(parameters.Length == 5);
+            Debug.Assert(parameters.Length == 5);
 
             System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attr.ConstructorArguments;
-            Contract.Assert(args.Count == 5);
+            Debug.Assert(args.Count == 5);
 
             if (parameters[2].ParameterType == typeof(uint))
             {
index 872a79b..aba0a06 100644 (file)
@@ -34,7 +34,6 @@ namespace System.Runtime.CompilerServices
         /// <param name="continuation">The action to invoke when the operation completes.</param>
         /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
         /// <remarks>Unlike OnCompleted, UnsafeOnCompleted need not propagate ExecutionContext information.</remarks>
-        [SecurityCritical]
         void UnsafeOnCompleted(Action continuation);
     }
 }
index 507593b..926eb6c 100644 (file)
@@ -25,16 +25,13 @@ namespace System.Runtime.CompilerServices {
 
     public static class RuntimeHelpers
     {
-#if FEATURE_CORECLR
         // Exposed here as a more appropriate place than on FormatterServices itself,
         // which is a high level reflection heavy type.
         public static Object GetUninitializedObject(Type type)
         {
             return FormatterServices.GetUninitializedObject(type);
         }
-#endif // FEATURE_CORECLR
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void InitializeArray(Array array,RuntimeFieldHandle fldHandle);
 
@@ -51,7 +48,6 @@ namespace System.Runtime.CompilerServices {
         // cloned when you pass them around, and are always passed by value.  
         // Of course, reference types are not cloned.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern Object GetObjectValue(Object obj);
 
@@ -63,7 +59,6 @@ namespace System.Runtime.CompilerServices {
         // This call will generate an exception if the specified class constructor threw an 
         // exception when it ran. 
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _RunClassConstructor(RuntimeType type);
 
@@ -80,7 +75,6 @@ namespace System.Runtime.CompilerServices {
         // This call will generate an exception if the specified module constructor threw an 
         // exception when it ran. 
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module);
 
@@ -90,12 +84,9 @@ namespace System.Runtime.CompilerServices {
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         internal static extern void _CompileMethod(IRuntimeMethodInfo method);
 
-
-        #if FEATURE_CORECLR
         public static void PrepareMethod(RuntimeMethodHandle method){}
         public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation){}
         public static void PrepareContractedDelegate(Delegate d){}
@@ -108,69 +99,9 @@ namespace System.Runtime.CompilerServices {
             }
         }
 
-        #else
-        
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static unsafe extern void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation);
-
-        // Simple (instantiation not required) method.
-        [System.Security.SecurityCritical]  // auto-generated_required
-        public static void PrepareMethod(RuntimeMethodHandle method) 
-        {
-            unsafe
-            {
-                _PrepareMethod(method.GetMethodInfo(), null, 0);
-            }
-        }
-
-        // Generic method or method with generic class with specific instantiation.
-        [System.Security.SecurityCritical]  // auto-generated_required
-        public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation)
-        {
-            unsafe
-            {
-                int length;
-                IntPtr[] instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length);
-                fixed (IntPtr* pInstantiation = instantiationHandles)
-                {
-                    _PrepareMethod(method.GetMethodInfo(), pInstantiation, length);
-                    GC.KeepAlive(instantiation);
-                }
-            }
-        }
-        // This method triggers a given delegate to be prepared.  This involves preparing the
-        // delegate's Invoke method and preparing the target of that Invoke.  In the case of
-        // a multi-cast delegate, we rely on the fact that each individual component was prepared
-        // prior to the Combine.  In other words, this service does not navigate through the
-        // entire multicasting list.
-        // If our own reliable event sinks perform the Combine (for example AppDomain.DomainUnload),
-        // then the result is fully prepared.  But if a client calls Combine himself and then
-        // then adds that combination to e.g. AppDomain.DomainUnload, then the client is responsible
-        // for his own preparation.
-        [System.Security.SecurityCritical]  // auto-generated_required
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        public static extern void PrepareDelegate(Delegate d);
-
-        // See comment above for PrepareDelegate
-        //
-        // PrepareContractedDelegate weakens this a bit by only assuring that we prepare 
-        // delegates which also have a ReliabilityContract. This is useful for services that
-        // want to provide opt-in reliability, generally some random event sink providing
-        // always reliable semantics to random event handlers that are likely to have not
-        // been written with relability in mind is a lost cause anyway.
-        //
-        // NOTE: that for the NGen case you can sidestep the required ReliabilityContract
-        // by using the [PrePrepareMethod] attribute.
-        [System.Security.SecurityCritical]  // auto-generated_required
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        public static extern void PrepareContractedDelegate(Delegate d);
-        #endif
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern int GetHashCode(Object o);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public new static extern bool Equals(Object o1, Object o2);
 
@@ -199,7 +130,6 @@ namespace System.Runtime.CompilerServices {
         // If there is not enough stack, then it throws System.InsufficientExecutionStackException.
         // Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
         // below.
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static extern void EnsureSufficientExecutionStack();
@@ -208,25 +138,16 @@ namespace System.Runtime.CompilerServices {
         // If there is not enough stack, then it return false.
         // Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
         // below.
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static extern bool TryEnsureSufficientExecutionStack();
 
-        #if FEATURE_CORECLR
         public static void ProbeForSufficientStack()
         {
         }
-        #else
-        [System.Security.SecurityCritical]  // auto-generated_required
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-        public static extern void ProbeForSufficientStack();
-        #endif
 
         // This method is a marker placed immediately before a try clause to mark the corresponding catch and finally blocks as
         // constrained. There's no code here other than the probe because most of the work is done at JIT time when we spot a call to this routine.
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public static void PrepareConstrainedRegions()
         {
@@ -235,29 +156,18 @@ namespace System.Runtime.CompilerServices {
 
         // When we detect a CER with no calls, we can point the JIT to this non-probing version instead
         // as we don't need to probe.
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public static void PrepareConstrainedRegionsNoOP()
         {
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public delegate void TryCode(Object userData);
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public delegate void CleanupCode(Object userData, bool exceptionThrown);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData);
 
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         [PrePrepareMethod]
         internal static void ExecuteBackoutCodeHelper(Object backoutCode, Object userData, bool exceptionThrown)
         {
index 8eb7435..d2691df 100644 (file)
@@ -33,7 +33,6 @@ namespace System.Runtime.CompilerServices {
 
         private Object m_wrappedException;
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info==null) {
                 throw new ArgumentNullException(nameof(info));
index 874895f..98a81ea 100644 (file)
@@ -57,7 +57,6 @@ namespace System.Runtime.CompilerServices
 {
     /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary>
     /// <remarks>This type is intended for compiler use only.</remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public struct TaskAwaiter : ICriticalNotifyCompletion
     {
         /// <summary>The task being awaited.</summary>
@@ -84,7 +83,6 @@ namespace System.Runtime.CompilerServices
         /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
         /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
         /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
-        [SecuritySafeCritical]
         public void OnCompleted(Action continuation)
         {
             OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
@@ -95,7 +93,6 @@ namespace System.Runtime.CompilerServices
         /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
         /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
         /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
-        [SecurityCritical]
         public void UnsafeOnCompleted(Action continuation)
         {
             OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
@@ -143,7 +140,7 @@ namespace System.Runtime.CompilerServices
             if (!task.IsCompleted)
             {
                 bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken));
-                Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed.");
+                Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed.");
             }
 
             // Now that we're done, alert the debugger if so requested
@@ -171,7 +168,7 @@ namespace System.Runtime.CompilerServices
                     if (oceEdi != null)
                     {
                         oceEdi.Throw();
-                        Contract.Assert(false, "Throw() should have thrown");
+                        Debug.Assert(false, "Throw() should have thrown");
                     }
                     throw new TaskCanceledException(task);
 
@@ -182,12 +179,12 @@ namespace System.Runtime.CompilerServices
                     if (edis.Count > 0)
                     {
                         edis[0].Throw();
-                        Contract.Assert(false, "Throw() should have thrown");
+                        Debug.Assert(false, "Throw() should have thrown");
                         break; // Necessary to compile: non-reachable, but compiler can't determine that
                     }
                     else
                     {
-                        Contract.Assert(false, "There should be exceptions if we're Faulted.");
+                        Debug.Assert(false, "There should be exceptions if we're Faulted.");
                         throw task.Exception;
                     }
             }
@@ -202,7 +199,6 @@ namespace System.Runtime.CompilerServices
         /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
         /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable         
-        [SecurityCritical]
         internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext)
         {
             if (continuation == null) throw new ArgumentNullException(nameof(continuation));
@@ -294,7 +290,6 @@ namespace System.Runtime.CompilerServices
 
     /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
     /// <remarks>This type is intended for compiler use only.</remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion
     {
         /// <summary>The task being awaited.</summary>
@@ -321,7 +316,6 @@ namespace System.Runtime.CompilerServices
         /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
         /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
         /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
-        [SecuritySafeCritical]
         public void OnCompleted(Action continuation)
         {
             TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
@@ -332,7 +326,6 @@ namespace System.Runtime.CompilerServices
         /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
         /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
         /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
-        [SecurityCritical]
         public void UnsafeOnCompleted(Action continuation)
         {
             TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
@@ -377,7 +370,6 @@ namespace System.Runtime.CompilerServices
 
         /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary>
         /// <remarks>This type is intended for compiler use only.</remarks>
-        [HostProtection(Synchronization = true, ExternalThreading = true)]
         public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion
         {
             /// <summary>The task being awaited.</summary>
@@ -411,7 +403,6 @@ namespace System.Runtime.CompilerServices
             /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
             /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
             /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
-            [SecuritySafeCritical]
             public void OnCompleted(Action continuation)
             {
                 TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
@@ -422,7 +413,6 @@ namespace System.Runtime.CompilerServices
             /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
             /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
             /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
-            [SecurityCritical]
             public void UnsafeOnCompleted(Action continuation)
             {
                 TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
@@ -466,7 +456,6 @@ namespace System.Runtime.CompilerServices
 
         /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary>
         /// <remarks>This type is intended for compiler use only.</remarks>
-        [HostProtection(Synchronization = true, ExternalThreading = true)]
         public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion
         {
             /// <summary>The task being awaited.</summary>
@@ -499,7 +488,6 @@ namespace System.Runtime.CompilerServices
             /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
             /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
             /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
-            [SecuritySafeCritical]
             public void OnCompleted(Action continuation)
             {
                 TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
@@ -510,7 +498,6 @@ namespace System.Runtime.CompilerServices
             /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
             /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
             /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
-            [SecurityCritical]
             public void UnsafeOnCompleted(Action continuation)
             {
                 TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
index 034dad1..d9e067b 100644 (file)
@@ -26,7 +26,6 @@ namespace System.Runtime.CompilerServices
             }
         }
 
-        [System.Security.SecurityCritical]
         internal static TypeForwardedToAttribute[] GetCustomAttribute(RuntimeAssembly assembly)
         {
             Type[] types = null;
index dec3388..86789bf 100644 (file)
@@ -48,7 +48,6 @@ namespace System.Runtime.CompilerServices
 
         /// <summary>Provides an awaiter that switches into a target environment.</summary>
         /// <remarks>This type is intended for compiler use only.</remarks>
-        [HostProtection(Synchronization = true, ExternalThreading = true)]
         public struct YieldAwaiter : ICriticalNotifyCompletion
         {
             /// <summary>Gets whether a yield is not required.</summary>
@@ -58,7 +57,6 @@ namespace System.Runtime.CompilerServices
             /// <summary>Posts the <paramref name="continuation"/> back to the current context.</summary>
             /// <param name="continuation">The action to invoke asynchronously.</param>
             /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
-            [SecuritySafeCritical]
             public void OnCompleted(Action continuation)
             {
                 QueueContinuation(continuation, flowContext: true);
@@ -67,7 +65,6 @@ namespace System.Runtime.CompilerServices
             /// <summary>Posts the <paramref name="continuation"/> back to the current context.</summary>
             /// <param name="continuation">The action to invoke asynchronously.</param>
             /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
-            [SecurityCritical]
             public void UnsafeOnCompleted(Action continuation)
             {
                 QueueContinuation(continuation, flowContext: false);
@@ -77,7 +74,6 @@ namespace System.Runtime.CompilerServices
             /// <param name="continuation">The action to invoke asynchronously.</param>
             /// <param name="flowContext">true to flow ExecutionContext; false if flowing is not required.</param>
             /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
-            [SecurityCritical]
             private static void QueueContinuation(Action continuation, bool flowContext)
             {
                 // Validate arguments
index a4c67aa..c1346f7 100644 (file)
@@ -11,6 +11,7 @@ using System;
 using System.Threading;
 using System.Runtime;
 using System.Runtime.Versioning;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Security;
@@ -74,7 +75,6 @@ namespace System.Runtime.CompilerServices {
 
         // Wraps object variable into a handle. Used to return managed strings from QCalls.
         // s has to be a local variable on the stack.
-        [SecurityCritical]
         static internal StringHandleOnStack GetStringHandleOnStack(ref string s)
         {
             return new StringHandleOnStack(UnsafeCastToStackPointer(ref s));
@@ -82,7 +82,6 @@ namespace System.Runtime.CompilerServices {
 
         // Wraps object variable into a handle. Used to pass managed object references in and out of QCalls.
         // o has to be a local variable on the stack.
-        [SecurityCritical]
         static internal ObjectHandleOnStack GetObjectHandleOnStack<T>(ref T o) where T : class
         {
             return new ObjectHandleOnStack(UnsafeCastToStackPointer(ref o));
@@ -90,25 +89,22 @@ namespace System.Runtime.CompilerServices {
 
         // Wraps StackCrawlMark into a handle. Used to pass StackCrawlMark to QCalls.
         // stackMark has to be a local variable on the stack.
-        [SecurityCritical]
         static internal StackCrawlMarkHandle GetStackCrawlMarkHandle(ref StackCrawlMark stackMark)
         {
             return new StackCrawlMarkHandle(UnsafeCastToStackPointer(ref stackMark));
         }
 
 #if _DEBUG
-        [SecurityCritical]
         [FriendAccessAllowed]
         static internal T UnsafeCast<T>(Object o) where T : class
         {
             T ret = UnsafeCastInternal<T>(o);
-            Contract.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!");
+            Debug.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!");
             return ret;
         }
 
         // The IL body of this method is not critical, but its body will be replaced with unsafe code, so
         // this method is effectively critical
-        [SecurityCritical]
         static private T UnsafeCastInternal<T>(Object o) where T : class
         {
             // The body of this function will be replaced by the EE with unsafe code that just returns o!!!
@@ -118,7 +114,7 @@ namespace System.Runtime.CompilerServices {
 
         static internal int UnsafeEnumCast<T>(T val) where T : struct          // Actually T must be 4 byte (or less) enum
         {
-            Contract.Assert(typeof(T).IsEnum 
+            Debug.Assert(typeof(T).IsEnum 
                               && (Enum.GetUnderlyingType(typeof(T)) == typeof(int) 
                                   || Enum.GetUnderlyingType(typeof(T)) == typeof(uint) 
                                   || Enum.GetUnderlyingType(typeof(T)) == typeof(short)
@@ -138,7 +134,7 @@ namespace System.Runtime.CompilerServices {
 
         static internal long UnsafeEnumCastLong<T>(T val) where T : struct             // Actually T must be 8 byte enum
         {
-            Contract.Assert(typeof(T).IsEnum 
+            Debug.Assert(typeof(T).IsEnum 
                               && (Enum.GetUnderlyingType(typeof(T)) == typeof(long) 
                                   || Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)), 
                 "Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!");
@@ -154,15 +150,13 @@ namespace System.Runtime.CompilerServices {
 
         // Internal method for getting a raw pointer for handles in JitHelpers.
         // The reference has to point into a local stack variable in order so it can not be moved by the GC.
-        [SecurityCritical]
         static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
         {
             IntPtr p = UnsafeCastToStackPointerInternal<T>(ref val);
-            Contract.Assert(IsAddressInStack(p), "Pointer not in the stack!");
+            Debug.Assert(IsAddressInStack(p), "Pointer not in the stack!");
             return p;
         }
 
-        [SecurityCritical]
         static private IntPtr UnsafeCastToStackPointerInternal<T>(ref T val)
         {
             // The body of this function will be replaced by the EE with unsafe code that just returns val!!!
@@ -172,7 +166,6 @@ namespace System.Runtime.CompilerServices {
 #else // _DEBUG
         // The IL body of this method is not critical, but its body will be replaced with unsafe code, so
         // this method is effectively critical
-        [SecurityCritical]
         [FriendAccessAllowed]
         static internal T UnsafeCast<T>(Object o) where T : class
         {
@@ -195,7 +188,6 @@ namespace System.Runtime.CompilerServices {
             throw new InvalidOperationException();
         }
 
-        [SecurityCritical]
         static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
         {
             // The body of this function will be replaced by the EE with unsafe code that just returns o!!!
@@ -205,12 +197,10 @@ namespace System.Runtime.CompilerServices {
 #endif // _DEBUG
 
         // Set the given element in the array without any type or range checks
-        [SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         extern static internal void UnsafeSetArrayElement(Object[] target, int index, Object element);
 
         // Used for unsafe pinning of arbitrary objects.
-        [System.Security.SecurityCritical]  // auto-generated
         static internal PinningHelper GetPinningHelper(Object o)
         {
             // This cast is really unsafe - call the private version that does not assert in debug
@@ -222,7 +212,6 @@ namespace System.Runtime.CompilerServices {
         }
 
 #if _DEBUG
-        [SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         extern static bool IsAddressInStack(IntPtr ptr);
 #endif
index 5b4be27..91997f5 100644 (file)
@@ -40,7 +40,6 @@ namespace System.Runtime {
 
         public static GCLatencyMode LatencyMode
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             get 
             {
@@ -48,8 +47,6 @@ namespace System.Runtime {
             }
 
             // We don't want to allow this API when hosted.
-            [System.Security.SecurityCritical]  // auto-generated_required
-            [HostProtection(MayLeakOnAbort = true)]
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             set 
             {
@@ -66,7 +63,6 @@ namespace System.Runtime {
 
         public static GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             get 
             {
@@ -74,8 +70,6 @@ namespace System.Runtime {
             }
 
             // We don't want to allow this API when hosted.
-            [System.Security.SecurityCritical]  // auto-generated_required
-            [HostProtection(MayLeakOnAbort = true)]
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             set 
             {
@@ -92,7 +86,6 @@ namespace System.Runtime {
 
         public static bool IsServerGC 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return GC.IsServerGC();
             }
index 83eae1c..77db3a7 100644 (file)
@@ -17,7 +17,6 @@ namespace System.Runtime.InteropServices {
         //    throw new Exception();
         //}
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public ArrayWithOffset(Object array, int offset)
         {
             m_array  = array;
@@ -64,7 +63,6 @@ namespace System.Runtime.InteropServices {
             return !(a == b);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern int CalculateCount();
     
index 06c963a..2de7304 100644 (file)
@@ -8,6 +8,7 @@ namespace System.Runtime.InteropServices{
 
     using System;
     using System.Reflection;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
@@ -525,31 +526,26 @@ namespace System.Runtime.InteropServices{
     [System.Runtime.InteropServices.ComVisible(true)]
     public unsafe sealed class MarshalAsAttribute : Attribute
     {
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
         {
             return GetCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeParameterInfo parameter)
         {
             return GetCustomAttribute(parameter) != null;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
         {
             return GetCustomAttribute(field.MetadataToken, field.GetRuntimeModule()); ;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeFieldInfo field)
         {
             return GetCustomAttribute(field) != null;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute GetCustomAttribute(int token, RuntimeModule scope)
         {
             UnmanagedType unmanagedType, arraySubType;
@@ -578,7 +574,7 @@ namespace System.Runtime.InteropServices{
             {
                 // The user may have supplied a bad type name string causing this TypeLoadException
                 // Regardless, we return the bad type name
-                Contract.Assert(marshalTypeName != null);
+                Debug.Assert(marshalTypeName != null);
             }
 
             return new MarshalAsAttribute(
@@ -772,7 +768,6 @@ namespace System.Runtime.InteropServices{
     [System.Runtime.InteropServices.ComVisible(true)]
     public unsafe sealed class DllImportAttribute : Attribute
     {
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute GetCustomAttribute(RuntimeMethodInfo method)
         {
             if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0)
@@ -869,7 +864,6 @@ namespace System.Runtime.InteropServices{
     {
         private const int DEFAULT_PACKING_SIZE = 8;
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute GetCustomAttribute(RuntimeType type)
         {
             if (!IsDefined(type))
@@ -940,7 +934,6 @@ namespace System.Runtime.InteropServices{
     [System.Runtime.InteropServices.ComVisible(true)]
     public unsafe sealed class FieldOffsetAttribute : Attribute
     {
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
         {
             int fieldOffset;
@@ -952,7 +945,6 @@ namespace System.Runtime.InteropServices{
             return null;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool IsDefined(RuntimeFieldInfo field)
         {
             return GetCustomAttribute(field) != null;
index 58e93a8..1673c91 100644 (file)
@@ -21,19 +21,11 @@ namespace System.Runtime.InteropServices {
 [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class BStrWrapper
     {
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand,Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         public BStrWrapper(String value)
         {
             m_WrappedObject = value;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         public BStrWrapper(Object value)
         {
             m_WrappedObject = (String)value;
index 95b925c..fd500fd 100644 (file)
@@ -46,7 +46,6 @@ namespace System.Runtime.InteropServices {
             SetErrorCode(errorCode);
         }
 
-        [SecuritySafeCritical]
         internal COMException(int hresult)
             : base(Win32Native.GetMessage(hresult))
         {
index 0bf616d..82692c1 100644 (file)
@@ -115,7 +115,6 @@ namespace System.Runtime.InteropServices {
         /// <param name="iid">identifier of the source interface used by COM object to fire events</param>
         /// <param name="dispid">dispatch identifier of the method on the source interface</param>
         /// <param name="d">delegate to invoke when specifed COM event is fired</param>
-        [System.Security.SecurityCritical]
         public static void Combine(object rcw, Guid iid, int dispid, System.Delegate d) {
 
             rcw = UnwrapIfTransparentProxy(rcw);
@@ -146,7 +145,6 @@ namespace System.Runtime.InteropServices {
         /// <param name="dispid">dispatch identifier of the method on the source interface</param>
         /// <param name="d">delegate to remove from the invocation list</param>
         /// <returns></returns>
-        [System.Security.SecurityCritical]
         public static Delegate Remove(object rcw, Guid iid, int dispid, System.Delegate d) {
 
             rcw = UnwrapIfTransparentProxy(rcw);
@@ -183,18 +181,8 @@ namespace System.Runtime.InteropServices {
             }
         }
 
-        [System.Security.SecurityCritical]
-        internal static object UnwrapIfTransparentProxy(object rcw) {
-#if FEATURE_REMOTING
-            if (RemotingServices.IsTransparentProxy(rcw)) {
-                IntPtr punk = Marshal.GetIUnknownForObject(rcw);
-                try {
-                    rcw = Marshal.GetObjectForIUnknown(punk);
-                } finally {
-                    Marshal.Release(punk);
-                }
-            }
-#endif
+        internal static object UnwrapIfTransparentProxy(object rcw)
+        {
             return rcw;
         }
     }
index 6feb524..2456ba3 100644 (file)
@@ -17,7 +17,6 @@ namespace System.Runtime.InteropServices {
     using ComTypes = System.Runtime.InteropServices.ComTypes;
 
     // see code:ComEventsHelper#ComEventsArchitecture
-    [System.Security.SecurityCritical]
     internal class ComEventsInfo {
 
 
@@ -35,7 +34,6 @@ namespace System.Runtime.InteropServices {
             _rcw = rcw;
         }
 
-        [System.Security.SecuritySafeCritical]
         ~ComEventsInfo() {
             // see code:ComEventsHelper#ComEventsFinalization
             _sinks = ComEventsSink.RemoveAll(_sinks);
@@ -46,13 +44,11 @@ namespace System.Runtime.InteropServices {
 
 #region static methods
 
-        [System.Security.SecurityCritical]
         internal static ComEventsInfo Find(object rcw) {
             return (ComEventsInfo)Marshal.GetComObjectData(rcw, typeof(ComEventsInfo));
         }
 
         // it is caller's responsibility to call this method under lock(rcw)
-        [System.Security.SecurityCritical]
         internal static ComEventsInfo FromObject(object rcw) {
             ComEventsInfo eventsInfo = Find(rcw);
             if (eventsInfo == null) {
@@ -80,7 +76,6 @@ namespace System.Runtime.InteropServices {
         }
 
         // it is caller's responsibility to call this method under lock(rcw)
-        [System.Security.SecurityCritical]
         internal ComEventsSink RemoveSink(ComEventsSink sink) {
             _sinks = ComEventsSink.Remove(_sinks, sink);
             return _sinks;
index a414eff..05978a6 100644 (file)
@@ -16,7 +16,6 @@ namespace System.Runtime.InteropServices {
     using System.Diagnostics;
 
     // see code:ComEventsHelper#ComEventsArchitecture
-    [System.Security.SecurityCritical]
     internal class ComEventsSink : NativeMethods.IDispatch, ICustomQueryInterface
     {
 #region private fields
@@ -57,7 +56,6 @@ namespace System.Runtime.InteropServices {
             return sink;
         }
 
-        [System.Security.SecurityCritical]
         internal static ComEventsSink RemoveAll(ComEventsSink sinks) {
             while (sinks != null) {
                 sinks.Unadvise();
@@ -67,7 +65,6 @@ namespace System.Runtime.InteropServices {
             return null;
         }
 
-        [System.Security.SecurityCritical]
         internal static ComEventsSink Remove(ComEventsSink sinks, ComEventsSink sink) {
             BCLDebug.Assert(sinks != null, "removing event sink from empty sinks collection");
             BCLDebug.Assert(sink != null, "specify event sink is null");
@@ -114,17 +111,14 @@ namespace System.Runtime.InteropServices {
 
 #region IDispatch Members
 
-        [System.Security.SecurityCritical]
         void NativeMethods.IDispatch.GetTypeInfoCount(out uint pctinfo) {
             pctinfo = 0;
         }
 
-        [System.Security.SecurityCritical]
         void NativeMethods.IDispatch.GetTypeInfo(uint iTInfo, int lcid, out IntPtr info) {
             throw new NotImplementedException();
         }
 
-        [System.Security.SecurityCritical]
         void NativeMethods.IDispatch.GetIDsOfNames(ref Guid iid, string[] names, uint cNames, int lcid, int[] rgDispId) {
             throw new NotImplementedException();
         }
@@ -149,7 +143,6 @@ namespace System.Runtime.InteropServices {
             return pSrc;
         }
 
-        [System.Security.SecurityCritical]
         unsafe void NativeMethods.IDispatch.Invoke(
             int dispid, 
             ref Guid riid, 
@@ -233,7 +226,6 @@ namespace System.Runtime.InteropServices {
 
         static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}");
 
-        [System.Security.SecurityCritical]
         CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) {
             ppv = IntPtr.Zero;
             if (iid == this._iidSourceItf || iid == typeof(NativeMethods.IDispatch).GUID) {
@@ -265,7 +257,6 @@ namespace System.Runtime.InteropServices {
             _connectionPoint = cp;
         }
 
-        [System.Security.SecurityCritical]
         private void Unadvise() {
             BCLDebug.Assert(_connectionPoint != null, "can not unadvise from empty connection point");
 
index 54fd6b0..700e059 100644 (file)
@@ -139,10 +139,6 @@ namespace System.Runtime.InteropServices
 // we'll do this to ensure we've cut off all attack vectors.  Similarly, all
 // methods have a link demand to ensure untrusted code cannot directly edit
 // or alter a handle.
-[System.Security.SecurityCritical]  // auto-generated_required
-#if !FEATURE_CORECLR
-[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
 public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
 {
     // ! Do not add or rearrange fields as the EE depends on this layout.
@@ -168,19 +164,15 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
 #endif
     }
 
-#if FEATURE_CORECLR
     // Adding an empty default constructor for annotation purposes
     private CriticalHandle(){} 
-#endif
 
-    [System.Security.SecuritySafeCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     ~CriticalHandle()
     {
         Dispose(false);
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     private void Cleanup()
     {
@@ -229,20 +221,17 @@ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
         get;
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     public void Close() {
         Dispose(true);
     }
     
-    [System.Security.SecuritySafeCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     public void Dispose()
     {
         Dispose(true);
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     protected virtual void Dispose(bool disposing)
     {
index 1fc72f7..47b7542 100644 (file)
@@ -21,10 +21,6 @@ namespace System.Runtime.InteropServices {
 [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class DispatchWrapper
     {
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand,Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         public DispatchWrapper(Object obj)
         {
             if (obj != null)
index aebc858..a9fa58f 100644 (file)
@@ -32,10 +32,6 @@ namespace System.Runtime.InteropServices {
             m_ErrorCode = (int)errorCode;
         }        
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         public ErrorWrapper(Exception e)
         {
             m_ErrorCode = Marshal.GetHRForException(e);
index 62718de..a12a38e 100644 (file)
@@ -34,7 +34,6 @@ namespace System.Runtime.InteropServices {
         // class for which the callbacks will be made. 
         // It is not legal to register this callback from a class that has any
         // parents that have already registered a callback.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void RegisterObjectCreationCallback(ObjectCreationDelegate callback);
     }
index f1a8804..5530819 100644 (file)
@@ -47,7 +47,6 @@ namespace System.Runtime.InteropServices
         private const GCHandleType MaxHandleType = GCHandleType.Pinned;
 
 #if MDA_SUPPORTED
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static GCHandle()
         {
             s_probeIsActive = Mda.IsInvalidGCHandleCookieProbeEnabled();
@@ -57,7 +56,6 @@ namespace System.Runtime.InteropServices
 #endif
 
         // Allocate a handle storing the object and the type.
-        [System.Security.SecurityCritical]  // auto-generated
         internal GCHandle(Object value, GCHandleType type)
         {
             // Make sure the type parameter is within the valid range for the enum.
@@ -73,7 +71,6 @@ namespace System.Runtime.InteropServices
         }  
 
         // Used in the conversion functions below.
-        [System.Security.SecurityCritical]  // auto-generated
         internal GCHandle(IntPtr handle)
         {
             InternalCheckDomain(handle);
@@ -86,13 +83,11 @@ namespace System.Runtime.InteropServices
         // type - The type of GC handle to create.
         // 
         // returns a new GC handle that protects the object.
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static GCHandle Alloc(Object value)
         {
             return new GCHandle(value, GCHandleType.Normal);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static GCHandle Alloc(Object value, GCHandleType type)
         {
             return new GCHandle(value, type);
@@ -100,7 +95,6 @@ namespace System.Runtime.InteropServices
 
 
         // Frees a GC handle.
-        [System.Security.SecurityCritical]  // auto-generated_required
         public void Free()
         {
             // Copy the handle instance member to a local variable. This is required to prevent
@@ -134,7 +128,6 @@ namespace System.Runtime.InteropServices
         // Target property - allows getting / updating of the handle's referent.
         public Object Target
         {
-            [System.Security.SecurityCritical]  // auto-generated_required
             get
             {
                 // Check if the handle was never initialized or was freed.
@@ -144,7 +137,6 @@ namespace System.Runtime.InteropServices
                 return InternalGet(GetHandleValue());
             }
     
-            [System.Security.SecurityCritical]  // auto-generated_required
             set
             {
                 // Check if the handle was never initialized or was freed.
@@ -157,7 +149,6 @@ namespace System.Runtime.InteropServices
         
         // Retrieve the address of an object in a Pinned handle.  This throws
         // an exception if the handle is any type other than Pinned.
-        [System.Security.SecurityCritical]  // auto-generated_required
         public IntPtr AddrOfPinnedObject()
         {
             // Check if the handle was not a pinned handle.
@@ -186,13 +177,11 @@ namespace System.Runtime.InteropServices
 
         // Used to create a GCHandle from an int.  This is intended to
         // be used with the reverse conversion.
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static explicit operator GCHandle(IntPtr value)
         {
             return FromIntPtr(value);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static GCHandle FromIntPtr(IntPtr value)
         {
             if (value == IntPtr.Zero)
@@ -293,28 +282,20 @@ namespace System.Runtime.InteropServices
         }
 
         // Internal native calls that this implementation uses.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern IntPtr InternalAlloc(Object value, GCHandleType type);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void InternalFree(IntPtr handle);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern Object InternalGet(IntPtr handle);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void InternalSet(IntPtr handle, Object value, bool isPinned);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern Object InternalCompareExchange(IntPtr handle, Object value, Object oldValue, bool isPinned);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern IntPtr InternalAddrOfPinnedObject(IntPtr handle);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void InternalCheckDomain(IntPtr handle);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern GCHandleType InternalGetHandleType(IntPtr handle);
 
index 61688b9..c7d7937 100644 (file)
@@ -33,7 +33,6 @@ namespace System.Runtime.InteropServices {
     [System.Runtime.InteropServices.ComVisible(false)]
     public interface ICustomQueryInterface
     {
-        [System.Security.SecurityCritical]
         CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv);
     }
 }
index 2da0a56..2330365 100644 (file)
@@ -22,48 +22,9 @@ namespace System.Runtime.InteropServices {
     [GuidAttribute("b36b5c63-42ef-38bc-a07e-0b34c98f164a")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
     [CLSCompliant(false)]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _Exception
     {
-#if !FEATURE_CORECLR
-        // This contains all of our V1 Exception class's members.
-
-        // From Object
-        String ToString();
-        bool Equals (Object obj);
-        int GetHashCode ();
-        Type GetType ();
-
-        // From V1's Exception class
-        String Message {
-            get;
-        }
-
-        Exception GetBaseException();
-
-        String StackTrace {
-            get;
-        }
-
-        String HelpLink {
-            get;
-            set;
-        }
-
-        String Source {
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
-            get;
-            #if FEATURE_CORECLR
-            [System.Security.SecurityCritical] // auto-generated
-            #endif
-            set;
-        }
-        [System.Security.SecurityCritical]  // auto-generated_required
-        void GetObjectData(SerializationInfo info, StreamingContext context);
-#endif
-
         //
         // This method is intentionally included in CoreCLR to make Exception.get_InnerException "newslot virtual final".
         // Some phone apps include MEF from desktop Silverlight. MEF's ComposablePartException depends on implicit interface 
@@ -73,12 +34,5 @@ namespace System.Runtime.InteropServices {
         Exception InnerException {
             get;
         }
-
-#if !FEATURE_CORECLR        
-        MethodBase TargetSite {
-            get;
-        }
-#endif
    }
-
 }
index ae330e8..f2f7c61 100644 (file)
@@ -31,24 +31,18 @@ namespace System.Runtime.InteropServices {
 [System.Runtime.InteropServices.ComVisible(true)]
     public interface IRegistrationServices
     {
-        [System.Security.SecurityCritical]  // auto-generated_required
         bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         bool UnregisterAssembly(Assembly assembly);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         Type[] GetRegistrableTypesInAssembly(Assembly assembly);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         String GetProgIdForType(Type type);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         void RegisterTypeForComClients(Type type, ref Guid g);
 
         Guid GetManagedCategoryGuid();
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         bool TypeRequiresRegistration(Type type);
 
         bool TypeRepresentsComType(Type type);
index 6e8f2bc..3a79650 100644 (file)
@@ -29,6 +29,7 @@ namespace System.Runtime.InteropServices
     using System.Runtime.Versioning;
     using Win32Native = Microsoft.Win32.Win32Native;
     using Microsoft.Win32.SafeHandles;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Runtime.InteropServices.ComTypes;
 
@@ -45,9 +46,6 @@ namespace System.Runtime.InteropServices
     // declaration on the class.
     //========================================================================
 
-    #if FEATURE_CORECLR
-    [System.Security.SecurityCritical] // auto-generated
-    #endif
     public static partial class Marshal
     { 
         //====================================================================
@@ -117,7 +115,6 @@ namespace System.Runtime.InteropServices
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int GetSystemMaxDBCSCharSize();
         
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static String PtrToStringAnsi(IntPtr ptr)
         {
             if (IntPtr.Zero == ptr) {
@@ -137,7 +134,6 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static String PtrToStringAnsi(IntPtr ptr, int len)
         {
             if (ptr == IntPtr.Zero)
@@ -148,7 +144,6 @@ namespace System.Runtime.InteropServices
             return new String((sbyte *)ptr, 0, len); 
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static String PtrToStringUni(IntPtr ptr, int len)
         {
             if (ptr == IntPtr.Zero)
@@ -159,14 +154,12 @@ namespace System.Runtime.InteropServices
             return new String((char *)ptr, 0, len);
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static String PtrToStringAuto(IntPtr ptr, int len)
         {
             // Ansi platforms are no longer supported
             return PtrToStringUni(ptr, len);
         }    
         
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static String PtrToStringUni(IntPtr ptr)
         {
             if (IntPtr.Zero == ptr) {
@@ -180,21 +173,18 @@ namespace System.Runtime.InteropServices
             }
         }
         
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static String PtrToStringAuto(IntPtr ptr)
         {
             // Ansi platforms are no longer supported
             return PtrToStringUni(ptr);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static String PtrToStringUTF8(IntPtr ptr)
         {
             int nbBytes = System.StubHelpers.StubHelpers.strlen((sbyte*)ptr.ToPointer());
             return PtrToStringUTF8(ptr, nbBytes);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static String PtrToStringUTF8(IntPtr ptr,int byteLen)
         {
             if (byteLen < 0)
@@ -290,9 +280,6 @@ namespace System.Runtime.InteropServices
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private static extern uint AlignedSizeOfType(Type type);
 
-#if !FEATURE_CORECLR // Marshal is critical in CoreCLR, so SafeCritical members trigger Annotator violations
-        [System.Security.SecuritySafeCritical]
-#endif // !FEATURE_CORECLR
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable);
 
@@ -330,11 +317,9 @@ namespace System.Runtime.InteropServices
         // an array that is not pinned or in the fixed heap can cause 
         // unexpected results !
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index);
 
-        [System.Security.SecurityCritical]
         public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
         {
             return UnsafeAddrOfPinnedArrayElement((Array)arr, index);
@@ -343,42 +328,34 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Copy blocks from CLR arrays to native memory.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(int[]     source, int startIndex, IntPtr destination, int length)
         {
             CopyToNative(source, startIndex, destination, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(char[]    source, int startIndex, IntPtr destination, int length)
         {
             CopyToNative(source, startIndex, destination, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(short[]   source, int startIndex, IntPtr destination, int length)
         {
             CopyToNative(source, startIndex, destination, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(long[]    source, int startIndex, IntPtr destination, int length)
         {
             CopyToNative(source, startIndex, destination, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(float[]   source, int startIndex, IntPtr destination, int length)
         {
             CopyToNative(source, startIndex, destination, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(double[]  source, int startIndex, IntPtr destination, int length)
         {
             CopyToNative(source, startIndex, destination, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
         {
             CopyToNative(source, startIndex, destination, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
         {
             CopyToNative(source, startIndex, destination, length);
@@ -389,42 +366,34 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Copy blocks from native memory to CLR arrays
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(IntPtr source, int[]     destination, int startIndex, int length)
         {
             CopyToManaged(source, destination, startIndex, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(IntPtr source, char[]    destination, int startIndex, int length)
         {
             CopyToManaged(source, destination, startIndex, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(IntPtr source, short[]   destination, int startIndex, int length)
         {
             CopyToManaged(source, destination, startIndex, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(IntPtr source, long[]    destination, int startIndex, int length)
         {
             CopyToManaged(source, destination, startIndex, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(IntPtr source, float[]   destination, int startIndex, int length)
         {
             CopyToManaged(source, destination, startIndex, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(IntPtr source, double[]  destination, int startIndex, int length)
         {
             CopyToManaged(source, destination, startIndex, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
         {
             CopyToManaged(source, destination, startIndex, length);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
         {
             CopyToManaged(source, destination, startIndex, length);
@@ -435,19 +404,11 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Read from memory
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [DllImport(Win32Native.SHIM, EntryPoint="ND_RU1")]
-        [SuppressUnmanagedCodeSecurity]
-        public static extern byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs);    
-#else
         public static byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
         {
             throw new PlatformNotSupportedException();
-        }    
-#endif // !FEATURE_CORECLR
+        }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static unsafe byte ReadByte(IntPtr ptr, int ofs)
         {
             try
@@ -462,25 +423,16 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static byte ReadByte(IntPtr ptr)
         {
             return ReadByte(ptr,0);
         }
-        
-        [System.Security.SecurityCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [DllImport(Win32Native.SHIM, EntryPoint="ND_RI2")]
-        [SuppressUnmanagedCodeSecurity]
-        public static extern short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);    
-#else
+
         public static short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
         {
             throw new PlatformNotSupportedException();
-        }    
-#endif // !FEATURE_CORECLR
+        }
  
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static unsafe short ReadInt16(IntPtr ptr, int ofs)
         {
             try
@@ -508,25 +460,16 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static short ReadInt16(IntPtr ptr)
         {
             return ReadInt16(ptr, 0);
         }
-    
-        [System.Security.SecurityCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [DllImport(Win32Native.SHIM, EntryPoint="ND_RI4"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [SuppressUnmanagedCodeSecurity]
-        public static extern int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);    
-#else
+
         public static int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
         {
             throw new PlatformNotSupportedException();
         }
-#endif // !FEATURE_CORECLR
  
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static unsafe int ReadInt32(IntPtr ptr, int ofs)
         {
@@ -557,14 +500,12 @@ namespace System.Runtime.InteropServices
             }
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static int ReadInt32(IntPtr ptr)
         {
             return ReadInt32(ptr,0);
         }
        
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
         {
@@ -575,7 +516,6 @@ namespace System.Runtime.InteropServices
             #endif
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
         {
@@ -586,7 +526,6 @@ namespace System.Runtime.InteropServices
             #endif
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static IntPtr ReadIntPtr(IntPtr ptr)
         {
@@ -597,19 +536,11 @@ namespace System.Runtime.InteropServices
             #endif
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [DllImport(Win32Native.SHIM, EntryPoint="ND_RI8"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [SuppressUnmanagedCodeSecurity]
-        public static extern long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);    
-#else
         public static long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
         {
             throw new PlatformNotSupportedException();
         }
-#endif // !FEATURE_CORECLR
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static unsafe long ReadInt64(IntPtr ptr, int ofs)
         {
             try
@@ -643,7 +574,6 @@ namespace System.Runtime.InteropServices
             }
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static long ReadInt64(IntPtr ptr)
         {
@@ -654,7 +584,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Write to memory
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
         {
             try
@@ -669,25 +598,16 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [DllImport(Win32Native.SHIM, EntryPoint="ND_WU1")]
-        [SuppressUnmanagedCodeSecurity]
-        public static extern void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val);    
-#else
         public static void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val)
         {
             throw new PlatformNotSupportedException();
         }
-#endif // !FEATURE_CORECLR
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void WriteByte(IntPtr ptr, byte val)
         {
             WriteByte(ptr, 0, val);
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
         {
             try
@@ -712,44 +632,32 @@ namespace System.Runtime.InteropServices
                 throw new AccessViolationException();
             }
         }
-    
-        [System.Security.SecurityCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [DllImport(Win32Native.SHIM, EntryPoint="ND_WI2")]
-        [SuppressUnmanagedCodeSecurity]
-        public static extern void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val);
-#else
+
         public static void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val)
         {
             throw new PlatformNotSupportedException();
         }
-#endif // !FEATURE_CORECLR
-                
-        [System.Security.SecurityCritical]  // auto-generated_required
+
         public static void WriteInt16(IntPtr ptr, short val)
         {
             WriteInt16(ptr, 0, val);
         }    
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void WriteInt16(IntPtr ptr, int ofs, char val)
         {
             WriteInt16(ptr, ofs, (short)val);
         }
         
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void WriteInt16([In,Out]Object ptr, int ofs, char val)
         {
             WriteInt16(ptr, ofs, (short)val);
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void WriteInt16(IntPtr ptr, char val)
         {
             WriteInt16(ptr, 0, (short)val);
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
         {
             try
@@ -776,26 +684,17 @@ namespace System.Runtime.InteropServices
                 throw new AccessViolationException();
             }
         }
-        
-        [System.Security.SecurityCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [DllImport(Win32Native.SHIM, EntryPoint="ND_WI4")]
-        [SuppressUnmanagedCodeSecurity]
-        public static extern void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val);
-#else
+
         public static void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val)
         {
             throw new PlatformNotSupportedException();
         }
-#endif // !FEATURE_CORECLR
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void WriteInt32(IntPtr ptr, int val)
         {
             WriteInt32(ptr,0,val);
         }    
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
         {
             #if BIT64
@@ -805,7 +704,6 @@ namespace System.Runtime.InteropServices
             #endif
         }
         
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, IntPtr val)
         {
             #if BIT64
@@ -815,7 +713,6 @@ namespace System.Runtime.InteropServices
             #endif
         }
         
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void WriteIntPtr(IntPtr ptr, IntPtr val)
         {
             #if BIT64
@@ -825,7 +722,6 @@ namespace System.Runtime.InteropServices
             #endif
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
         {
             try
@@ -856,20 +752,12 @@ namespace System.Runtime.InteropServices
                 throw new AccessViolationException();
             }
         }
-    
-        [System.Security.SecurityCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [DllImport(Win32Native.SHIM, EntryPoint="ND_WI8")]        
-        [SuppressUnmanagedCodeSecurity]
-        public static extern void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val);
-#else
+
         public static void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val)
         {
             throw new PlatformNotSupportedException();
         }
-#endif // !FEATURE_CORECLR
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void WriteInt64(IntPtr ptr, long val)
         {
             WriteInt64(ptr, 0, val);
@@ -879,7 +767,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // GetLastWin32Error
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static extern int GetLastWin32Error();
@@ -896,7 +783,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // GetHRForLastWin32Error
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static int GetHRForLastWin32Error()
         {
@@ -911,7 +797,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Prelink
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void Prelink(MethodInfo m)
         {
             if (m == null) 
@@ -927,10 +812,8 @@ namespace System.Runtime.InteropServices
         }
     
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        [SecurityCritical]
         private static extern void InternalPrelink(IRuntimeMethodInfo m);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void PrelinkAll(Type c)
         {
             if (c == null)
@@ -950,7 +833,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // NumParamBytes
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static int NumParamBytes(MethodInfo m)
         {
             if (m == null) 
@@ -965,7 +847,6 @@ namespace System.Runtime.InteropServices
         }
 
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        [SecurityCritical]
         private static extern int InternalNumParamBytes(IRuntimeMethodInfo m);
 
         //====================================================================
@@ -973,12 +854,10 @@ namespace System.Runtime.InteropServices
         // These are mostly interesting for Structured exception handling,
         // but need to be exposed for all exceptions (not just SEHException).
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [System.Runtime.InteropServices.ComVisible(true)]
         public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern int GetExceptionCode();
 
@@ -988,12 +867,10 @@ namespace System.Runtime.InteropServices
         // If the structure contains pointers to allocated blocks and
         // "fDeleteOld" is true, this routine will call DestroyStructure() first. 
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         [System.Runtime.InteropServices.ComVisible(true)]
         public static extern void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld);
 
-        [System.Security.SecurityCritical]
         public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
         {
             StructureToPtr((object)structure, ptr, fDeleteOld);
@@ -1002,14 +879,12 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Marshals data from a native memory block to a preallocated structure class.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [System.Runtime.InteropServices.ComVisible(true)]
         public static void PtrToStructure(IntPtr ptr, Object structure)
         {
             PtrToStructureHelper(ptr, structure, false);
         }
 
-        [System.Security.SecurityCritical]
         public static void PtrToStructure<T>(IntPtr ptr, T structure)
         {
             PtrToStructure(ptr, (object)structure);
@@ -1019,7 +894,6 @@ namespace System.Runtime.InteropServices
         // Creates a new instance of "structuretype" and marshals data from a
         // native memory block to it.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [System.Runtime.InteropServices.ComVisible(true)]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Object PtrToStructure(IntPtr ptr, Type structureType)
@@ -1044,7 +918,6 @@ namespace System.Runtime.InteropServices
             return structure;
         }
 
-        [System.Security.SecurityCritical]
         public static T PtrToStructure<T>(IntPtr ptr)
         {
             return (T)PtrToStructure(ptr, typeof(T));
@@ -1061,12 +934,10 @@ namespace System.Runtime.InteropServices
         // Freeds all substructures pointed to by the native memory block.
         // "structureclass" is used to provide layout information.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [System.Runtime.InteropServices.ComVisible(true)]
         public static extern void DestroyStructure(IntPtr ptr, Type structuretype);
 
-        [System.Security.SecurityCritical]
         public static void DestroyStructure<T>(IntPtr ptr)
         {
             DestroyStructure(ptr, typeof(T));
@@ -1078,7 +949,6 @@ namespace System.Runtime.InteropServices
         // doesn't have an HInstance.  In Memory (Dynamic) Modules won't have 
         // an HInstance.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr GetHINSTANCE(Module m)
         {
             if (m == null)
@@ -1099,7 +969,6 @@ namespace System.Runtime.InteropServices
             return GetHINSTANCE(rtModule.GetNativeHandle());
         }    
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [SuppressUnmanagedCodeSecurity]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private extern static IntPtr GetHINSTANCE(RuntimeModule m);
@@ -1108,13 +977,11 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Throws a CLR exception based on the HRESULT.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void ThrowExceptionForHR(int errorCode)
         {
             if (errorCode < 0)
                 ThrowExceptionForHRInternal(errorCode, IntPtr.Zero);
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
         {
             if (errorCode < 0)
@@ -1128,7 +995,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Converts the HRESULT to a CLR exception.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Exception GetExceptionForHR(int errorCode)
         {
             if (errorCode < 0)
@@ -1136,7 +1002,6 @@ namespace System.Runtime.InteropServices
             else 
                 return null;
         }
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
         {
             if (errorCode < 0)
@@ -1153,7 +1018,6 @@ namespace System.Runtime.InteropServices
         // This method is intended for compiler code generators rather
         // than applications. 
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ObsoleteAttribute("The GetUnmanagedThunkForManagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern IntPtr GetUnmanagedThunkForManagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
@@ -1162,7 +1026,6 @@ namespace System.Runtime.InteropServices
         // This method is intended for compiler code generators rather
         // than applications. 
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ObsoleteAttribute("The GetManagedThunkForUnmanagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern IntPtr GetManagedThunkForUnmanagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
@@ -1173,7 +1036,6 @@ namespace System.Runtime.InteropServices
         // activity.  A fiber cookie can be redeemed for its managed Thread
         // object by calling the following service.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ObsoleteAttribute("The GetThreadFromFiberCookie method has been deprecated.  Use the hosting API to perform this operation.", false)]
         public static Thread GetThreadFromFiberCookie(int cookie)
         {
@@ -1191,7 +1053,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Memory allocation and deallocation.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public static IntPtr AllocHGlobal(IntPtr cb)
         {
@@ -1216,14 +1077,12 @@ namespace System.Runtime.InteropServices
             return pNewMem;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public static IntPtr AllocHGlobal(int cb)
         {
             return AllocHGlobal((IntPtr)cb);
         }
         
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static void FreeHGlobal(IntPtr hglobal)
         {
@@ -1234,7 +1093,6 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
         {
             IntPtr pNewMem = Win32Native.LocalReAlloc(pv, cb, LMEM_MOVEABLE);
@@ -1248,7 +1106,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // String convertions.
         //====================================================================          
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static IntPtr StringToHGlobalAnsi(String s)
         {
             if (s == null)
@@ -1278,7 +1135,6 @@ namespace System.Runtime.InteropServices
             }
         }    
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static IntPtr StringToHGlobalUni(String s)
         {
             if (s == null)
@@ -1311,7 +1167,6 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr StringToHGlobalAuto(String s)
         {
             // Ansi platforms are no longer supported
@@ -1324,7 +1179,6 @@ namespace System.Runtime.InteropServices
         // Converts the CLR exception to an HRESULT. This function also sets
         // up an IErrorInfo for the exception.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern int GetHRForException(Exception e);
 
@@ -1334,7 +1188,6 @@ namespace System.Runtime.InteropServices
         // This function is only used in WinRT and converts ObjectDisposedException
         // to RO_E_CLOSED
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int GetHRForException_WinRT(Exception e);
 
@@ -1343,7 +1196,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Given a managed object that wraps a UCOMITypeLib, return its name
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibName(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
         public static String GetTypeLibName(UCOMITypeLib pTLB)
         {
@@ -1354,7 +1206,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Given a managed object that wraps an ITypeLib, return its name
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static String GetTypeLibName(ITypeLib typelib)
         {
             if (typelib == null)
@@ -1375,7 +1226,6 @@ namespace System.Runtime.InteropServices
         // Internal version of GetTypeLibName
         // Support GUID_ManagedName which aligns with TlbImp
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         internal static String GetTypeLibNameInternal(ITypeLib typelib)
         {
             if (typelib == null)
@@ -1417,7 +1267,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Given an managed object that wraps an UCOMITypeLib, return its guid
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibGuid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
         public static Guid GetTypeLibGuid(UCOMITypeLib pTLB)
         {
@@ -1427,7 +1276,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Given an managed object that wraps an ITypeLib, return its guid
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Guid GetTypeLibGuid(ITypeLib typelib)
         {
             Guid result = new Guid ();
@@ -1441,7 +1289,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Given a managed object that wraps a UCOMITypeLib, return its lcid
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibLcid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
         public static int GetTypeLibLcid(UCOMITypeLib pTLB)
         {
@@ -1451,7 +1298,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Given a managed object that wraps an ITypeLib, return its lcid
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern int GetTypeLibLcid(ITypeLib typelib);
 
@@ -1465,7 +1311,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Given a managed object that wraps an ITypeInfo, return its guid.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Guid GetTypeInfoGuid(ITypeInfo typeInfo)
         {
             Guid result = new Guid ();
@@ -1480,7 +1325,6 @@ namespace System.Runtime.InteropServices
         // Given a assembly, return the TLBID that will be generated for the
         // typelib exported from the assembly.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Guid GetTypeLibGuidForAssembly(Assembly asm)
         {
             if (asm == null)
@@ -1506,7 +1350,6 @@ namespace System.Runtime.InteropServices
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void _GetTypeLibVersionForAssembly(RuntimeAssembly inputAssembly, out int majorVersion, out int minorVersion);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void GetTypeLibVersionForAssembly(Assembly inputAssembly, out int majorVersion, out int minorVersion) 
         {
             if (inputAssembly == null)
@@ -1523,7 +1366,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Given a managed object that wraps an UCOMITypeInfo, return its name
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeInfoName(ITypeInfo pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
         public static String GetTypeInfoName(UCOMITypeInfo pTI)
         {
@@ -1533,7 +1375,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Given a managed object that wraps an ITypeInfo, return its name
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static String GetTypeInfoName(ITypeInfo typeInfo)
         {
             if (typeInfo == null)
@@ -1554,7 +1395,6 @@ namespace System.Runtime.InteropServices
         // Internal version of GetTypeInfoName
         // Support GUID_ManagedName which aligns with TlbImp
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         internal static String GetTypeInfoNameInternal(ITypeInfo typeInfo, out bool hasManagedName)
         {
             if (typeInfo == null)
@@ -1592,7 +1432,6 @@ namespace System.Runtime.InteropServices
         // Get the corresponding managed name as converted by TlbImp
         // Used to get the type using GetType() from imported assemblies
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         internal static String GetManagedTypeInfoNameInternal(ITypeLib typeLib, ITypeInfo typeInfo)
         {
             bool hasManagedName;
@@ -1611,95 +1450,8 @@ namespace System.Runtime.InteropServices
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern Type GetLoadedTypeForGUID(ref Guid guid);
 
-#if !FEATURE_CORECLR // current implementation requires reflection only load 
-        //====================================================================
-        // map ITypeInfo* to Type
-        //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
-        public static Type GetTypeForITypeInfo(IntPtr /* ITypeInfo* */ piTypeInfo)
-        {
-            ITypeInfo pTI = null;
-            ITypeLib pTLB = null;
-            Type TypeObj = null;
-            Assembly AsmBldr = null;
-            TypeLibConverter TlbConverter = null;
-            int Index = 0;
-            Guid clsid;
-
-            // If the input ITypeInfo is NULL then return NULL.
-            if (piTypeInfo == IntPtr.Zero)
-                return null;
-
-            // Wrap the ITypeInfo in a CLR object.
-            pTI = (ITypeInfo)GetObjectForIUnknown(piTypeInfo);
-
-            // Check to see if a class exists with the specified GUID.
-
-            clsid = GetTypeInfoGuid(pTI);
-            TypeObj = GetLoadedTypeForGUID(ref clsid);
-
-            // If we managed to find the type based on the GUID then return it.
-            if (TypeObj != null)
-                return TypeObj;
-
-            // There is no type with the specified GUID in the app domain so lets
-            // try and convert the containing typelib.
-            try 
-            {
-                pTI.GetContainingTypeLib(out pTLB, out Index);
-            }
-            catch(COMException)
-            {
-                pTLB = null;
-            }
-
-            // Check to see if we managed to get a containing typelib.
-            if (pTLB != null)
-            {
-                // Get the assembly name from the typelib.
-                AssemblyName AsmName = TypeLibConverter.GetAssemblyNameFromTypelib(pTLB, null, null, null, null, AssemblyNameFlags.None);
-                String AsmNameString = AsmName.FullName;
-
-                // Check to see if the assembly that will contain the type already exists.
-                Assembly[] aAssemblies = Thread.GetDomain().GetAssemblies();
-                int NumAssemblies = aAssemblies.Length;
-                for (int i = 0; i < NumAssemblies; i++)
-                {
-                    if (String.Compare(aAssemblies[i].FullName, 
-                                       AsmNameString,StringComparison.Ordinal) == 0)
-                        AsmBldr = aAssemblies[i];
-                }
-
-                // If we haven't imported the assembly yet then import it.
-                if (AsmBldr == null)
-                {
-                    TlbConverter = new TypeLibConverter();
-                    AsmBldr = TlbConverter.ConvertTypeLibToAssembly(pTLB, 
-                        GetTypeLibName(pTLB) + ".dll", 0, new ImporterCallback(), null, null, null, null);
-                }
-
-                // Load the type object from the imported typelib.
-                // Call GetManagedTypeInfoNameInternal to align with TlbImp behavior
-                TypeObj = AsmBldr.GetType(GetManagedTypeInfoNameInternal(pTLB, pTI), true, false);
-                if (TypeObj != null && !TypeObj.IsVisible) 
-                    TypeObj = null;
-            }
-            else
-            {
-                // If the ITypeInfo does not have a containing typelib then simply 
-                // return Object as the type.
-                TypeObj = typeof(Object);
-            }
-
-            return TypeObj;
-        }
-#endif // #if !FEATURE_CORECLR 
-
         // This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it
         // on Marshal for more consistent API surface.
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-#endif //!FEATURE_CORECLR
         public static Type GetTypeFromCLSID(Guid clsid)
         {
             return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
@@ -1708,7 +1460,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // map Type to ITypeInfo*
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern IntPtr /* ITypeInfo* */ GetITypeInfoForType(Type t);
 
@@ -1717,13 +1468,11 @@ namespace System.Runtime.InteropServices
         // is the one where the RCW was first seen. Will return null 
         // otherwise.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o)
         {
             return GetIUnknownForObjectNative(o, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr /* IUnknown* */ GetIUnknownForObjectInContext(Object o)
         {
             return GetIUnknownForObjectNative(o, true);
@@ -1744,14 +1493,9 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // return the IDispatch* for an Object
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr /* IDispatch */ GetIDispatchForObject(Object o)
         {
-#if FEATURE_CORECLR
             throw new PlatformNotSupportedException();
-#else         
-            return GetIDispatchForObjectNative(o, false);
-#endif // FEATURE_CORECLR            
         }
         
 #if FEATURE_COMINTEROP
@@ -1760,7 +1504,6 @@ namespace System.Runtime.InteropServices
         // is the one where the RCW was first seen. Will return null 
         // otherwise.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr /* IUnknown* */ GetIDispatchForObjectInContext(Object o)
         {
             return GetIDispatchForObjectNative(o, true);
@@ -1773,13 +1516,11 @@ namespace System.Runtime.InteropServices
         // return the IUnknown* representing the interface for the Object
         // Object o should support Type T
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T)
         {
             return GetComInterfaceForObjectNative(o, T, false, true);
         }
 
-        [System.Security.SecurityCritical]
         public static IntPtr GetComInterfaceForObject<T, TInterface>(T o)
         {
             return GetComInterfaceForObject(o, typeof(TInterface));
@@ -1790,7 +1531,6 @@ namespace System.Runtime.InteropServices
         // Object o should support Type T, it refer the value of mode to 
         // invoke customized QueryInterface or not
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode)
         {
             bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false);
@@ -1803,7 +1543,6 @@ namespace System.Runtime.InteropServices
         // is the one where the RCW was first seen. Will return null 
         // otherwise.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr /* IUnknown* */ GetComInterfaceForObjectInContext(Object o, Type t)
         {
             return GetComInterfaceForObjectNative(o, t, true, true);
@@ -1815,7 +1554,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // return an Object for IUnknown
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk);
 
@@ -1826,7 +1564,6 @@ namespace System.Runtime.InteropServices
         //  where you want to be able to call ReleaseComObject on a RCW
         //  and not worry about other active uses of said RCW.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern Object GetUniqueObjectForIUnknown(IntPtr unknown);
 
@@ -1836,40 +1573,31 @@ namespace System.Runtime.InteropServices
         //  Type T should be either a COM imported Type or a sub-type of COM 
         //  imported Type
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern Object GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, Type t);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern IntPtr CreateAggregatedObject(IntPtr pOuter, Object o);
 
-        [System.Security.SecurityCritical]
         public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
         {
             return CreateAggregatedObject(pOuter, (object)o);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void CleanupUnusedObjectsInCurrentContext();
 
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern bool AreComObjectsAvailableForCleanup();
 
         //====================================================================
         // check if the object is classic COM component
         //====================================================================
-#if !FEATURE_CORECLR // with FEATURE_CORECLR, the whole type is SecurityCritical
-        [System.Security.SecuritySafeCritical]
-#endif
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern bool IsComObject(Object o);
 
 #endif // FEATURE_COMINTEROP
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr AllocCoTaskMem(int cb)
         {
             IntPtr pNewMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)cb));
@@ -1880,7 +1608,6 @@ namespace System.Runtime.InteropServices
             return pNewMem;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static IntPtr StringToCoTaskMemUni(String s)
         {
             if (s == null)
@@ -1912,7 +1639,6 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static IntPtr StringToCoTaskMemUTF8(String s)
         {
             const int MAX_UTF8_CHAR_SIZE = 3;
@@ -1944,14 +1670,12 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr StringToCoTaskMemAuto(String s)
         {
             // Ansi platforms are no longer supported
             return StringToCoTaskMemUni(s);
         } 
    
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static IntPtr StringToCoTaskMemAnsi(String s)
         {
             if (s == null)
@@ -1980,7 +1704,6 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void FreeCoTaskMem(IntPtr ptr)
         {
             if (IsNotWin32Atom(ptr)) {
@@ -1988,7 +1711,6 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
         {
             IntPtr pNewMem = Win32Native.CoTaskMemRealloc(pv, new UIntPtr((uint)cb));
@@ -2002,7 +1724,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // BSTR allocation and dealocation.
         //====================================================================      
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void FreeBSTR(IntPtr ptr)
         {
             if (IsNotWin32Atom(ptr))
@@ -2011,7 +1732,6 @@ namespace System.Runtime.InteropServices
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr StringToBSTR(String s)
         {
             if (s == null)
@@ -2028,7 +1748,6 @@ namespace System.Runtime.InteropServices
             return bstr;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static String PtrToStringBSTR(IntPtr ptr)
         {
             return PtrToStringUni(ptr, (int)Win32Native.SysStringLen(ptr));
@@ -2039,7 +1758,6 @@ namespace System.Runtime.InteropServices
         // release the COM component and if the reference hits 0 zombie this object
         // further usage of this Object might throw an exception
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static int ReleaseComObject(Object o)
         {
             __ComObject co = null;
@@ -2065,7 +1783,6 @@ namespace System.Runtime.InteropServices
         // release the COM component and zombie this object
         // further usage of this Object might throw an exception
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Int32 FinalReleaseComObject(Object o)
         {
             if (o == null)
@@ -2096,39 +1813,9 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // This method retrieves data from the COM object.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Object GetComObjectData(Object obj, Object key)
         {
-#if FEATURE_CORECLR
             throw new PlatformNotSupportedException();
-#else        
-            // Validate that the arguments aren't null.
-            if (obj == null)
-                throw new ArgumentNullException(nameof(obj));
-            if (key == null)
-                throw new ArgumentNullException(nameof(key));
-            Contract.EndContractBlock();
-
-            __ComObject comObj = null;
-
-            // Make sure the obj is an __ComObject.
-            try
-            {
-                comObj = (__ComObject)obj;
-            }
-            catch (InvalidCastException)
-            {
-                throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(obj));
-            }
-
-            if (obj.GetType().IsWindowsRuntimeObject)
-            {
-                throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), nameof(obj));
-            }
-
-            // Retrieve the data from the __ComObject.
-            return comObj.GetData(key);
-#endif // FEATURE_CORECLR            
         }
 
         //====================================================================
@@ -2137,39 +1824,9 @@ namespace System.Runtime.InteropServices
         // true if the data has been added, false if the data could not be
         // added because there already was data for the specified key.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static bool SetComObjectData(Object obj, Object key, Object data)
         {
-#if FEATURE_CORECLR
             throw new PlatformNotSupportedException();
-#else          
-            // Validate that the arguments aren't null. The data can validly be null.
-            if (obj == null)
-                throw new ArgumentNullException(nameof(obj));
-            if (key == null)
-                throw new ArgumentNullException(nameof(key));
-            Contract.EndContractBlock();
-
-            __ComObject comObj = null;
-
-            // Make sure the obj is an __ComObject.
-            try
-            {
-                comObj = (__ComObject)obj;
-            }
-            catch (InvalidCastException)
-            {
-                throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(obj));
-            }
-
-            if (obj.GetType().IsWindowsRuntimeObject)
-            {
-                throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), nameof(obj));
-            }
-
-            // Retrieve the data from the __ComObject.
-            return comObj.SetData(key, data);
-#endif // FEATURE_CORECLR            
         }
 
 #if FEATURE_COMINTEROP
@@ -2177,7 +1834,6 @@ namespace System.Runtime.InteropServices
         // This method takes the given COM object and wraps it in an object
         // of the specified type. The type must be derived from __ComObject.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Object CreateWrapperOfType(Object o, Type t)
         {
             // Validate the arguments.
@@ -2224,7 +1880,6 @@ namespace System.Runtime.InteropServices
             return Wrapper;
         }
 
-        [System.Security.SecurityCritical]
         public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
         {
             return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper));
@@ -2233,7 +1888,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // Helper method called from CreateWrapperOfType.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern Object InternalCreateWrapperOfType(Object o, Type t);
 
@@ -2241,7 +1895,6 @@ namespace System.Runtime.InteropServices
         // There may be a thread-based cache of COM components.  This service can
         // force the aggressive release of the current thread's cache.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [Obsolete("This API did not perform any operation and will be removed in future versions of the CLR.", false)]
         public static void ReleaseThreadCache()
         {
@@ -2250,50 +1903,40 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // check if the type is visible from COM.
         //====================================================================
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern bool IsTypeVisibleFromCom(Type t);
 
         //====================================================================
         // IUnknown Helpers
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv);    
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk );
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk );
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant);
 
-        [System.Security.SecurityCritical]
         public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
         {
             GetNativeVariantForObject((object)obj, pDstNativeVariant);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant );
 
-        [System.Security.SecurityCritical]
         public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
         {
             return (T)GetObjectForNativeVariant(pSrcNativeVariant);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars );
 
-        [System.Security.SecurityCritical]
         public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
         {
             object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
@@ -2312,14 +1955,12 @@ namespace System.Runtime.InteropServices
         /// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on
         /// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para>
         /// </summary>
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern int GetStartComSlot(Type t);
 
         /// <summary>
         /// <para>Returns the last valid COM slot that GetMethodInfoForSlot will work on. </para>
         /// </summary>
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern int GetEndComSlot(Type t);
 
@@ -2330,7 +1971,6 @@ namespace System.Runtime.InteropServices
         /// For classes, the lookup is done on the default interface that will be
         /// exposed for the class. </para>
         /// </summary>
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern MemberInfo GetMethodInfoForComSlot(Type t, int slot, ref ComMemberType memberType);
 
@@ -2338,7 +1978,6 @@ namespace System.Runtime.InteropServices
         /// <para>Returns the COM slot for a memeber info, taking into account whether 
         /// the exposed interface is IUnknown based or IDispatch based</para>
         /// </summary>
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static int GetComSlotForMethodInfo(MemberInfo m)
         {
             if (m== null) 
@@ -2366,22 +2005,10 @@ namespace System.Runtime.InteropServices
         // guid GUID is generated based on the fully qualified name of the 
         // type.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Guid GenerateGuidForType(Type type)
         {
-#if FEATURE_CORECLR
             return type.GUID;
         }
-#else
-            Guid result = new Guid ();
-            FCallGenerateGuidForType (ref result, type);
-            return result;
-        }
-
-        // The full assembly name is used to compute the GUID, so this should be SxS-safe
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern void FCallGenerateGuidForType(ref Guid result, Type type);
-#endif // FEATURE_CORECLR            
 
         //====================================================================
         // This method generates a PROGID for the specified type. If the type
@@ -2389,7 +2016,6 @@ namespace System.Runtime.InteropServices
         // PROGID is generated based on the fully qualified name of the 
         // type.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static String GenerateProgIdForType(Type type)
         {
             if (type == null)
@@ -2400,11 +2026,6 @@ namespace System.Runtime.InteropServices
                 throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
             Contract.EndContractBlock();
 
-#if !FEATURE_CORECLR
-            if (!RegistrationServices.TypeRequiresRegistrationHelper(type))
-                throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"), nameof(type));
-#endif // FEATURE_CORECLR            
-
             IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type);
             for (int i = 0; i < cas.Count; i ++)
             {
@@ -2412,10 +2033,10 @@ namespace System.Runtime.InteropServices
                 {
                     // Retrieve the PROGID string from the ProgIdAttribute.
                     IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments;
-                    Contract.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
+                    Debug.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
                     
                     CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0];                    
-                    Contract.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
+                    Debug.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
                     
                     String strProgId = (String)progIdConstructorArg.Value;
                     
@@ -2434,7 +2055,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // This method binds to the specified moniker.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Object BindToMoniker(String monikerName)
         {
             Object obj = null;
@@ -2452,7 +2072,6 @@ namespace System.Runtime.InteropServices
         //====================================================================
         // This method gets the currently running object.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Object GetActiveObject(String progID)
         {
             Object obj = null;
@@ -2476,32 +2095,26 @@ namespace System.Runtime.InteropServices
 
         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
         [SuppressUnmanagedCodeSecurity]
-        [System.Security.SecurityCritical]  // auto-generated
         private static extern void CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
 
         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
         [SuppressUnmanagedCodeSecurity]
-        [System.Security.SecurityCritical]  // auto-generated
         private static extern void CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
 
         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
         [SuppressUnmanagedCodeSecurity]
-        [System.Security.SecurityCritical]  // auto-generated
         private static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc);
 
         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
         [SuppressUnmanagedCodeSecurity]
-        [System.Security.SecurityCritical]  // auto-generated
         private static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] String szUserName, out UInt32 pchEaten, out IMoniker ppmk);
 
         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
         [SuppressUnmanagedCodeSecurity]
-        [System.Security.SecurityCritical]  // auto-generated
         private static extern void BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult);
 
         [DllImport(Microsoft.Win32.Win32Native.OLEAUT32, PreserveSig = false)]
         [SuppressUnmanagedCodeSecurity]
-        [System.Security.SecurityCritical]  // auto-generated
         private static extern void GetActiveObject(ref Guid rclsid, IntPtr reserved, [MarshalAs(UnmanagedType.Interface)] out Object ppunk);
 
         //========================================================================
@@ -2516,7 +2129,6 @@ namespace System.Runtime.InteropServices
         //========================================================================
         // Private method called from EE upon use of license/ICF2 marshaling.
         //========================================================================
-        [SecurityCritical]
         private static IntPtr LoadLicenseManager()
         {
             Assembly sys = Assembly.Load("System, Version="+ ThisAssembly.Version + 
@@ -2527,16 +2139,13 @@ namespace System.Runtime.InteropServices
             return t.TypeHandle.Value;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void ChangeWrapperHandleStrength(Object otp, bool fIsWeak);
 
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void InitializeWrapperForWinRT(object o, ref IntPtr pUnk);
 
 #if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType);
 #endif
@@ -2544,7 +2153,6 @@ namespace System.Runtime.InteropServices
         //========================================================================
         // Create activation factory and wraps it with a unique RCW
         //========================================================================
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern object GetNativeActivationFactory(Type type);
 
@@ -2552,11 +2160,9 @@ namespace System.Runtime.InteropServices
         // Methods allowing retrieval of the IIDs exposed by an underlying WinRT
         // object, as specified by the object's IInspectable::GetIids()
         //========================================================================
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private static extern void _GetInspectableIids(ObjectHandleOnStack obj, ObjectHandleOnStack guids);
 
-        [System.Security.SecurityCritical]
         internal static System.Guid[] GetInspectableIids(object obj)
         {
             System.Guid[] result = null;
@@ -2574,14 +2180,12 @@ namespace System.Runtime.InteropServices
         // Methods allowing retrieval of the cached WinRT type corresponding to
         // the specified GUID
         //========================================================================
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private static extern void _GetCachedWinRTTypeByIid(
                         ObjectHandleOnStack appDomainObj, 
                         System.Guid iid,
                         out IntPtr rthHandle);
 
-        [System.Security.SecurityCritical]
         internal static System.Type GetCachedWinRTTypeByIid(
                         System.AppDomain ad, 
                         System.Guid iid)
@@ -2599,14 +2203,12 @@ namespace System.Runtime.InteropServices
         // Methods allowing retrieval of the WinRT types cached in the specified
         // app domain
         //========================================================================
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private static extern void _GetCachedWinRTTypes(
                         ObjectHandleOnStack appDomainObj, 
                         ref int epoch,
                         ObjectHandleOnStack winrtTypes);
 
-        [System.Security.SecurityCritical]
         internal static System.Type[] GetCachedWinRTTypes(
                         System.AppDomain ad, 
                         ref int epoch)
@@ -2626,7 +2228,6 @@ namespace System.Runtime.InteropServices
             return result;
         }
 
-        [System.Security.SecurityCritical]
         internal static System.Type[] GetCachedWinRTTypes(
                         System.AppDomain ad)
         {
@@ -2637,7 +2238,6 @@ namespace System.Runtime.InteropServices
 
 #endif // FEATURE_COMINTEROP
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
         {
             // Validate the parameters
@@ -2661,7 +2261,6 @@ namespace System.Runtime.InteropServices
             return GetDelegateForFunctionPointerInternal(ptr, t);
         }
 
-        [System.Security.SecurityCritical]
         public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
         {
             return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
@@ -2670,7 +2269,6 @@ namespace System.Runtime.InteropServices
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr GetFunctionPointerForDelegate(Delegate d)
         {
             if (d == null)
@@ -2680,7 +2278,6 @@ namespace System.Runtime.InteropServices
             return GetFunctionPointerForDelegateInternal(d);
         }
 
-        [System.Security.SecurityCritical]
         public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
         {
             return GetFunctionPointerForDelegate((Delegate)(object)d);
@@ -2689,7 +2286,6 @@ namespace System.Runtime.InteropServices
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr SecureStringToBSTR(SecureString s) {
             if( s == null) {
                 throw new ArgumentNullException(nameof(s));
@@ -2703,7 +2299,6 @@ namespace System.Runtime.InteropServices
 #endif
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) {
             if( s == null) {
                 throw new ArgumentNullException(nameof(s));
@@ -2713,7 +2308,6 @@ namespace System.Runtime.InteropServices
             return s.MarshalToString(globalAlloc: false, unicode: false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
         {
             if( s == null) {
@@ -2725,7 +2319,6 @@ namespace System.Runtime.InteropServices
         }
 
 #if FEATURE_COMINTEROP
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void ZeroFreeBSTR(IntPtr s)
         {
             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2));
@@ -2733,28 +2326,24 @@ namespace System.Runtime.InteropServices
         }
 #endif
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void ZeroFreeCoTaskMemAnsi(IntPtr s)
         {
             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
             FreeCoTaskMem(s);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void ZeroFreeCoTaskMemUnicode(IntPtr s)
         {
             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
             FreeCoTaskMem(s);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe public static void ZeroFreeCoTaskMemUTF8(IntPtr s)
         {
             Win32Native.ZeroMemory(s, (UIntPtr)System.StubHelpers.StubHelpers.strlen((sbyte*)s));
             FreeCoTaskMem(s);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) {
             if( s == null) {
                 throw new ArgumentNullException(nameof(s));
@@ -2764,7 +2353,6 @@ namespace System.Runtime.InteropServices
             return s.MarshalToString(globalAlloc: true, unicode: false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) {
             if( s == null) {
                 throw new ArgumentNullException(nameof(s));
@@ -2774,54 +2362,15 @@ namespace System.Runtime.InteropServices
             return s.MarshalToString(globalAlloc: true, unicode: true);;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void ZeroFreeGlobalAllocAnsi(IntPtr s) {
             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
             FreeHGlobal(s);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static void ZeroFreeGlobalAllocUnicode(IntPtr s) {
             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
             FreeHGlobal(s);
         }
     }
-
-#if FEATURE_COMINTEROP && !FEATURE_CORECLR // current implementation requires reflection only load 
-    //========================================================================
-    // Typelib importer callback implementation.
-    //========================================================================
-    internal class ImporterCallback : ITypeLibImporterNotifySink
-    {
-        public void ReportEvent(ImporterEventKind EventKind, int EventCode, String EventMsg)
-        {
-        }
-        
-        [System.Security.SecuritySafeCritical] // overrides transparent public member
-        public Assembly ResolveRef(Object TypeLib)
-        {
-            try
-            {
-                // Create the TypeLibConverter.
-                ITypeLibConverter TLBConv = new TypeLibConverter();
-
-                // Convert the typelib.
-                return TLBConv.ConvertTypeLibToAssembly(TypeLib,
-                                                        Marshal.GetTypeLibName((ITypeLib)TypeLib) + ".dll",
-                                                        0,
-                                                        new ImporterCallback(),
-                                                        null,
-                                                        null,
-                                                        null,
-                                                        null);
-            }
-            catch(Exception)
-//            catch
-            {
-                return null;
-            }               
-        }
-    }
-#endif // FEATURE_COMINTEROP && !FEATURE_CORECLR 
 }
 
index 82cd4fa..650ea65 100644 (file)
@@ -31,13 +31,10 @@ namespace System.Runtime.InteropServices {
         ]
         internal interface IDispatch {
 
-            [System.Security.SecurityCritical]
             void GetTypeInfoCount(out uint pctinfo);
 
-            [System.Security.SecurityCritical]
             void GetTypeInfo(uint iTInfo, int lcid, out IntPtr info);
 
-            [System.Security.SecurityCritical]
             void GetIDsOfNames(
                 ref Guid iid,
                 [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)]
@@ -48,7 +45,6 @@ namespace System.Runtime.InteropServices {
                 [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4, SizeParamIndex = 2)]
                 int[] rgDispId);
 
-            [System.Security.SecurityCritical]
             void Invoke(
                 int dispIdMember,
                 ref Guid riid,
index 9fd818d..0105866 100644 (file)
@@ -29,6 +29,7 @@ namespace System.Runtime.InteropServices {
     using System.Runtime.CompilerServices;
     using System.Globalization;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Flags]
@@ -91,7 +92,6 @@ namespace System.Runtime.InteropServices {
         
         #region IRegistrationServices
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags)
         {
             // Validate the arguments.
@@ -154,7 +154,6 @@ namespace System.Runtime.InteropServices {
                 return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual bool UnregisterAssembly(Assembly assembly)
         {
             // Validate the arguments.
@@ -214,7 +213,6 @@ namespace System.Runtime.InteropServices {
                 return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual Type[] GetRegistrableTypesInAssembly(Assembly assembly)
         {
             // Validate the arguments.
@@ -246,13 +244,11 @@ namespace System.Runtime.InteropServices {
             return RetArray;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual String GetProgIdForType(Type type)
         {
             return Marshal.GenerateProgIdForType(type);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual void RegisterTypeForComClients(Type type, ref Guid g)
         {
 #if FEATURE_COMINTEROP_MANAGED_ACTIVATION
@@ -276,13 +272,11 @@ namespace System.Runtime.InteropServices {
             return s_ManagedCategoryGuid;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public virtual bool TypeRequiresRegistration(Type type)
         {
             return TypeRequiresRegistrationHelper(type);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public virtual bool TypeRepresentsComType(Type type)
         {
             // If the type is not a COM import, then it does not represent a COM type.
@@ -296,7 +290,7 @@ namespace System.Runtime.InteropServices {
             // If the type is derived from a tdImport class and has the same GUID as the
             // imported class, then it represents a COM type.
             Type baseComImportType = GetBaseComImportType(type);
-            Contract.Assert(baseComImportType != null, "baseComImportType != null");
+            Debug.Assert(baseComImportType != null, "baseComImportType != null");
             if (Marshal.GenerateGuidForType(type) == Marshal.GenerateGuidForType(baseComImportType))
                 return true;
 
@@ -307,7 +301,6 @@ namespace System.Runtime.InteropServices {
 
         
         #region Public methods not on IRegistrationServices
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ComVisible(false)]
         public virtual int RegisterTypeForComClients(Type type, RegistrationClassContext classContext, RegistrationConnectionType flags)
         {
@@ -327,7 +320,6 @@ namespace System.Runtime.InteropServices {
 #endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ComVisible(false)]
         public virtual void UnregisterTypeForComClients(int cookie)
         {
@@ -340,7 +332,6 @@ namespace System.Runtime.InteropServices {
 
         #region Internal helpers
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         internal static bool TypeRequiresRegistrationHelper(Type type)
         {
             // If the type is not a class or a value class, then it does not get registered.
@@ -365,7 +356,6 @@ namespace System.Runtime.InteropServices {
 
         #region Private helpers
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void RegisterValueType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
         {
             // Retrieve some information that will be used during the registration process.
@@ -397,7 +387,6 @@ namespace System.Runtime.InteropServices {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void RegisterManagedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
         {
             //
@@ -483,7 +472,6 @@ namespace System.Runtime.InteropServices {
             EnsureManagedCategoryExists();
         } 
         
-        [System.Security.SecurityCritical]  // auto-generated
         private void RegisterComImportedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
         {
             // Retrieve some information that will be used during the registration process.
@@ -525,7 +513,6 @@ namespace System.Runtime.InteropServices {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private bool UnregisterValueType(Type type, String strAsmVersion)
         {
             bool bAllVersionsGone = true;
@@ -582,7 +569,6 @@ namespace System.Runtime.InteropServices {
         // Return :
         //      true:   All versions are gone.
         //      false:  Some versions are still left in registry
-        [System.Security.SecurityCritical]  // auto-generated
         private bool UnregisterManagedType(Type type,String strAsmVersion)
         {
             bool bAllVersionsGone = true;
@@ -776,7 +762,6 @@ namespace System.Runtime.InteropServices {
         // Return:
         //      true:      All version information are gone.
         //      false:     There are still some version left in registry
-        [System.Security.SecurityCritical]  // auto-generated
         private bool UnregisterComImportedType(Type type, String strAsmVersion)
         {
             bool bAllVersionsGone = true;
@@ -846,7 +831,6 @@ namespace System.Runtime.InteropServices {
             return bAllVersionsGone;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void RegisterPrimaryInteropAssembly(RuntimeAssembly assembly, String strAsmCodeBase, PrimaryInteropAssemblyAttribute attr)
         {
             // Validate that the PIA has a strong name.
@@ -874,7 +858,6 @@ namespace System.Runtime.InteropServices {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void UnregisterPrimaryInteropAssembly(Assembly assembly, PrimaryInteropAssemblyAttribute attr)
         {
             String strTlbId = "{" + Marshal.GetTypeLibGuidForAssembly(assembly).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
@@ -937,20 +920,12 @@ namespace System.Runtime.InteropServices {
         private static bool ManagedCategoryExists()
         {
             using (RegistryKey componentCategoryKey = Registry.ClassesRoot.OpenSubKey(strComponentCategorySubKey, 
-#if FEATURE_MACL
-                                                                                      RegistryKeyPermissionCheck.ReadSubTree))
-#else
                                                                                       false))
-#endif
             {
                 if (componentCategoryKey == null)
                     return false;
                 using (RegistryKey managedCategoryKey = componentCategoryKey.OpenSubKey(strManagedCategoryGuid,
-#if FEATURE_MACL
-                                                                                        RegistryKeyPermissionCheck.ReadSubTree))
-#else
                                                                                         false))
-#endif
                 {
                     if (managedCategoryKey == null)
                         return false;
@@ -966,7 +941,6 @@ namespace System.Runtime.InteropServices {
             return true;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         private void CallUserDefinedRegistrationMethod(Type type, bool bRegister)
         {
             bool bFunctionCalled = false;
@@ -1069,13 +1043,11 @@ namespace System.Runtime.InteropServices {
 #if FEATURE_COMINTEROP_MANAGED_ACTIVATION
         // GUID versioning can be controlled by using the GuidAttribute or 
         // letting the runtime generate it based on type and assembly strong name.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void RegisterTypeForComClientsNative(Type type,ref Guid g);
         
         // GUID versioning can be controlled by using the GuidAttribute or 
         // letting the runtime generate it based on type and assembly strong name.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int RegisterTypeForComClientsExNative(Type t, RegistrationClassContext clsContext, RegistrationConnectionType flags);
 #endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
index d722843..a5c058d 100644 (file)
@@ -23,70 +23,31 @@ using Microsoft.Win32;
 using System.Runtime.Versioning;
 using StackCrawlMark = System.Threading.StackCrawlMark;
 
-namespace System.Runtime.InteropServices {
-[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
-    static
-#endif
-    public class RuntimeEnvironment {
+namespace System.Runtime.InteropServices
+{
+    [System.Runtime.InteropServices.ComVisible(true)]
+    static public class RuntimeEnvironment {
 
-#if !FEATURE_CORECLR
-        // 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.  On Silverlight, this type exists but is
-        // not public.
-        [Obsolete("Do not create instances of the RuntimeEnvironment class.  Call the static methods directly on this type instead", true)]
-        public RuntimeEnvironment()
-        {
-            // Should not have been instantiable - here for binary compatibility in V4.
-        }
-#endif
-
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern String GetModuleFileName();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern String GetDeveloperPath();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern String GetHostBindingFile();
 
-#if !FEATURE_CORECLR
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SuppressUnmanagedCodeSecurity]
-        internal static extern void _GetSystemVersion(StringHandleOnStack retVer);
-#endif //!FEATURE_CORECLR
-
         public static bool FromGlobalAccessCache(Assembly a)
         {
             return a.GlobalAssemblyCache;
         }
-        
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // public member
-#endif
+
         [MethodImpl (MethodImplOptions.NoInlining)]
         public static String GetSystemVersion()
         {
-#if FEATURE_CORECLR
-
             return Assembly.GetExecutingAssembly().ImageRuntimeVersion;
-
-#else // FEATURE_CORECLR
-
-            String ver = null;
-            _GetSystemVersion(JitHelpers.GetStringHandleOnStack(ref ver));
-            return ver;
-
-#endif // FEATURE_CORECLR
-
         }
-        
-        [System.Security.SecuritySafeCritical]  // auto-generated
+
         public static String GetRuntimeDirectory()
         {
             String dir = GetRuntimeDirectoryImpl();
@@ -94,13 +55,11 @@ namespace System.Runtime.InteropServices {
             return dir;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern String GetRuntimeDirectoryImpl();
         
         // Returns the system ConfigurationFile
         public static String SystemConfigurationFile {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 StringBuilder sb = new StringBuilder(Path.MaxPath);
                 sb.Append(GetRuntimeDirectory());
@@ -115,7 +74,6 @@ namespace System.Runtime.InteropServices {
         }
 
 #if FEATURE_COMINTEROP
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern IntPtr GetRuntimeInterfaceImpl(
@@ -130,7 +88,6 @@ namespace System.Runtime.InteropServices {
         // Returns unmanaged pointer to requested interface on success. Throws
         // COMException with failed HR if there is a QI failure.
         //
-        [System.Security.SecurityCritical]  // do not allow partial trust callers
         [ComVisible(false)]
         public static IntPtr GetRuntimeInterfaceAsIntPtr(Guid clsid, Guid riid)
         {
@@ -145,7 +102,6 @@ namespace System.Runtime.InteropServices {
         // Returns an RCW to requested interface on success. Throws
         // COMException with failed HR if there is a QI failure.
         //
-        [System.Security.SecurityCritical]  // do not allow partial trust callers
         [ComVisible(false)]
         public static object GetRuntimeInterfaceAsObject(Guid clsid, Guid riid)
         {
@@ -159,7 +115,6 @@ namespace System.Runtime.InteropServices {
                 }
             }
         }
-
 #endif // FEATURE_COMINTEROP
     }
 }
index 0946902..eba67ae 100644 (file)
@@ -75,10 +75,10 @@ using System.Runtime.CompilerServices;
 using System.Runtime.ConstrainedExecution;
 using System.Runtime.Versioning;
 using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 
-    [System.Security.SecurityCritical]
     public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid
     {
         // Steal UIntPtr.MaxValue as our uninitialized value.
@@ -385,7 +385,7 @@ using System.Diagnostics.Contracts;
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private static InvalidOperationException NotInitialized()
         {
-            Contract.Assert(false, "Uninitialized SafeBuffer!  Someone needs to call Initialize before using this instance!");
+            Debug.Assert(false, "Uninitialized SafeBuffer!  Someone needs to call Initialize before using this instance!");
             return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize"));
         }
 
index c268528..ed9910e 100644 (file)
@@ -134,10 +134,6 @@ using System.Runtime.Versioning;
 // we'll do this to ensure we've cut off all attack vectors.  Similarly, all
 // methods have a link demand to ensure untrusted code cannot directly edit
 // or alter a handle.
-[System.Security.SecurityCritical]  // auto-generated_required
-#if !FEATURE_CORECLR
-[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
 public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
 {
     // ! Do not add or rearrange fields as the EE depends on this layout.
@@ -182,16 +178,13 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
         _fullyInitialized = true;
     }
 
-#if FEATURE_CORECLR
     // Migrating InheritanceDemands requires this default ctor, so we can mark it critical
     protected SafeHandle()
     {
         BCLDebug.Assert(false, "SafeHandle's protected default ctor should never be used!");
         throw new NotImplementedException();
     }
-#endif
 
-    [System.Security.SecuritySafeCritical]  // auto-generated
     ~SafeHandle()
     {
         Dispose(false);
@@ -236,19 +229,16 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
         get;
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     public void Close() {
         Dispose(true);
     }
     
-    [System.Security.SecuritySafeCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     public void Dispose() {
         Dispose(true);
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     protected virtual void Dispose(bool disposing)
     {
@@ -266,7 +256,6 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
     // your handle is invalid and you want to record that information.
     // An example is calling a syscall and getting back ERROR_INVALID_HANDLE.
     // This method will normally leak handles!
-    [System.Security.SecurityCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     [MethodImplAttribute(MethodImplOptions.InternalCall)]
     public extern void SetHandleAsInvalid();
@@ -295,7 +284,6 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
     // when the method is interrupted prior to processing by a thread abort or
     // when the handle has already been (or is in the process of being)
     // released.
-    [System.Security.SecurityCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     [MethodImplAttribute(MethodImplOptions.InternalCall)]
     public extern void DangerousAddRef(ref bool success);
@@ -309,7 +297,6 @@ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
     // constitutes a potential security hole (via handle recycling) as well as a
     // correctness problem -- so don't ever expose Dangerous* calls out to
     // untrusted code.
-    [System.Security.SecurityCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     [MethodImplAttribute(MethodImplOptions.InternalCall)]
     public extern void DangerousRelease();
index 58f70e5..160a0ab 100644 (file)
@@ -10,6 +10,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
     using System.Reflection.Emit;
     using System.Collections;
     using System.Threading;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     
     internal class EventProviderWriter
@@ -96,34 +97,34 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
             
             // Find the delegate on the event sink helper.
             FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
-            Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
+            Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
             
             // Find the cookie on the event sink helper.
             FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
-            Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
+            Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
             
             // Retrieve the sink helper's constructor.
             ConstructorInfo SinkHelperCons = SinkHelperClass.GetConstructor(EventProviderWriter.DefaultLookup | BindingFlags.NonPublic, null, Array.Empty<Type>(), null );    
-            Contract.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
+            Debug.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
             
             // Retrieve the IConnectionPoint.Advise method.
             MethodInfo CPAdviseMethod = typeof(IConnectionPoint).GetMethod( "Advise" );
-            Contract.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise");
+            Debug.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise");
            
             // Retrieve the ArrayList.Add method.
             aParamTypes = new Type[1];
             aParamTypes[0] = typeof(Object);
             MethodInfo ArrayListAddMethod = typeof(ArrayList).GetMethod( "Add", aParamTypes, null );
-            Contract.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");
+            Debug.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");
 
             // Retrieve the Monitor.Enter() method.
             MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod( "Enter", MonitorEnterParamTypes, null );
-            Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
+            Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
             
             // Retrieve the Monitor.Exit() method.
             aParamTypes[0] = typeof(Object);
             MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
-            Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
+            Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
             
             // Define the add_XXX method.
             Type[] parameterTypes;
@@ -239,51 +240,51 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
             
             // Find the delegate on the event sink helper.
             FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
-            Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
+            Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
             
             // Find the cookie on the event sink helper.
             FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
-            Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
+            Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
             
             // Retrieve the ArrayList.RemoveAt method.
             aParamTypes = new Type[1];
             aParamTypes[0] = typeof(Int32);
             MethodInfo ArrayListRemoveMethod = typeof(ArrayList).GetMethod( "RemoveAt", aParamTypes, null );
-            Contract.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
+            Debug.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
             
             // Retrieve the ArrayList.Item property get method.
             PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
-            Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
+            Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
             MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
-            Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
+            Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
             
             // Retrieve the ArrayList.Count property get method.
             PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
-            Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
+            Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
             MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
-            Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
+            Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
             
             // Retrieve the Delegate.Equals() method.
             aParamTypes[0] = typeof(Delegate);
             MethodInfo DelegateEqualsMethod = typeof(Delegate).GetMethod( "Equals", aParamTypes, null );
-            Contract.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");
+            Debug.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");
 
             // Retrieve the Monitor.Enter() method.
             MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
-            Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
+            Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
             
             // Retrieve the Monitor.Exit() method.
             aParamTypes[0] = typeof(Object);
             MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
-            Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
+            Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
             
             // Retrieve the ConnectionPoint.Unadvise() method.
             MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
-            Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
+            Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
             
             // Retrieve the Marshal.ReleaseComObject() method.
             MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
-            Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
+            Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
             
             // Define the remove_XXX method.
             Type[] parameterTypes;
@@ -463,7 +464,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
         {
             // Retrieve the constructor info for the array list's default constructor.
             ConstructorInfo DefaultArrayListCons = typeof(ArrayList).GetConstructor(EventProviderWriter.DefaultLookup, null, Array.Empty<Type>(), null );
-            Contract.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");    
+            Debug.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");    
             
             // Temp byte array for Guid
             ubyte[] rgByteGuid = new ubyte[16];
@@ -472,11 +473,11 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
             Type[] aParamTypes = new Type[1];
             aParamTypes[0] = typeof(Byte[]);
             ConstructorInfo ByteArrayGUIDCons = typeof(Guid).GetConstructor(EventProviderWriter.DefaultLookup, null, aParamTypes, null );
-            Contract.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument");    
+            Debug.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument");    
             
             // Retrieve the IConnectionPointContainer.FindConnectionPoint() method.
             MethodInfo CPCFindCPMethod = typeof(IConnectionPointContainer).GetMethod( "FindConnectionPoint" );
-            Contract.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");    
+            Debug.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");    
             
             // Define the Init method itself.
             MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
@@ -553,7 +554,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
         {
             // Retrieve the constructor info for the base class's constructor.
             ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Array.Empty<Type>(), null );
-            Contract.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor");
+            Debug.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor");
             
             // Define the default constructor.
             MethodAttributes ctorAttributes = MethodAttributes.SpecialName | (DefaultBaseClsCons.Attributes & MethodAttributes.MemberAccessMask);
@@ -584,37 +585,37 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
         {
             // Find the cookie on the event sink helper.
             FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
-            Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");    
+            Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");    
 
             // Retrieve the ArrayList.Item property get method.
             PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
-            Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");    
+            Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");    
             MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
-            Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");    
+            Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");    
             
             // Retrieve the ArrayList.Count property get method.
             PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
-            Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");    
+            Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");    
             MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
-            Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");    
+            Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");    
             
             // Retrieve the ConnectionPoint.Unadvise() method.
             MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
-            Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");    
+            Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");    
 
             // Retrieve the Marshal.ReleaseComObject() method.
             MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
-            Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
+            Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
 
             // Retrieve the Monitor.Enter() method.
             MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
-            Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
+            Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
             
             // Retrieve the Monitor.Exit() method.
             Type[] aParamTypes = new Type[1];
             aParamTypes[0] = typeof(Object);
             MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
-            Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
+            Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
                         
             // Define the Finalize method itself.
             MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Finalize", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
@@ -743,7 +744,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
         {
             // Retrieve the method info for GC.SuppressFinalize().
             MethodInfo SuppressFinalizeMethod = typeof(GC).GetMethod("SuppressFinalize");
-            Contract.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize");    
+            Debug.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize");    
             
             // Define the Finalize method itself.
             MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Dispose", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
index 0367e79..862419c 100644 (file)
@@ -8,6 +8,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
     using System.Reflection;
     using System.Reflection.Emit;
     using System.Collections;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     internal class EventSinkHelperWriter
     {
@@ -65,7 +66,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
                     // Retrieve the delegate type from the add_XXX method.
                     MethodInfo AddMeth = m_EventItfType.GetMethod( "add_" + aMethods[cMethods].Name );
                     ParameterInfo[] aParams = AddMeth.GetParameters();
-                    Contract.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type");    
+                    Debug.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type");    
                     Type DelegateCls = aParams[0].ParameterType;
 
                     // Define the delegate instance field.
@@ -119,7 +120,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
         {
             // Retrieve the method info for the invoke method on the delegate.
             MethodInfo DelegateInvokeMethod = DelegateCls.GetMethod( "Invoke" );
-            Contract.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");    
+            Debug.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");    
     
             // Retrieve the return type.
             Type ReturnType = Method.ReturnType;
@@ -229,7 +230,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
                         if ( ReturnType == typeof(IntPtr) )
                             il.Emit( OpCodes.Ldc_I4_0 );
                         else
-                            Contract.Assert(false, "Unexpected type for Primitive type.");    
+                            Debug.Assert(false, "Unexpected type for Primitive type.");    
                         break;
                 }
             }
@@ -254,7 +255,7 @@ namespace System.Runtime.InteropServices.TCEAdapterGen {
         {
             // Retrieve the constructor info for the base classe's constructor.
             ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, Array.Empty<Type>(), null );
-            Contract.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);    
+            Debug.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);    
         
             // Define the default constructor.
             MethodBuilder Cons = OutputTypeBuilder.DefineMethod( ".ctor", 
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TypeLibConverter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TypeLibConverter.cs
deleted file mode 100644 (file)
index 629c414..0000000
+++ /dev/null
@@ -1,595 +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: Component that implements the ITypeLibConverter interface and
-**          does the actual work of converting a typelib to metadata and
-**          vice versa.
-**
-**
-=============================================================================*/
-#if !FEATURE_CORECLR // current implementation requires reflection only load 
-namespace System.Runtime.InteropServices {
-   
-    using System;
-    using System.Diagnostics.Contracts;
-    using System.Collections;
-    using System.Collections.Generic;
-    using System.Threading;
-    using System.Runtime.InteropServices.TCEAdapterGen;
-    using System.IO;
-    using System.Reflection;
-    using System.Reflection.Emit;
-    using System.Configuration.Assemblies;
-    using Microsoft.Win32;
-    using System.Runtime.CompilerServices;
-    using System.Globalization;
-    using System.Security;
-    using System.Security.Permissions;
-    using System.Runtime.InteropServices.ComTypes;
-    using System.Runtime.Versioning;
-    using WORD = System.UInt16;
-    using DWORD = System.UInt32;
-    using _TYPELIBATTR = System.Runtime.InteropServices.ComTypes.TYPELIBATTR;
-
-    [Guid("F1C3BF79-C3E4-11d3-88E7-00902754C43A")]
-    [ClassInterface(ClassInterfaceType.None)]
-[System.Runtime.InteropServices.ComVisible(true)]
-    public sealed class TypeLibConverter : ITypeLibConverter
-    {
-        private const String s_strTypeLibAssemblyTitlePrefix = "TypeLib ";
-        private const String s_strTypeLibAssemblyDescPrefix = "Assembly generated from typelib ";
-        private const int MAX_NAMESPACE_LENGTH = 1024;
-
-
-        //
-        // ITypeLibConverter interface.
-        //
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-        public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib, 
-                                                        String asmFileName,
-                                                        int flags,
-                                                        ITypeLibImporterNotifySink notifySink,
-                                                        byte[] publicKey,
-                                                        StrongNameKeyPair keyPair,
-                                                        bool unsafeInterfaces)
-        {
-            return ConvertTypeLibToAssembly(typeLib,
-                                            asmFileName,
-                                            (unsafeInterfaces
-                                                ? TypeLibImporterFlags.UnsafeInterfaces
-                                                : 0),
-                                            notifySink,
-                                            publicKey,
-                                            keyPair,
-                                            null,
-                                            null);
-        }
-
-
-
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-        public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib, 
-                                                        String asmFileName,
-                                                        TypeLibImporterFlags flags, 
-                                                        ITypeLibImporterNotifySink notifySink,
-                                                        byte[] publicKey,
-                                                        StrongNameKeyPair keyPair,
-                                                        String asmNamespace,
-                                                        Version asmVersion)
-        {
-            // Validate the arguments.
-            if (typeLib == null)
-                throw new ArgumentNullException(nameof(typeLib));
-            if (asmFileName == null)
-                throw new ArgumentNullException(nameof(asmFileName));         
-            if (notifySink == null)
-                throw new ArgumentNullException(nameof(notifySink));
-            if (String.Empty.Equals(asmFileName))
-                throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), nameof(asmFileName));
-            if (asmFileName.Length > Path.MaxPath)
-                throw new ArgumentException(Environment.GetResourceString("IO.PathTooLong"), asmFileName);
-            if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0 && publicKey == null && keyPair == null)
-                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed"));
-            Contract.EndContractBlock();
-
-            ArrayList eventItfInfoList = null;
-
-            // Determine the AssemblyNameFlags
-            AssemblyNameFlags asmNameFlags = AssemblyNameFlags.None;
-            
-            // Retrieve the assembly name from the typelib.
-            AssemblyName asmName = GetAssemblyNameFromTypelib(typeLib, asmFileName, publicKey, keyPair, asmVersion, asmNameFlags);
-
-            // Create the dynamic assembly that will contain the converted typelib types.
-            AssemblyBuilder asmBldr = CreateAssemblyForTypeLib(typeLib, asmFileName, asmName, 
-                                        (flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0,
-                                        (flags & TypeLibImporterFlags.ReflectionOnlyLoading) != 0,
-                                        (flags & TypeLibImporterFlags.NoDefineVersionResource) != 0);
-
-            // Define a dynamic module that will contain the contain the imported types.
-            String strNonQualifiedAsmFileName = Path.GetFileName(asmFileName);
-            ModuleBuilder modBldr = asmBldr.DefineDynamicModule(strNonQualifiedAsmFileName, strNonQualifiedAsmFileName);
-
-            // If the namespace hasn't been specified, then use the assembly name.
-            if (asmNamespace == null)
-                asmNamespace = asmName.Name;
-
-            // Create a type resolve handler that will also intercept resolve ref messages
-            // on the sink interface to build up a list of referenced assemblies.
-            TypeResolveHandler typeResolveHandler = new TypeResolveHandler(modBldr, notifySink);
-
-            // Add a listener for the type resolve events.
-            AppDomain currentDomain = Thread.GetDomain();
-            ResolveEventHandler resolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveEvent);
-            ResolveEventHandler asmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveAsmEvent);
-            ResolveEventHandler ROAsmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveROAsmEvent);
-            currentDomain.TypeResolve += resolveHandler;
-            currentDomain.AssemblyResolve += asmResolveHandler;
-            currentDomain.ReflectionOnlyAssemblyResolve += ROAsmResolveHandler;
-
-            // Convert the types contained in the typelib into metadata and add them to the assembly.
-            nConvertTypeLibToMetadata(typeLib, asmBldr.InternalAssembly, modBldr.InternalModule, asmNamespace, flags, typeResolveHandler, out eventItfInfoList);
-
-            // Update the COM types in the assembly.
-            UpdateComTypesInAssembly(asmBldr, modBldr);
-
-            // If there are any event sources then generate the TCE adapters.
-            if (eventItfInfoList.Count > 0)
-                new TCEAdapterGenerator().Process(modBldr, eventItfInfoList);
-
-            // Remove the listener for the type resolve events.
-            currentDomain.TypeResolve -= resolveHandler;
-            currentDomain.AssemblyResolve -= asmResolveHandler;
-            currentDomain.ReflectionOnlyAssemblyResolve -= ROAsmResolveHandler;
-
-            // We have finished converting the typelib and now have a fully formed assembly.
-            return asmBldr;
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-        [return : MarshalAs(UnmanagedType.Interface)]
-        public Object ConvertAssemblyToTypeLib(Assembly assembly, String strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink)
-        {
-            RuntimeAssembly rtAssembly;
-            AssemblyBuilder ab = assembly as AssemblyBuilder;
-            if (ab != null)
-                rtAssembly = ab.InternalAssembly;
-            else
-                rtAssembly = assembly as RuntimeAssembly;
-
-            return nConvertAssemblyToTypeLib(rtAssembly, strTypeLibName, flags, notifySink);
-        }
-
-        public bool GetPrimaryInteropAssembly(Guid g, Int32 major, Int32 minor, Int32 lcid, out String asmName, out String asmCodeBase)
-        {
-            String strTlbId = "{" + g.ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
-            String strVersion = major.ToString("x", CultureInfo.InvariantCulture) + "." + minor.ToString("x", CultureInfo.InvariantCulture);
-
-            // Set the two out values to null before we start.
-            asmName = null;
-            asmCodeBase = null;
-
-            // Try to open the HKEY_CLASS_ROOT\TypeLib key.
-            using (RegistryKey TypeLibKey = Registry.ClassesRoot.OpenSubKey("TypeLib", false))
-            {
-                if (TypeLibKey != null)
-                {
-                    // Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID> key.            
-                    using (RegistryKey TypeLibSubKey = TypeLibKey.OpenSubKey(strTlbId))
-                    {
-                        if (TypeLibSubKey != null)
-                        {
-                            // Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID>\<Major.Minor> key.
-                            using (RegistryKey VersionKey = TypeLibSubKey.OpenSubKey(strVersion, false))
-                            {
-                                if (VersionKey != null)
-                                {
-                                    // Attempt to retrieve the assembly name and codebase under the version key.
-                                    asmName = (String)VersionKey.GetValue("PrimaryInteropAssemblyName");
-                                    asmCodeBase = (String)VersionKey.GetValue("PrimaryInteropAssemblyCodeBase");
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-            
-            // If the assembly name isn't null, then we found an PIA.
-            return asmName != null;
-        }
-
-
-        //
-        // Non native helper methods.
-        //
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
-        private static AssemblyBuilder CreateAssemblyForTypeLib(Object typeLib, String asmFileName, AssemblyName asmName, bool bPrimaryInteropAssembly, bool bReflectionOnly, bool bNoDefineVersionResource)
-        {
-            // Retrieve the current app domain.
-            AppDomain currentDomain = Thread.GetDomain();
-
-            // Retrieve the directory from the assembly file name.
-            String dir = null;
-            if (asmFileName != null)
-            {
-                dir = Path.GetDirectoryName(asmFileName);
-                if (String.IsNullOrEmpty(dir))
-                    dir = null;
-            }
-
-            AssemblyBuilderAccess aba;
-            if (bReflectionOnly)
-            {
-                aba = AssemblyBuilderAccess.ReflectionOnly;
-            }
-            else
-            {
-                aba = AssemblyBuilderAccess.RunAndSave;
-            }
-
-            // Create the dynamic assembly itself.
-            AssemblyBuilder asmBldr;
-
-            List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
-#if !FEATURE_CORECLR
-            // mscorlib.dll must specify the security rules that assemblies it emits are to use, since by
-            // default all assemblies will follow security rule set level 2, and we want to make that an
-            // explicit decision.
-            ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) });
-            CustomAttributeBuilder securityRulesAttribute =
-                new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level2 });
-            assemblyAttributes.Add(securityRulesAttribute);
-#endif // !FEATURE_CORECLR
-
-            asmBldr = currentDomain.DefineDynamicAssembly(asmName, aba, dir, false, assemblyAttributes);
-
-            // Set the Guid custom attribute on the assembly.
-            SetGuidAttributeOnAssembly(asmBldr, typeLib);
-
-            // Set the imported from COM attribute on the assembly and return it.
-            SetImportedFromTypeLibAttrOnAssembly(asmBldr, typeLib);
-
-            // Set the version information on the typelib.
-            if (bNoDefineVersionResource)
-            {
-                SetTypeLibVersionAttribute(asmBldr, typeLib);
-            }
-            else
-            {
-            SetVersionInformation(asmBldr, typeLib, asmName);
-            }
-
-            // If we are generating a PIA, then set the PIA custom attribute.
-            if (bPrimaryInteropAssembly)
-                SetPIAAttributeOnAssembly(asmBldr, typeLib);
-
-            return asmBldr;
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static AssemblyName GetAssemblyNameFromTypelib(Object typeLib, String asmFileName, byte[] publicKey, StrongNameKeyPair keyPair, Version asmVersion, AssemblyNameFlags asmNameFlags)
-        {
-            // Extract the name of the typelib.
-            String strTypeLibName = null;
-            String strDocString = null;
-            int dwHelpContext = 0;
-            String strHelpFile = null;
-            ITypeLib pTLB = (ITypeLib)typeLib;
-            pTLB.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
-
-            // Retrieve the name to use for the assembly.
-            if (asmFileName == null)
-            {
-                asmFileName = strTypeLibName;
-            }
-            else
-            {
-                Contract.Assert((asmFileName != null) && (asmFileName.Length > 0), "The assembly file name cannot be an empty string!");
-
-                String strFileNameNoPath = Path.GetFileName(asmFileName);
-                String strExtension = Path.GetExtension(asmFileName);
-
-                // Validate that the extension is valid.
-                bool bExtensionValid = ".dll".Equals(strExtension, StringComparison.OrdinalIgnoreCase);
-
-                // If the extension is not valid then tell the user and quit.
-                if (!bExtensionValid)
-                    throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileExtension"));
-
-                // The assembly cannot contain the path nor the extension.
-                asmFileName = strFileNameNoPath.Substring(0, strFileNameNoPath.Length - ".dll".Length);
-            }
-
-            // If the version information was not specified, then retrieve it from the typelib.
-            if (asmVersion == null)
-            {
-                int major;
-                int minor;
-                Marshal.GetTypeLibVersion(pTLB, out major, out minor);
-                asmVersion = new Version(major, minor, 0, 0);
-            }
-            
-            // Create the assembly name for the imported typelib's assembly.
-            AssemblyName AsmName = new AssemblyName();
-            AsmName.Init(
-                asmFileName,
-                publicKey,
-                null,
-                asmVersion,
-                null,
-                AssemblyHashAlgorithm.None,
-                AssemblyVersionCompatibility.SameMachine,
-                null,
-                asmNameFlags,
-                keyPair);
-
-            return AsmName;
-        }
-
-        private static void UpdateComTypesInAssembly(AssemblyBuilder asmBldr, ModuleBuilder modBldr)
-        {
-            // Retrieve the AssemblyBuilderData associated with the assembly builder.
-            AssemblyBuilderData AsmBldrData = asmBldr.m_assemblyData;
-
-            // Go through the types in the module and add them as public COM types.
-            Type[] aTypes = modBldr.GetTypes();
-            int NumTypes = aTypes.Length;
-            for (int cTypes = 0; cTypes < NumTypes; cTypes++)
-                AsmBldrData.AddPublicComType(aTypes[cTypes]);
-        }
-
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private static void SetGuidAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
-        {
-            // Retrieve the GuidAttribute constructor.
-            Type []aConsParams = new Type[1] {typeof(String)};
-            ConstructorInfo GuidAttrCons = typeof(GuidAttribute).GetConstructor(aConsParams);
-
-            // Create an instance of the custom attribute builder.
-            Object[] aArgs = new Object[1] {Marshal.GetTypeLibGuid((ITypeLib)typeLib).ToString()};
-            CustomAttributeBuilder GuidCABuilder = new CustomAttributeBuilder(GuidAttrCons, aArgs);
-
-            // Set the GuidAttribute on the assembly builder.
-            asmBldr.SetCustomAttribute(GuidCABuilder);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private static void SetImportedFromTypeLibAttrOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
-        {
-            // Retrieve the ImportedFromTypeLibAttribute constructor.
-            Type []aConsParams = new Type[1] {typeof(String)};
-            ConstructorInfo ImpFromComAttrCons = typeof(ImportedFromTypeLibAttribute).GetConstructor(aConsParams);
-
-            // Retrieve the name of the typelib.
-            String strTypeLibName = Marshal.GetTypeLibName((ITypeLib)typeLib);
-
-            // Create an instance of the custom attribute builder.
-            Object[] aArgs = new Object[1] {strTypeLibName};
-            CustomAttributeBuilder ImpFromComCABuilder = new CustomAttributeBuilder(ImpFromComAttrCons, aArgs);
-
-            // Set the ImportedFromTypeLibAttribute on the assembly builder.
-            asmBldr.SetCustomAttribute(ImpFromComCABuilder);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private static void SetTypeLibVersionAttribute(AssemblyBuilder asmBldr, Object typeLib)
-        {
-            Type []aConsParams = new Type[2] {typeof(int), typeof(int)};
-            ConstructorInfo TypeLibVerCons = typeof(TypeLibVersionAttribute).GetConstructor(aConsParams);
-
-            // Get the typelib version
-            int major;
-            int minor;
-            Marshal.GetTypeLibVersion((ITypeLib)typeLib, out major, out minor);
-            
-            // Create an instance of the custom attribute builder.
-            Object[] aArgs = new Object[2] {major, minor};
-            CustomAttributeBuilder TypeLibVerBuilder = new CustomAttributeBuilder(TypeLibVerCons, aArgs);
-
-            // Set the attribute on the assembly builder.
-            asmBldr.SetCustomAttribute(TypeLibVerBuilder);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private static void SetVersionInformation(AssemblyBuilder asmBldr, Object typeLib, AssemblyName asmName)
-        {
-            // Extract the name of the typelib.
-            String strTypeLibName = null;
-            String strDocString = null;
-            int dwHelpContext = 0;
-            String strHelpFile = null;
-            ITypeLib pTLB = (ITypeLib)typeLib;
-            pTLB.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
-
-            // Generate the product name string from the named of the typelib.
-            String strProductName = String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("TypeLibConverter_ImportedTypeLibProductName"), strTypeLibName);
-
-            // Set the OS version information.
-            asmBldr.DefineVersionInfoResource(strProductName, asmName.Version.ToString(), null, null, null);
-
-            // Set the TypeLibVersion attribute
-            SetTypeLibVersionAttribute(asmBldr, typeLib);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
-        {
-            IntPtr pAttr = IntPtr.Zero;
-            _TYPELIBATTR Attr;
-            ITypeLib pTLB = (ITypeLib)typeLib;
-            int Major = 0;
-            int Minor = 0;
-
-            // Retrieve the PrimaryInteropAssemblyAttribute constructor.
-            Type []aConsParams = new Type[2] {typeof(int), typeof(int)};
-            ConstructorInfo PIAAttrCons = typeof(PrimaryInteropAssemblyAttribute).GetConstructor(aConsParams);
-
-            // Retrieve the major and minor version from the typelib.
-            try
-            {
-                pTLB.GetLibAttr(out pAttr);
-                Attr = (_TYPELIBATTR)Marshal.PtrToStructure(pAttr, typeof(_TYPELIBATTR));
-                Major = Attr.wMajorVerNum;
-                Minor = Attr.wMinorVerNum;
-            }
-            finally
-            {
-                // Release the typelib attributes.
-                if (pAttr != IntPtr.Zero)
-                    pTLB.ReleaseTLibAttr(pAttr);
-            }
-
-            // Create an instance of the custom attribute builder.
-            Object[] aArgs = new Object[2] {Major, Minor};
-            CustomAttributeBuilder PIACABuilder = new CustomAttributeBuilder(PIAAttrCons, aArgs);
-
-            // Set the PrimaryInteropAssemblyAttribute on the assembly builder.
-            asmBldr.SetCustomAttribute(PIACABuilder);
-        }
-
-
-        //
-        // Native helper methods.
-        //
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)] 
-        private static extern void nConvertTypeLibToMetadata(Object typeLib, RuntimeAssembly asmBldr, RuntimeModule modBldr, String nameSpace, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, out ArrayList eventItfInfoList);
-
-        // Must use assembly versioning or GuidAttribute to avoid collisions in typelib export or registration.
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)] 
-        private static extern Object nConvertAssemblyToTypeLib(RuntimeAssembly assembly, String strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink);
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        internal extern static void LoadInMemoryTypeByName(RuntimeModule module, String className);
-
-        //
-        // Helper class called when a resolve type event is fired.
-        //
-
-        private class TypeResolveHandler : ITypeLibImporterNotifySink
-        {
-            public TypeResolveHandler(ModuleBuilder mod, ITypeLibImporterNotifySink userSink)
-            {
-                m_Module = mod;
-                m_UserSink = userSink;
-            }
-
-            public void ReportEvent(ImporterEventKind eventKind, int eventCode, String eventMsg)
-            {
-                m_UserSink.ReportEvent(eventKind, eventCode, eventMsg);
-            }
-
-            public Assembly ResolveRef(Object typeLib)
-            {
-                Contract.Ensures(Contract.Result<Assembly>() != null && Contract.Result<Assembly>() is RuntimeAssembly);
-                Contract.EndContractBlock();
-
-                // Call the user sink to resolve the reference.
-                Assembly asm = m_UserSink.ResolveRef(typeLib);
-
-                if (asm == null)
-                    throw new ArgumentNullException();
-
-                // Return the resolved assembly. We extract the internal assembly because we are called
-                // by the VM which accesses fields of the object directly and does not go via those
-                // delegating properties (the fields are empty if asm is an (external) AssemblyBuilder).
-
-                RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
-                if (rtAssembly == null)
-                {
-                    AssemblyBuilder ab = asm as AssemblyBuilder;
-                    if (ab != null)
-                        rtAssembly = ab.InternalAssembly;
-                }
-
-                if (rtAssembly == null)
-                    throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
-
-                // Add the assembly to the list of assemblies.
-                m_AsmList.Add(rtAssembly);
-
-                return rtAssembly;
-            }
-
-            [System.Security.SecurityCritical]  // auto-generated
-            public Assembly ResolveEvent(Object sender, ResolveEventArgs args)
-            {
-                // We need to load the type in the resolve event so that we will deal with
-                // cases where we are trying to load the CoClass before the interface has 
-                // been loaded.               
-                try
-                {
-                    LoadInMemoryTypeByName(m_Module.GetNativeHandle(), args.Name); 
-                    return m_Module.Assembly;
-                }
-                catch (TypeLoadException e)
-                {
-                    if (e.ResourceId != System.__HResults.COR_E_TYPELOAD)  // type not found
-                        throw;
-                }
-
-                foreach (RuntimeAssembly asm in m_AsmList)
-                {
-                    try
-                    {
-                        asm.GetType(args.Name, true, false);
-                        return asm;
-                    }
-                    catch (TypeLoadException e)
-                    {
-                        if (e._HResult != System.__HResults.COR_E_TYPELOAD)  // type not found
-                            throw;
-                    }
-                }
-                
-                return null;
-            }
-
-            public Assembly ResolveAsmEvent(Object sender, ResolveEventArgs args)
-            {
-                foreach (RuntimeAssembly asm in m_AsmList)
-                {
-                    if (String.Compare(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase) == 0)
-                        return asm;
-                }
-
-                return null;
-            }
-
-            public Assembly ResolveROAsmEvent(Object sender, ResolveEventArgs args)
-            {
-                foreach (RuntimeAssembly asm in m_AsmList)
-                {
-                    if (String.Compare(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase) == 0)
-                        return asm;
-                }
-
-                // We failed to find the referenced assembly in our pre-loaded assemblies, so try to load it based on policy.
-                string asmName = AppDomain.CurrentDomain.ApplyPolicy(args.Name);
-                return Assembly.ReflectionOnlyLoad(asmName);
-            }
-
-            private ModuleBuilder m_Module;
-            private ITypeLibImporterNotifySink m_UserSink;
-            private List<RuntimeAssembly> m_AsmList = new List<RuntimeAssembly>();
-        }
-    }
-}
-#endif // !FEATURE_CORECLR // current implementation requires reflection only load
-
index 9be1588..c7bbb78 100644 (file)
@@ -11,7 +11,6 @@ namespace System.Runtime.InteropServices {
     /// to and from COM calls.
     /// </summary>
     [StructLayout(LayoutKind.Explicit)]
-    [System.Security.SecurityCritical]
     internal struct Variant {
 
 #if DEBUG
index e9d2cdd..e3c6a92 100644 (file)
@@ -9,6 +9,7 @@ using System.Runtime;
 using System.Security;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -27,12 +28,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private BindableVectorToCollectionAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // int Count { get }
         [Pure]
-        [SecurityCritical]
         internal int Count()
         {
             IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
@@ -47,7 +47,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // bool IsSynchronized { get }
         [Pure]
-        [SecurityCritical]
         internal bool IsSynchronized()
         {
             return false;
@@ -55,7 +54,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // object SyncRoot { get }
         [Pure]
-        [SecurityCritical]
         internal object SyncRoot()
         {
             return this;
@@ -63,7 +61,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // void CopyTo(Array array, int index)
         [Pure]
-        [SecurityCritical]
         internal void CopyTo(Array array, int arrayIndex)
         {
             if (array == null)
index 6ec2933..d6e50f5 100644 (file)
@@ -9,6 +9,7 @@ using System.Runtime;
 using System.Security;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -27,11 +28,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private BindableVectorToListAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // object this[int index] { get }
-        [SecurityCritical]
         internal object Indexer_Get(int index)
         {
             if (index < 0)
@@ -42,7 +42,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // object this[int index] { set }
-        [SecurityCritical]
         internal void Indexer_Set(int index, object value)
         {
             if (index < 0)
@@ -53,7 +52,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // int Add(object value)
-        [SecurityCritical]
         internal int Add(object value)
         {
             IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
@@ -69,7 +67,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool Contains(object item)
-        [SecurityCritical]
         internal bool Contains(object item)
         {
             IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
@@ -79,7 +76,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Clear()
-        [SecurityCritical]
         internal void Clear()
         {
             IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
@@ -88,7 +84,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // bool IsFixedSize { get }
         [Pure]
-        [SecurityCritical]
         internal bool IsFixedSize()
         {
             return false;
@@ -96,14 +91,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // bool IsReadOnly { get }
         [Pure]
-        [SecurityCritical]
         internal bool IsReadOnly()
         {
             return false;
         }
 
         // int IndexOf(object item)
-        [SecurityCritical]
         internal int IndexOf(object item)
         {
             IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
@@ -123,7 +116,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Insert(int index, object item)
-        [SecurityCritical]
         internal void Insert(int index, object item)
         {
             if (index < 0)
@@ -134,7 +126,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool Remove(object item)
-        [SecurityCritical]
         internal void Remove(object item)
         {
             IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
@@ -154,7 +145,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void RemoveAt(int index)
-        [SecurityCritical]
         internal void RemoveAt(int index)
         {
             if (index < 0)
index c88f13d..702e0c9 100644 (file)
@@ -184,7 +184,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         [Pure]
-        [SecuritySafeCritical]
         public Point GetPoint()
         {
             if (this.Type != PropertyType.Point)
@@ -195,7 +194,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         [Pure]
-        [SecuritySafeCritical]
         public Size GetSize()
         {
             if (this.Type != PropertyType.Size)
@@ -206,7 +204,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         [Pure]
-        [SecuritySafeCritical]
         public Rect GetRect()
         {
             if (this.Type != PropertyType.Rect)
@@ -328,7 +325,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         [Pure]
-        [SecuritySafeCritical]
         public Point[] GetPointArray()
         {
             if (this.Type != PropertyType.PointArray)
@@ -339,7 +335,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         [Pure]
-        [SecuritySafeCritical]
         public Size[] GetSizeArray()
         {
             if (this.Type != PropertyType.SizeArray)
@@ -351,7 +346,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         [Pure]
-        [SecuritySafeCritical]
         public Rect[] GetRectArray()
         {
             if (this.Type != PropertyType.RectArray)
@@ -505,7 +499,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // Unbox the data stored in the property value to a structurally equivilent type
         [Pure]
-        [SecurityCritical]
         private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct {
             Contract.Requires(expectedBoxedType != null);
             Contract.Requires(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T)));
@@ -526,7 +519,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // Convert the array stored in the property value to a structurally equivilent array type
         [Pure]
-        [SecurityCritical]
         private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct {
             Contract.Requires(expectedArrayElementType != null);
             Contract.Requires(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T)));
index e379d38..9705b61 100644 (file)
@@ -6,6 +6,7 @@
 
 using System;
 using System.Collections;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Reflection;
 using System.Security;
@@ -55,7 +56,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         {
             Contract.Requires(wrapper != null);
             IReference<T> reference = (IReference<T>) wrapper;
-            Contract.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed.");
+            Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed.");
             return reference.Value;
         }
     }
@@ -216,7 +217,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         {
             Contract.Requires(wrapper != null);
             IReferenceArray<T> reference = (IReferenceArray<T>)wrapper;
-            Contract.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed.");
+            Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed.");
             T[] marshaled = reference.Value;
             return marshaled;
         }
@@ -229,7 +230,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, " + AssemblyRef.SystemRuntimeWindowsRuntime);
         internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, " + AssemblyRef.SystemRuntimeWindowsRuntime);
 
-        [SecuritySafeCritical]
         internal static Object CreateIReference(Object obj)
         {
             Contract.Requires(obj != null, "Null should not be boxed.");
@@ -302,11 +302,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj });
             }
 
-            Contract.Assert(false, "We should not see non-WinRT type here");
+            Debug.Assert(false, "We should not see non-WinRT type here");
             return null;
         }
 
-        [SecuritySafeCritical]
         internal static Object CreateIReferenceArray(Array obj)
         {
             Contract.Requires(obj != null);
@@ -315,7 +314,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
             Type type = obj.GetType().GetElementType();
             
-            Contract.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
+            Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
 
             if (type == typeof(int))
                 return new CLRIReferenceArrayImpl<int>(PropertyType.Int32Array, (int[])obj);
index 85ebd71..d575201 100644 (file)
@@ -7,6 +7,7 @@
 using System;
 using System.Security;
 using System.Reflection;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -88,7 +89,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             InvokeInternal(target, new object[] { indexValue, value }, false);
         }
 
-        [SecuritySafeCritical]
         private object InvokeInternal(object target, object[] args, bool getValue)
         {
             // Forward to the right object if we are dealing with a proxy
@@ -123,7 +123,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
             // We can safely skip access check because this is only used in full trust scenarios.
             // And we have already verified that the property accessor is public.
-            Contract.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted());
+            Debug.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted());
             return rtMethod.UnsafeInvoke(target, BindingFlags.Default, null, args, null);
         }
 
index fa021b7..24e5777 100644 (file)
@@ -10,6 +10,7 @@ using System.Reflection;
 using System.Collections;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -28,11 +29,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private DictionaryToMapAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // V Lookup(K key)
-        [SecurityCritical]
         internal V Lookup<K, V>(K key)
         {
             IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
@@ -50,7 +50,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // uint Size { get }
-        [SecurityCritical]
         internal uint Size<K, V>()
         {
             IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
@@ -58,7 +57,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
         
         // bool HasKey(K key)
-        [SecurityCritical]
         internal bool HasKey<K, V>(K key)
         {
             IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
@@ -66,11 +64,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // IMapView<K, V> GetView()
-        [SecurityCritical]
         internal IReadOnlyDictionary<K, V> GetView<K, V>()
         {
             IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
-            Contract.Assert(_this != null);
+            Debug.Assert(_this != null);
 
             // Note: This dictionary is not really read-only - you could QI for a modifiable
             // dictionary.  We gain some perf by doing this.  We believe this is acceptable.
@@ -83,7 +80,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool Insert(K key, V value)
-        [SecurityCritical]
         internal bool Insert<K, V>(K key, V value)
         {
             IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
@@ -93,7 +89,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Remove(K key)
-        [SecurityCritical]
         internal void Remove<K, V>(K key)
         {
             IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
@@ -108,7 +103,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Clear()
-        [SecurityCritical]
         internal void Clear<K, V>()
         {
             IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
index 7329d31..3f9d516 100644 (file)
@@ -7,6 +7,7 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -25,11 +26,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private EnumerableToIterableAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // This method is invoked when First is called on a managed implementation of IIterable<T>.
-        [System.Security.SecurityCritical]
         internal IIterator<T> First_Stub<T>()
         {
             IEnumerable<T> _this = JitHelpers.UnsafeCast<IEnumerable<T>>(this);
@@ -41,7 +41,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private EnumerableToBindableIterableAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         internal sealed class NonGenericToGenericEnumerator : IEnumerator<object>
@@ -58,7 +58,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // This method is invoked when First is called on a managed implementation of IBindableIterable.
-        [System.Security.SecurityCritical]
         internal IBindableIterator First_Stub()
         {
             IEnumerable _this = JitHelpers.UnsafeCast<IEnumerable>(this);
index 847147a..4c6169a 100644 (file)
@@ -7,6 +7,7 @@
 using System;
 using System.Security;
 using System.Collections;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.CompilerServices;
 
@@ -27,10 +28,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private IDisposableToIClosableAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
-        [SecurityCritical]
         public void Close()
         {
             IDisposable _this = JitHelpers.UnsafeCast<IDisposable>(this);
@@ -39,15 +39,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     }
 
     // Adapter class which converts IDisposable.Dispose calls into IClosable.Close
-    [SecurityCritical]
     internal sealed class IClosableToIDisposableAdapter
     {
         private IClosableToIDisposableAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
-        [SecurityCritical]
         private void Dispose()
         {
             IClosable _this = JitHelpers.UnsafeCast<IClosable>(this);
index 143a33e..3bbde35 100644 (file)
@@ -50,7 +50,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         // Creates a ICustomProperty implementation for Jupiter
         // Called from ICustomPropertyProvider_GetIndexedProperty from within runtime
         //               
-        [System.Security.SecurityCritical]
         static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative *pIndexedParamType)
         {
             Contract.Requires(target != null);
@@ -87,7 +86,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 return new CustomPropertyImpl(propertyInfo);
         }
 
-        [System.Security.SecurityCritical]
         static internal unsafe void GetType(object target, TypeNameNative *pIndexedParamType)
         {            
             IGetProxyTarget proxy = target as IGetProxyTarget;
@@ -207,7 +205,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         // 
         // ICustomQueryInterface methods
         //    
-        [System.Security.SecurityCritical]
         public CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv)
         {
             ppv = IntPtr.Zero;
@@ -441,7 +438,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             }            
         }
 
-        [SecuritySafeCritical]
         private IBindableVector GetIBindableVectorNoThrow()
         {
             if ((_flags & InterfaceForwardingSupport.IBindableVector) != 0)
@@ -450,7 +446,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 return null;
         }
 
-        [SecuritySafeCritical]
         private IVector_Raw<T1> GetVectorOfT()
         {
             if ((_flags & InterfaceForwardingSupport.IVector) != 0)
@@ -517,7 +512,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             public bool MoveNext() { return _iterator.MoveNext(); }
         }         
 
-        [SecuritySafeCritical]
         private IBindableVectorView GetIBindableVectorViewNoThrow()
         {
             if ((_flags & InterfaceForwardingSupport.IBindableVectorView) != 0)
@@ -526,7 +520,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 return null;
         }
 
-        [SecuritySafeCritical]
         private IVectorView<T2> GetVectorViewOfT()
         {
             if ((_flags & InterfaceForwardingSupport.IVectorView) != 0)
index 32bbd3f..a7424da 100644 (file)
@@ -28,11 +28,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private IMapViewToIReadOnlyDictionaryAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // V this[K key] { get }
-        [SecurityCritical]
         internal V Indexer_Get<K, V>(K key)
         {
             if (key == null)
@@ -44,7 +43,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // IEnumerable<K> Keys { get }
-        [SecurityCritical]
         internal IEnumerable<K> Keys<K, V>()
         {
             IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
@@ -53,7 +51,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // IEnumerable<V> Values { get }
-        [SecurityCritical]
         internal IEnumerable<V> Values<K, V>()
         {
             IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
@@ -63,7 +60,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // bool ContainsKey(K key)
         [Pure]
-        [SecurityCritical]
         internal bool ContainsKey<K, V>(K key)
         {
             if (key == null)
@@ -74,7 +70,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool TryGetValue(TKey key, out TValue value)
-        [SecurityCritical]
         internal bool TryGetValue<K, V>(K key, out V value)
         {
             if (key == null)
index d57f8f1..b185b41 100644 (file)
@@ -28,11 +28,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private IReadOnlyDictionaryToIMapViewAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // V Lookup(K key)
-        [SecurityCritical]
         internal V Lookup<K, V>(K key)
         {
             IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
@@ -50,7 +49,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // uint Size { get }
-        [SecurityCritical]
         internal uint Size<K, V>()
         {
             IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
@@ -58,7 +56,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
         
         // bool HasKey(K key)
-        [SecurityCritical]
         internal bool HasKey<K, V>(K key)
         {
             IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
@@ -66,7 +63,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Split(out IMapView<K, V> first, out IMapView<K, V> second)
-        [SecurityCritical]
         internal void Split<K, V>(out IMapView<K, V> first, out IMapView<K, V> second)
         {
             IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
index c37c32d..431d162 100644 (file)
@@ -28,11 +28,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private IReadOnlyListToIVectorViewAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // T GetAt(uint index)
-        [SecurityCritical]
         internal T GetAt<T>(uint index)
         {
             IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this);
@@ -50,7 +49,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // uint Size { get }
-        [SecurityCritical]
         internal uint Size<T>()
         {
             IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this);
@@ -58,7 +56,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool IndexOf(T value, out uint index)
-        [SecurityCritical]
         internal bool IndexOf<T>(T value, out uint index)
         {
             IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this);
@@ -85,7 +82,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // uint GetMany(uint startIndex, T[] items)
-        [SecurityCritical]
         internal uint GetMany<T>(uint startIndex, T[] items)
         {
             IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this);
index 48bcc4f..9de5e3f 100644 (file)
@@ -8,9 +8,7 @@ using System;
 
 namespace System.Runtime.InteropServices.WindowsRuntime
 {
-#if FEATURE_CORECLR
     [System.Runtime.CompilerServices.FriendAccessAllowed]
-#endif
     [ComImport]
     [Guid("82BA7092-4C88-427D-A7BC-16DD93FEB67E")]
     [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
index bb497ca..37f2130 100644 (file)
@@ -30,11 +30,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private IVectorViewToIReadOnlyListAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // T this[int index] { get }
-        [SecurityCritical]
         internal T Indexer_Get<T>(int index)
         {
             if (index < 0)
@@ -59,7 +58,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // T this[int index] { get }
-        [SecurityCritical]
         internal T Indexer_Get_Variance<T>(int index) where T : class
         {
             bool fUseString;
index 061a732..e219a86 100644 (file)
@@ -7,6 +7,7 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -28,11 +29,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private IterableToEnumerableAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
         
         // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable<T>.
-        [SecurityCritical]
         internal IEnumerator<T> GetEnumerator_Stub<T>()
         {
             IIterable<T> _this = JitHelpers.UnsafeCast<IIterable<T>>(this);
@@ -43,7 +43,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         // and it is possible that the implementation supports IEnumerable<Type>/IEnumerable<string>/IEnumerable<Exception>/
         // IEnumerable<array>/IEnumerable<delegate> rather than IEnumerable<T> because T is assignable from Type/string/
         // Exception/array/delegate via co-variance.
-        [SecurityCritical]
         internal IEnumerator<T> GetEnumerator_Variance_Stub<T>() where T : class
         {
             bool fUseString;
@@ -70,7 +69,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private BindableIterableToEnumerableAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         private sealed class NonGenericToGenericIterator : IIterator<object>
@@ -87,7 +86,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable.
-        [SecurityCritical]
         internal IEnumerator GetEnumerator_Stub()
         {
             IBindableIterable _this = JitHelpers.UnsafeCast<IBindableIterable>(this);
@@ -145,7 +143,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             }
         }
 
-        [SecuritySafeCritical]
         public bool MoveNext()
         {
             // If we've passed the end of the iteration, IEnumerable<T> should return false, while
index 3cf1d4d..b9fe115 100644 (file)
@@ -10,6 +10,7 @@ using System.Reflection;
 using System.Collections;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -28,11 +29,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private ListToBindableVectorAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // object GetAt(uint index)
-        [SecurityCritical]
         internal object GetAt(uint index)
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
@@ -49,7 +49,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // uint Size { get }
-        [SecurityCritical]
         internal uint Size()
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
@@ -57,7 +56,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // IBindableVectorView GetView()
-        [SecurityCritical]
         internal IBindableVectorView GetView()
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
@@ -65,7 +63,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool IndexOf(object value, out uint index)
-        [SecurityCritical]
         internal bool IndexOf(object value, out uint index)
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
@@ -82,7 +79,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void SetAt(uint index, object value)
-        [SecurityCritical]
         internal void SetAt(uint index, object value)
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
@@ -99,7 +95,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void InsertAt(uint index, object value)
-        [SecurityCritical]
         internal void InsertAt(uint index, object value)
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
@@ -121,7 +116,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void RemoveAt(uint index)
-        [SecurityCritical]
         internal void RemoveAt(uint index)
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
@@ -140,7 +134,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Append(object value)
-        [SecurityCritical]
         internal void Append(object value)
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
@@ -148,7 +141,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void RemoveAtEnd()
-        [SecurityCritical]
         internal void RemoveAtEnd()
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
@@ -164,7 +156,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Clear()
-        [SecurityCritical]
         internal void Clear()
         {
             IList _this = JitHelpers.UnsafeCast<IList>(this);
index cb61168..b73f4d7 100644 (file)
@@ -10,6 +10,7 @@ using System.Reflection;
 using System.Collections;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -28,11 +29,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private ListToVectorAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // T GetAt(uint index)
-        [SecurityCritical]
         internal T GetAt<T>(uint index)
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -49,7 +49,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // uint Size { get }
-        [SecurityCritical]
         internal uint Size<T>()
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -57,11 +56,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // IVectorView<T> GetView()
-        [SecurityCritical]
         internal IReadOnlyList<T> GetView<T>()
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
-            Contract.Assert(_this != null);
+            Debug.Assert(_this != null);
 
             // Note: This list is not really read-only - you could QI for a modifiable
             // list.  We gain some perf by doing this.  We believe this is acceptable.
@@ -74,7 +72,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool IndexOf(T value, out uint index)
-        [SecurityCritical]
         internal bool IndexOf<T>(T value, out uint index)
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -91,7 +88,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void SetAt(uint index, T value)
-        [SecurityCritical]
         internal void SetAt<T>(uint index, T value)
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -108,7 +104,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void InsertAt(uint index, T value)
-        [SecurityCritical]
         internal void InsertAt<T>(uint index, T value)
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -130,7 +125,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void RemoveAt(uint index)
-        [SecurityCritical]
         internal void RemoveAt<T>(uint index)
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -149,7 +143,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Append(T value)
-        [SecurityCritical]
         internal void Append<T>(T value)
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -157,7 +150,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void RemoveAtEnd()
-        [SecurityCritical]
         internal void RemoveAtEnd<T>()
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -173,7 +165,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Clear()
-        [SecurityCritical]
         internal void Clear<T>()
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -181,7 +172,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // uint GetMany(uint startIndex, T[] items)
-        [SecurityCritical]
         internal uint GetMany<T>(uint startIndex, T[] items)
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
@@ -189,7 +179,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void ReplaceAll(T[] items)
-        [SecurityCritical]
         internal void ReplaceAll<T>(T[] items)
         {
             IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
index cb710ff..2d08cab 100644 (file)
@@ -33,7 +33,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private Type m_type;
 
-        [SecurityCritical]
         internal ManagedActivationFactory(Type type)
         {
             if (type == null)
index 4517e15..f11260e 100644 (file)
@@ -8,6 +8,7 @@ using System;
 using System.Security;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -29,12 +30,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private MapToCollectionAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // int Count { get }
         [Pure]
-        [SecurityCritical]
         internal int Count<K, V>()
         {
             object _this = JitHelpers.UnsafeCast<object>(this);
@@ -66,14 +66,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool IsReadOnly { get }
-        [SecurityCritical]
         internal bool IsReadOnly<K, V>()
         {
             return false;
         }
 
         // void Add(T item)
-        [SecurityCritical]
         internal void Add<K, V>(KeyValuePair<K, V> item)
         {
             object _this = JitHelpers.UnsafeCast<object>(this);
@@ -91,7 +89,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Clear()
-        [SecurityCritical]
         internal void Clear<K, V>()
         {
             object _this = JitHelpers.UnsafeCast<object>(this);
@@ -109,7 +106,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool Contains(T item)
-        [SecurityCritical]
         internal bool Contains<K, V>(KeyValuePair<K, V> item)
         {
             object _this = JitHelpers.UnsafeCast<object>(this);
@@ -135,7 +131,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void CopyTo(T[] array, int arrayIndex)
-        [SecurityCritical]
         internal void CopyTo<K, V>(KeyValuePair<K, V>[] array, int arrayIndex)
         {
             if (array == null)
@@ -160,7 +155,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool Remove(T item)
-        [SecurityCritical]
         internal bool Remove<K, V>(KeyValuePair<K, V> item)
         {
             object _this = JitHelpers.UnsafeCast<object>(this);
index d032937..981972c 100644 (file)
@@ -8,6 +8,7 @@ using System;
 using System.Security;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -26,11 +27,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private MapToDictionaryAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // V this[K key] { get }
-        [SecurityCritical]
         internal V Indexer_Get<K, V>(K key)
         {
             if (key == null)
@@ -43,7 +43,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // V this[K key] { set }
-        [SecurityCritical]
         internal void Indexer_Set<K, V>(K key, V value)
         {
             if (key == null)
@@ -56,7 +55,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // ICollection<K> Keys { get }
-        [SecurityCritical]
         internal ICollection<K> Keys<K, V>()
         {
             IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this);
@@ -65,7 +63,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // ICollection<V> Values { get }
-        [SecurityCritical]
         internal ICollection<V> Values<K, V>()
         {
             IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this);
@@ -75,7 +72,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // bool ContainsKey(K key)
         [Pure]
-        [SecurityCritical]
         internal bool ContainsKey<K, V>(K key)
         {
             if (key == null)
@@ -86,7 +82,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Add(K key, V value)
-        [SecurityCritical]
         internal void Add<K, V>(K key, V value)
         {
             if (key == null)
@@ -102,7 +97,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool Remove(TKey key)
-        [SecurityCritical]
         internal bool Remove<K, V>(K key)
         {
             if (key == null)
@@ -128,7 +122,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool TryGetValue(TKey key, out TValue value)
-        [SecurityCritical]
         internal bool TryGetValue<K, V>(K key, out V value)
         {
             if (key == null)
index 58427fb..a3715da 100644 (file)
@@ -8,6 +8,7 @@ using System;
 using System.Security;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -29,12 +30,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private MapViewToReadOnlyCollectionAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // int Count { get }
         [Pure]
-        [SecurityCritical]
         internal int Count<K, V>()
         {
             object _this = JitHelpers.UnsafeCast<object>(this);
index b8cd65e..4380369 100644 (file)
@@ -22,30 +22,25 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     internal static class UnsafeNativeMethods
     {
         [DllImport("api-ms-win-core-winrt-error-l1-1-1.dll", PreserveSig = false)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         internal static extern IRestrictedErrorInfo GetRestrictedErrorInfo();
 
         [DllImport("api-ms-win-core-winrt-error-l1-1-1.dll")]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         internal static extern bool RoOriginateLanguageException(int error, [MarshalAs(UnmanagedType.HString)]string message, IntPtr languageException);
 
         [DllImport("api-ms-win-core-winrt-error-l1-1-1.dll", PreserveSig = false)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         internal static extern void RoReportUnhandledError(IRestrictedErrorInfo error);
 
         [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         internal static unsafe extern int WindowsCreateString([MarshalAs(UnmanagedType.LPWStr)] string sourceString,
                                                               int length,
                                                               [Out] IntPtr *hstring);
 
         [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         internal static unsafe extern int WindowsCreateStringReference(char *sourceString,
                                                                        int length,
@@ -53,12 +48,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                                                                        [Out] IntPtr *hstring);
 
         [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         internal static extern int WindowsDeleteString(IntPtr hstring);
 
         [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         internal static unsafe extern char* WindowsGetStringRawBuffer(IntPtr hstring, [Out] uint *length);
     }
index 5dd7d00..cd3c53a 100644 (file)
@@ -57,15 +57,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
         //
         // Support for ToString/GetHashCode/Equals override
         //        
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.InternalCall)]            
         internal extern IntPtr GetRedirectedGetHashCodeMD();        
         
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.InternalCall)]            
         internal extern int RedirectGetHashCode(IntPtr pMD);        
 
-        [System.Security.SecuritySafeCritical]
         public override int GetHashCode()
         {
             IntPtr pMD = GetRedirectedGetHashCodeMD();
@@ -74,15 +71,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
             return RedirectGetHashCode(pMD);
         }
 
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.InternalCall)]            
         internal extern IntPtr GetRedirectedToStringMD();        
 
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.InternalCall)]            
         internal extern string RedirectToString(IntPtr pMD);
 
-        [System.Security.SecuritySafeCritical]
         public override string ToString()
         {
             // Check whether the type implements IStringable.
@@ -102,15 +96,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
             }
         }
 
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.InternalCall)]            
         internal extern IntPtr GetRedirectedEqualsMD();        
 
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.InternalCall)]            
         internal extern bool RedirectEquals(object obj, IntPtr pMD);        
 
-        [System.Security.SecuritySafeCritical]
         public override bool Equals(object obj)
         {
             IntPtr pMD = GetRedirectedEqualsMD();
index ba29eae..898f1a6 100644 (file)
@@ -8,6 +8,7 @@ using System;
 using System.Security;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -26,12 +27,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private VectorToCollectionAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // int Count { get }
         [Pure]
-        [SecurityCritical]
         internal int Count<T>()
         {
             IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
@@ -45,14 +45,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool IsReadOnly { get }
-        [SecurityCritical]
         internal bool IsReadOnly<T>()
         {
             return false;
         }
 
         // void Add(T item)
-        [SecurityCritical]
         internal void Add<T>(T item)
         {
             IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
@@ -60,7 +58,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Clear()
-        [SecurityCritical]
         internal void Clear<T>()
         {
             IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
@@ -68,7 +65,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool Contains(T item)
-        [SecurityCritical]
         internal bool Contains<T>(T item)
         {
             IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
@@ -78,7 +74,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void CopyTo(T[] array, int arrayIndex)
-        [SecurityCritical]
         internal void CopyTo<T>(T[] array, int arrayIndex)
         {
             if (array == null)
@@ -104,7 +99,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // bool Remove(T item)
-        [SecurityCritical]
         internal bool Remove<T>(T item)
         {
             IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
index feefe4e..3e33248 100644 (file)
@@ -8,6 +8,7 @@ using System;
 using System.Security;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -26,11 +27,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private VectorToListAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // T this[int index] { get }
-        [SecurityCritical]
         internal T Indexer_Get<T>(int index)
         {
             if (index < 0)
@@ -41,7 +41,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // T this[int index] { set }
-        [SecurityCritical]
         internal void Indexer_Set<T>(int index, T value)
         {
             if (index < 0)
@@ -52,7 +51,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // int IndexOf(T item)
-        [SecurityCritical]
         internal int IndexOf<T>(T item)
         {
             IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
@@ -72,7 +70,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void Insert(int index, T item)
-        [SecurityCritical]
         internal void Insert<T>(int index, T item)
         {
             if (index < 0)
@@ -83,7 +80,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         }
 
         // void RemoveAt(int index)
-        [SecurityCritical]
         internal void RemoveAt<T>(int index)
         {
             if (index < 0)
index 4b4ae5d..6b7785d 100644 (file)
@@ -8,6 +8,7 @@ using System;
 using System.Security;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
@@ -26,12 +27,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private VectorViewToReadOnlyCollectionAdapter()
         {
-            Contract.Assert(false, "This class is never instantiated");
+            Debug.Assert(false, "This class is never instantiated");
         }
 
         // int Count { get }
         [Pure]
-        [SecurityCritical]
         internal int Count<T>()
         {
             IVectorView<T> _this = JitHelpers.UnsafeCast<IVectorView<T>>(this);
index 0d59895..a786880 100644 (file)
@@ -19,7 +19,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
 internal static class WindowsRuntimeBufferHelper {
 
 
-    [SecurityCritical]
     [DllImport(JitHelpers.QCall)]
     [SuppressUnmanagedCodeSecurity]
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
@@ -27,7 +26,6 @@ internal static class WindowsRuntimeBufferHelper {
 
 
     [FriendAccessAllowed]
-    [SecurityCritical]
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     internal unsafe static void StoreOverlappedInCCW(Object windowsRuntimeBuffer, NativeOverlapped* overlapped) {
 
index 5b04329..a7ad491 100644 (file)
@@ -6,6 +6,7 @@
 
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Reflection;
 using System.Runtime.CompilerServices;
@@ -23,7 +24,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         // delegate.  It then stores the corresponding token in a dictionary for easy access by RemoveEventHandler
         // later.  Note that the dictionary is indexed by the remove method that will be used for RemoveEventHandler
         // so the removeMethod given here must match the remove method supplied there exactly.
-        [SecurityCritical]
         public static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod,
                                               Action<EventRegistrationToken> removeMethod,
                                               T handler)
@@ -54,7 +54,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // Remove the delegate handler from the Windows Runtime style event registration by looking for
         // its token, previously stored via AddEventHandler<T>
-        [SecurityCritical]
         public static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler)
         {
             if (removeMethod == null)
@@ -79,7 +78,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 ManagedEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler);            
         }
         
-        [SecurityCritical]
         public static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
         {
             if (removeMethod == null)
@@ -220,7 +218,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>> s_eventRegistrations = 
                     new ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>>();
     
-            [SecurityCritical]
             internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod,
                                                   Action<EventRegistrationToken> removeMethod,
                                                   T handler)
@@ -280,7 +277,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 }
             }
 
-            [SecurityCritical]
             internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler)
             {
                 Contract.Requires(removeMethod != null);
@@ -322,7 +318,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instance + ", handler = " + handler + ", token = " + token.m_value + "\n");                
             }
 
-            [SecurityCritical]
             internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
             {
                 Contract.Requires(removeMethod != null);                                        
@@ -538,11 +533,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             private volatile static MyReaderWriterLock s_eventCacheRWLock = new MyReaderWriterLock();
 
             // Get InstanceKey to use in the cache
-            [SecuritySafeCritical]
             private static object GetInstanceKey(Action<EventRegistrationToken> removeMethod)
             {
                 object target = removeMethod.Target;
-                Contract.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW");
+                Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW");
                 if (target == null)
                     return removeMethod.Method.DeclaringType;
                 
@@ -550,7 +544,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 return (object) Marshal.GetRawIUnknownForComObjectNoAddRef(target);
             }
             
-            [SecurityCritical]
             internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod,
                                                   Action<EventRegistrationToken> removeMethod,
                                                   T handler)
@@ -685,7 +678,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 }
             }
 
-            [SecurityCritical]
             internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler)
             {
                 object instanceKey = GetInstanceKey(removeMethod);
@@ -721,7 +713,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                         // Note that inside TryGetValueWithValueEquality we assumes that any delegate 
                         // with the same value equality would have the same hash code
                         object key = registrationTokens.FindEquivalentKeyUnsafe(handler, out tokens);
-                        Contract.Assert((key != null && tokens != null) || (key == null && tokens == null), 
+                        Debug.Assert((key != null && tokens != null) || (key == null && tokens == null), 
                                         "key and tokens must be both null or non-null");
                         if (tokens == null)
                         {
@@ -762,7 +754,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 removeMethod(token);            
             }
 
-            [SecurityCritical]
             internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
             {
                 object instanceKey = GetInstanceKey(removeMethod);
@@ -908,7 +899,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 internal void ReleaseReaderLock()
                 {
                     EnterMyLock();
-                    Contract.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
+                    Debug.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
                     --owners;
                     ExitAndWakeUpAppropriateWaiters();
                 }
@@ -916,7 +907,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 internal void ReleaseWriterLock()
                 {
                     EnterMyLock();
-                    Contract.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held");
+                    Debug.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held");
                     owners++;
                     ExitAndWakeUpAppropriateWaiters();
                 }
@@ -928,8 +919,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 /// set 'waitEvent' 
                 /// </summary>
                 private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) {
-                    Contract.Assert(myLock != 0, "Lock must be held");
-                    Contract.Assert(waitEvent == null, "Wait event must be null");
+                    Debug.Assert(myLock != 0, "Lock must be held");
+                    Debug.Assert(waitEvent == null, "Wait event must be null");
 
                     ExitMyLock();
                     EventWaitHandle newEvent;
@@ -948,7 +939,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 /// </summary>
                 private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
                 {
-                    Contract.Assert(myLock != 0, "Lock must be held");
+                    Debug.Assert(myLock != 0, "Lock must be held");
 
                     waitEvent.Reset();
                     numWaiters++;
@@ -976,7 +967,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 /// </summary>
                 private void ExitAndWakeUpAppropriateWaiters()
                 {
-                    Contract.Assert(myLock != 0, "Lock must be held");
+                    Debug.Assert(myLock != 0, "Lock must be held");
 
                     if (owners == 0 && numWriteWaiters > 0)
                     {
@@ -1012,7 +1003,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 }
                 private void ExitMyLock()
                 {
-                    Contract.Assert(myLock != 0, "Exiting spin lock that is not held");
+                    Debug.Assert(myLock != 0, "Exiting spin lock that is not held");
                     myLock = 0;
                 }
             };            
@@ -1044,7 +1035,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 throw new AggregateException(exceptions.ToArray());
         }
         
-        [SecurityCritical]
         internal static unsafe string HStringToString(IntPtr hstring)
         {
             Contract.Requires(Environment.IsWinRTSupported);
@@ -1092,7 +1082,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         private static bool s_haveBlueErrorApis = true;
 
-        [SecurityCritical]
         private static bool RoOriginateLanguageException(int error, string message, IntPtr languageException)
         {
             if (s_haveBlueErrorApis)
@@ -1110,7 +1099,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             return false;
         }
 
-        [SecurityCritical]
         private static void RoReportUnhandledError(IRestrictedErrorInfo error)
         {
             if (s_haveBlueErrorApis)
@@ -1134,7 +1122,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         /// </summary>
         /// <returns>true if the error was reported, false if not (ie running on Win8)</returns>
         [FriendAccessAllowed]
-        [SecuritySafeCritical]
         internal static bool ReportUnhandledError(Exception e)
         {
             // Only report to the WinRT global exception handler in modern apps
@@ -1200,14 +1187,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
 #if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
         // Get an IActivationFactory * for a managed type
-        [SecurityCritical]
         internal static IntPtr GetActivationFactoryForType(Type type)
         {
             ManagedActivationFactory activationFactory = GetManagedActivationFactory(type); 
             return Marshal.GetComInterfaceForObject(activationFactory, typeof(IActivationFactory));
         }        
 
-        [SecurityCritical]
         internal static ManagedActivationFactory GetManagedActivationFactory(Type type)
         {
             ManagedActivationFactory activationFactory = new ManagedActivationFactory(type);
@@ -1224,7 +1209,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         // holds the IWinRTClassActivator* that is used for the process
         private static IntPtr s_pClassActivator = IntPtr.Zero;
 
-        [SecurityCritical]
         internal static IntPtr GetClassActivatorForApplication(string appBase)
         {
             if (s_pClassActivator == IntPtr.Zero)
@@ -1268,7 +1252,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         // factories from other apartments and make transiton to those apartments and cause
         // deadlocks and create objects in incorrect apartments
         //
-        [SecurityCritical]
         public static IActivationFactory GetActivationFactory(Type type)
         {
             if (type == null)
@@ -1291,7 +1274,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // HSTRING marshaling methods:
 
-        [SecurityCritical]
         public static IntPtr StringToHString(String s)
         {
             if (!Environment.IsWinRTSupported)
@@ -1309,7 +1291,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             }
         }
 
-        [SecurityCritical]
         public static String PtrToStringHString(IntPtr ptr)
         {
             if (!Environment.IsWinRTSupported)
@@ -1320,7 +1301,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             return HStringToString(ptr);
         }
 
-        [SecurityCritical]
         public static void FreeHString(IntPtr ptr)
         {
             if (!Environment.IsWinRTSupported)
index 642c4b2..9ca959c 100644 (file)
@@ -19,14 +19,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     public static class WindowsRuntimeMetadata
     {
         // Wrapper for Win8 API RoResolveNamespace with default Windows SDK path as installed .winmd files in %WINDIR%\system32\WinMetadata.
-        [System.Security.SecurityCritical]
         public static IEnumerable<string> ResolveNamespace(string namespaceName, IEnumerable<string> packageGraphFilePaths)
         {
             return ResolveNamespace(namespaceName, null, packageGraphFilePaths);
         }
 
         // Wrapper for Win8 API RoResolveNamespace.
-        [System.Security.SecurityCritical]
         public static IEnumerable<string> ResolveNamespace(string namespaceName, string windowsSdkFilePath, IEnumerable<string> packageGraphFilePaths)
         {
             if (namespaceName == null)
@@ -58,7 +56,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             return retFileNames;
         }
         
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void nResolveNamespace(
index 37ac309..e158a5a 100644 (file)
@@ -17,7 +17,6 @@ using System.Threading;
 
 namespace System.Runtime.Loader
 {
-    [System.Security.SecuritySafeCritical]
     public abstract class AssemblyLoadContext
     {
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -62,7 +61,6 @@ namespace System.Runtime.Loader
             InitializeLoadContext(fRepresentsTPALoadContext);
         }
         
-        [System.Security.SecuritySafeCritical]
         void InitializeLoadContext(bool fRepresentsTPALoadContext)
         {
             // Initialize the VM side of AssemblyLoadContext if not already done.
@@ -501,14 +499,12 @@ namespace System.Runtime.Loader
         }
     }
 
-    [System.Security.SecuritySafeCritical]
     class AppPathAssemblyLoadContext : AssemblyLoadContext
     {
         internal AppPathAssemblyLoadContext() : base(true)
         {
         }
 
-        [System.Security.SecuritySafeCritical]  
         protected override Assembly Load(AssemblyName assemblyName)
         {
             // We were loading an assembly into TPA ALC that was not found on TPA list. As a result we are here.
@@ -517,14 +513,12 @@ namespace System.Runtime.Loader
         }
     }
 
-    [System.Security.SecuritySafeCritical]
     internal class IndividualAssemblyLoadContext : AssemblyLoadContext
     {
         internal IndividualAssemblyLoadContext() : base(false)
         {
         }
 
-        [System.Security.SecuritySafeCritical]  
         protected override Assembly Load(AssemblyName assemblyName)
         {
             return null;
index c22ce65..bd87d90 100644 (file)
@@ -22,6 +22,7 @@ using System.Runtime.CompilerServices;
 using System.Runtime.ConstrainedExecution;
 using System.Security.Permissions;
 using System.Runtime.Versioning;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 /* 
@@ -143,7 +144,6 @@ namespace System.Runtime
         private ulong _reservedMemory;  // The size of this request (from user)
         private bool _mustSubtractReservation; // Did we add data to SharedStatics?
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static MemoryFailPoint()
         {
             GetMemorySettings(out GCSegmentSize, out TopOfMemory);
@@ -153,7 +153,6 @@ namespace System.Runtime
         // have scenarios for this in partial trust in the future, but
         // we're doing this just to restrict this in case the code below
         // is somehow incorrect.
-        [System.Security.SecurityCritical]  // auto-generated_required
         public MemoryFailPoint(int sizeInMegabytes)
         {
             if (sizeInMegabytes <= 0)
@@ -284,7 +283,7 @@ namespace System.Runtime
                     break;
 
                 default:
-                    Contract.Assert(false, "Fell through switch statement!");
+                    Debug.Assert(false, "Fell through switch statement!");
                     break;
                 }
             }
@@ -306,7 +305,6 @@ namespace System.Runtime
 #endif
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree)
         {
             bool r;
@@ -323,7 +321,6 @@ namespace System.Runtime
         // returns whether there is enough space.  In all cases, we update
         // our last known free address space, hopefully avoiding needing to 
         // probe again.
-        [System.Security.SecurityCritical]  // auto-generated
         private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow)
         {
             // Start walking the address space at 0.  VirtualAlloc may wrap
@@ -350,7 +347,6 @@ namespace System.Runtime
         // of pages.  If we didn't have enough address space, we still return 
         // a positive value < size, to help potentially avoid the overhead of 
         // this check if we use a MemoryFailPoint with a smaller size next.
-        [System.Security.SecurityCritical]  // auto-generated
         private static unsafe ulong MemFreeAfterAddress(void * address, ulong size)
         {
             if (size >= TopOfMemory)
@@ -377,11 +373,9 @@ namespace System.Runtime
             return largestFreeRegion;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory);
 
-        [System.Security.SecuritySafeCritical] // destructors should be safe to call
         ~MemoryFailPoint()
         {
             Dispose(false);
@@ -394,14 +388,12 @@ namespace System.Runtime
         // future create an allocation context and release it in the Dispose
         // method.  While the finalizer will eventually free this block of 
         // memory, apps will help their performance greatly by calling Dispose.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void Dispose()
         {
             Dispose(true);
             GC.SuppressFinalize(this);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private void Dispose(bool disposing)
         {
index c877d21..1e42308 100644 (file)
@@ -27,22 +27,18 @@ namespace System.Runtime {
     public static class ProfileOptimization
     {
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         internal static extern void InternalSetProfileRoot(string directoryPath);
 
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
 
-        [SecurityCritical]
         public static void SetProfileRoot(string directoryPath)
         {
             InternalSetProfileRoot(directoryPath);
         }
 
-        [SecurityCritical]
         public static void StartProfile(string profile)
         {
             InternalStartProfile(profile, IntPtr.Zero);
index 2524aaa..eb5a186 100644 (file)
@@ -22,15 +22,9 @@ using System.Runtime.InteropServices;
 
 namespace System.Runtime.ConstrainedExecution
 {
-#if !FEATURE_CORECLR
-    [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
     [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class CriticalFinalizerObject
     {
-        #if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-        #endif
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         protected CriticalFinalizerObject()
         {
index d10df9d..5555670 100644 (file)
 ** 
 ===========================================================*/
 
-namespace System.Runtime.Remoting{
-
+namespace System.Runtime.Remoting
+{
     using System;
-    using System.Security.Permissions;
     using System.Runtime.InteropServices;
-    using System.Runtime.Remoting;
-#if FEATURE_REMOTING
-    using System.Runtime.Remoting.Activation;
-    using System.Runtime.Remoting.Lifetime;
-#endif
 
     [ClassInterface(ClassInterfaceType.AutoDual)]
     [System.Runtime.InteropServices.ComVisible(true)]
     public class ObjectHandle: 
-#if FEATURE_REMOTING
-        MarshalByRefObject, 
-#endif
         IObjectHandle 
     {
         private Object WrappedObject;
@@ -48,34 +39,5 @@ namespace System.Runtime.Remoting{
         {
             return WrappedObject;
         }
-
-        // ObjectHandle has a finite lifetime. For now the default
-        // lifetime is being used, this can be changed in this method to
-        // specify a custom lifetime.
-#if FEATURE_REMOTING
-        [System.Security.SecurityCritical]  // auto-generated_required
-        public override Object InitializeLifetimeService()
-        {
-            BCLDebug.Trace("REMOTE", "ObjectHandle.InitializeLifetimeService");
-
-            //
-            // If the wrapped object has implemented InitializeLifetimeService to return null,
-            // we don't want to go to the base class (which will result in a lease being
-            // requested from the MarshalByRefObject, which starts up the LeaseManager,
-            // which starts up the ThreadPool, adding three threads to the process.
-            // We check if the wrapped object is a MarshalByRef object, and call InitializeLifetimeServices on it
-            // and if it returns null, we return null. Otherwise we fall back to the old behavior.
-            //
-
-            MarshalByRefObject mbr = WrappedObject as MarshalByRefObject;
-            if (mbr != null) {
-                Object o = mbr.InitializeLifetimeService();
-                if (o == null)
-                    return null;
-            }
-            ILease lease = (ILease)base.InitializeLifetimeService();
-            return lease;
-        }
-#endif // FEATURE_REMOTING
     }
 }
index 82fb362..27c3f15 100644 (file)
@@ -29,16 +29,15 @@ namespace System.Runtime.Serialization {
     using System.IO;
     using System.Text;
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [System.Runtime.InteropServices.ComVisible(true)]
     public static class FormatterServices {
 #if FEATURE_SERIALIZATION
         internal static Dictionary<MemberHolder, MemberInfo[]> m_MemberInfoTable = new Dictionary<MemberHolder, MemberInfo[]>(32);
-        [System.Security.SecurityCritical]
         private static bool unsafeTypeForwardersIsEnabled = false;
 
-        [System.Security.SecurityCritical]
         private static volatile bool unsafeTypeForwardersIsEnabledInitialized = false;
 
         private static Object s_FormatterServicesSyncObject = null;
@@ -56,7 +55,6 @@ namespace System.Runtime.Serialization {
             }
         }
 
-        [SecuritySafeCritical]
         static FormatterServices()
         {
             // Static initialization touches security critical types, so we need an
@@ -100,7 +98,7 @@ namespace System.Runtime.Serialization {
             FieldInfo [] typeFields;
             RuntimeType parentType;
 
-            Contract.Assert((object)type != null, "[GetAllSerializableMembers]type!=null");
+            Debug.Assert((object)type != null, "[GetAllSerializableMembers]type!=null");
 
             if (type.IsInterface) {
                 return new MemberInfo[0];
@@ -186,7 +184,6 @@ namespace System.Runtime.Serialization {
         // be included, properties must have both a getter and a setter.  N.B.: A class
         // which implements ISerializable or has a serialization surrogate may not use all of these members
         // (or may have additional members).
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static MemberInfo[] GetSerializableMembers(Type type) {
             return GetSerializableMembers(type, new StreamingContext(StreamingContextStates.All));
         }
@@ -194,7 +191,6 @@ namespace System.Runtime.Serialization {
         // Get all of the Serializable Members for a particular class.  If we're not cloning, this is all
         // non-transient, non-static fields.  If we are cloning, include the transient fields as well since
         // we know that we're going to live inside of the same context.
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static MemberInfo[] GetSerializableMembers(Type type, StreamingContext context) {
             MemberInfo[] members;
     
@@ -230,14 +226,9 @@ namespace System.Runtime.Serialization {
       
         static readonly Type[] advancedTypes = new Type[]{
             typeof(System.DelegateSerializationHolder),
-#if FEATURE_REMOTING
-            typeof(System.Runtime.Remoting.ObjRef),
-            typeof(System.Runtime.Remoting.IEnvoyInfo),
-            typeof(System.Runtime.Remoting.Lifetime.ISponsor),
-#endif
         };
-  
-        public static void CheckTypeSecurity(Type t,  TypeFilterLevel securityLevel) {            
+
+        public static void CheckTypeSecurity(Type t,  TypeFilterLevel securityLevel) {
             if (securityLevel == TypeFilterLevel.Low){
                 for(int i=0;i<advancedTypes.Length;i++){
                     if (advancedTypes[i].IsAssignableFrom(t))
@@ -254,7 +245,6 @@ namespace System.Runtime.Serialization {
         // will not create an unitialized string because it is non-sensical to create an empty
         // instance of an immutable type.
         //
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Object GetUninitializedObject(Type type) {
             if ((object)type == null) {
                 throw new ArgumentNullException(nameof(type));
@@ -268,44 +258,33 @@ namespace System.Runtime.Serialization {
             return nativeGetUninitializedObject((RuntimeType)type);
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Object GetSafeUninitializedObject(Type type) {
              if ((object)type == null) {
                 throw new ArgumentNullException(nameof(type));
             }
              Contract.EndContractBlock();
-    
+
             if (!(type is RuntimeType)) {
                 throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
             }
-#if FEATURE_REMOTING
-            if (Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.ConstructionCall)) || 
-                Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.LogicalCallContext)) ||
-                Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Contexts.SynchronizationAttribute)))
-                 return nativeGetUninitializedObject((RuntimeType)type);                                    
-#endif
 
-            try {                            
-                return nativeGetSafeUninitializedObject((RuntimeType)type);                    
+            try {
+                return nativeGetSafeUninitializedObject((RuntimeType)type);
             }
-            catch(SecurityException e) {                
+            catch(SecurityException e) {
                 throw new SerializationException(Environment.GetResourceString("Serialization_Security",  type.FullName), e);
-            }                                        
+            }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern Object nativeGetSafeUninitializedObject(RuntimeType type);
     
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern Object nativeGetUninitializedObject(RuntimeType type);
 #if FEATURE_SERIALIZATION
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool GetEnableUnsafeTypeForwarders();
 
-        [SecuritySafeCritical]
         internal static bool UnsafeTypeForwardersIsEnabled()
         {
             if (!unsafeTypeForwardersIsEnabledInitialized)
@@ -318,7 +297,6 @@ namespace System.Runtime.Serialization {
         }
 #endif
         private static Binder s_binder = Type.DefaultBinder;
-        [System.Security.SecurityCritical]
         internal static void SerializationSetValue(MemberInfo fi, Object target, Object value)
         {
             Contract.Requires(fi != null);
@@ -345,7 +323,6 @@ namespace System.Runtime.Serialization {
         // Fill in the members of obj with the data contained in data.
         // Returns the number of members populated.
         //
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Object PopulateObjectMembers(Object obj, MemberInfo[] members, Object[] data) {
             if (obj==null) {
                 throw new ArgumentNullException(nameof(obj));
@@ -400,7 +377,6 @@ namespace System.Runtime.Serialization {
         // extract (must be FieldInfos or PropertyInfos).  For each supplied member, extract the matching value and
         // return it in a Object[] of the same size.
         //
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Object[] GetObjectData(Object obj, MemberInfo[] members) {
     
             if (obj==null) {
@@ -425,7 +401,7 @@ namespace System.Runtime.Serialization {
                 }
     
                 if (mi.MemberType==MemberTypes.Field) {
-                    Contract.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo,
+                    Debug.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo,
                                     "[FormatterServices.GetObjectData]mi is RuntimeFieldInfo || mi is SerializationFieldInfo.");
 
                     RtFieldInfo rfi = mi as RtFieldInfo;
@@ -443,7 +419,6 @@ namespace System.Runtime.Serialization {
             return data;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [System.Runtime.InteropServices.ComVisible(false)]
         public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
         {
@@ -459,7 +434,6 @@ namespace System.Runtime.Serialization {
         **Arguments:
         **Exceptions:
         ==============================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Type GetTypeFromAssembly(Assembly assem, String name) {
             if (assem==null)
                 throw new ArgumentNullException(nameof(assem));
@@ -570,13 +544,11 @@ namespace System.Runtime.Serialization {
             this.innerSurrogate = innerSurrogate;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated        
         public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
         {
             innerSurrogate.GetObjectData(obj, info, context);
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
         {
             return innerSurrogate.SetObjectData(obj, info, context, selector);
index f1a1bc0..42662a1 100644 (file)
@@ -22,7 +22,6 @@ namespace System.Runtime.Serialization {
     // Interface does not need to be marked with the serializable attribute
 [System.Runtime.InteropServices.ComVisible(true)]
     public interface IObjectReference {
-        [System.Security.SecurityCritical]  // auto-generated_required
         Object GetRealObject(StreamingContext context);
     }
 }
index e59fa65..fc283d4 100644 (file)
@@ -22,7 +22,6 @@ namespace System.Runtime.Serialization {
 
     [System.Runtime.InteropServices.ComVisible(true)]
     public interface ISerializable {
-        [System.Security.SecurityCritical]  // auto-generated_required
         void GetObjectData(SerializationInfo info, StreamingContext context);
     }
 
index 9bb30d9..226bbdc 100644 (file)
@@ -24,13 +24,11 @@ namespace System.Runtime.Serialization {
         // Returns a SerializationInfo completely populated with all of the data needed to reinstantiate the
         // the object at the other end of serialization.  
         //
-        [System.Security.SecurityCritical]  // auto-generated_required
         void GetObjectData(Object obj, SerializationInfo info, StreamingContext context);
     
         // Reinflate the object using all of the information in data.  The information in
         // members is used to find the particular field or property which needs to be set.
         // 
-        [System.Security.SecurityCritical]  // auto-generated_required
         Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector);
     }
 }
index 01b960f..87b7845 100644 (file)
@@ -22,16 +22,13 @@ namespace System.Runtime.Serialization {
         // Interface does not need to be marked with the serializable attribute
         // Specifies the next ISurrogateSelector to be examined for surrogates if the current
         // instance doesn't have a surrogate for the given type and assembly in the given context.
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ChainSelector(ISurrogateSelector selector);
     
         // Returns the appropriate surrogate for the given type in the given context.
-        [System.Security.SecurityCritical]  // auto-generated_required
         ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector);
     
     
         // Return the next surrogate in the chain. Returns null if no more exist.
-        [System.Security.SecurityCritical]  // auto-generated_required
         ISurrogateSelector GetNextSelector();
     }
 }
index 9c89327..585d367 100644 (file)
@@ -153,8 +153,6 @@ namespace System.Runtime.Serialization
     //
     //    3. Serialize the safe serialization object in GetObjectData, and call its CompleteSerialization method:
     //  
-    //       [SecurityCritical]
-    //       void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
     //       {
     //           info.AddValue("m_safeSerializationManager", m_safeSerializationManager, typeof(SafeSerializationManager));
     //           m_safeSerializationManager.CompleteSerialization(this, info, context);
@@ -281,7 +279,6 @@ namespace System.Runtime.Serialization
         {
         }
 
-        [SecurityCritical]
         private SafeSerializationManager(SerializationInfo info, StreamingContext context)
         {
             // We need to determine if we're being called to really deserialize a SafeSerializationManager,
@@ -313,7 +310,6 @@ namespace System.Runtime.Serialization
         // CompleteSerialization is called by the base ISerializable in its GetObjectData method.  It is
         // responsible for gathering up the serialized object state of any delegates that wish to add their
         // own state to the serialized object.
-        [SecurityCritical]
         internal void CompleteSerialization(object serializedObject,
                                             SerializationInfo info,
                                             StreamingContext context)
@@ -360,7 +356,6 @@ namespace System.Runtime.Serialization
             }
         }
 
-        [SecurityCritical]
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             info.AddValue("m_serializedStates", m_serializedStates, typeof(List<IDeserializationCallback>));
@@ -369,7 +364,6 @@ namespace System.Runtime.Serialization
         // GetRealObject intercepts the deserialization process in order to allow deserializing part of the
         // object's inheritance heirarchy using standard ISerializable constructors, and the remaining
         // portion using the saved serialization states.
-        [SecurityCritical]
         object IObjectReference.GetRealObject(StreamingContext context)
         {
             // If we've already deserialized the real object, use that rather than deserializing it again
index 5e7851b..82536ce 100644 (file)
@@ -21,11 +21,9 @@ namespace System.Runtime.Serialization {
     using System;
     using System.Reflection;
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Threading;
-#if FEATURE_REMOTING
-    using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
 
     internal sealed class SerializationFieldInfo : FieldInfo {
 
@@ -38,8 +36,8 @@ namespace System.Runtime.Serialization {
         public override int MetadataToken { get { return m_field.MetadataToken; } } 
 
         internal SerializationFieldInfo(RuntimeFieldInfo field, String namePrefix) {
-            Contract.Assert(field!=null,      "[SerializationFieldInfo.ctor]field!=null");
-            Contract.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null");
+            Debug.Assert(field!=null,      "[SerializationFieldInfo.ctor]field!=null");
+            Debug.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null");
             
             m_field = field;
             m_serializationName = String.Concat(namePrefix, FakeNameSeparatorString, m_field.Name);
@@ -91,7 +89,6 @@ namespace System.Runtime.Serialization {
             return m_field.GetValue(obj);
         }
 
-        [System.Security.SecurityCritical]
         internal Object InternalGetValue(Object obj) {
             RtFieldInfo field = m_field as RtFieldInfo;
             if (field != null)
@@ -107,7 +104,6 @@ namespace System.Runtime.Serialization {
             m_field.SetValue(obj, value, invokeAttr, binder, culture);
         }
 
-        [System.Security.SecurityCritical]
         internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) {
             RtFieldInfo field = m_field as RtFieldInfo;
             if (field != null)
@@ -136,31 +132,5 @@ namespace System.Runtime.Serialization {
                 return m_field.Attributes;
             }
         }
-
-#if FEATURE_REMOTING
-        #region Legacy Remoting Cache
-        private RemotingFieldCachedData m_cachedData;
-
-        internal RemotingFieldCachedData RemotingCache
-        {
-            get
-            {
-                // This grabs an internal copy of m_cachedData and uses
-                // that instead of looking at m_cachedData directly because
-                // the cache may get cleared asynchronously.  This prevents
-                // us from having to take a lock.
-                RemotingFieldCachedData cache = m_cachedData;
-                if (cache == null)
-                {
-                    cache = new RemotingFieldCachedData(this);
-                    RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
-                    if (ret != null)
-                        cache = ret;
-                }
-                return cache;
-            }
-        }
-        #endregion
-#endif //FEATURE_REMOTING
     }
 }
index 64a7fca..55909c8 100644 (file)
@@ -18,15 +18,11 @@ namespace System.Runtime.Serialization
     using System.Collections.Generic;
     using System.Reflection;
     using System.Runtime.Remoting;
-#if FEATURE_REMOTING
-    using System.Runtime.Remoting.Proxies;
-#endif
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Security;
-#if FEATURE_CORECLR
     using System.Runtime.CompilerServices;
-#endif 
 
     [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class SerializationInfo
@@ -111,7 +107,6 @@ namespace System.Runtime.Serialization
             {
                 return m_assemName;
             }
-            [SecuritySafeCritical]
             set
             {
                 if (null == value)
@@ -128,7 +123,6 @@ namespace System.Runtime.Serialization
             }
         }
 
-        [SecuritySafeCritical]
         public void SetType(Type type)
         {
             if ((object)type == null)
@@ -170,15 +164,8 @@ namespace System.Runtime.Serialization
             }
         }
 
-        [SecuritySafeCritical]
         internal static void DemandForUnsafeAssemblyNameAssignments(string originalAssemblyName, string newAssemblyName)
         {
-#if !FEATURE_CORECLR
-            if (!IsAssemblyNameAssignmentSafe(originalAssemblyName, newAssemblyName))
-            {
-                CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
-            }
-#endif
         }
 
         internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName)
@@ -242,7 +229,7 @@ namespace System.Runtime.Serialization
         private void ExpandArrays()
         {
             int newSize;
-            Contract.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
+            Debug.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
 
             newSize = (m_currMember * 2);
 
@@ -416,19 +403,14 @@ namespace System.Runtime.Serialization
         **Exceptions: None.  All error checking is done with asserts. Although public in coreclr,
         **            it's not exposed in a contract and is only meant to be used by corefx.
         ==============================================================================*/
-#if FEATURE_CORECLR
         // This should not be used by clients: exposing out this functionality would allow children
         // to overwrite their parent's values. It is public in order to give corefx access to it for
         // its ObjectManager implementation, but it should not be exposed out of a contract.
-        public
-#else
-        internal
-#endif
-        void UpdateValue(String name, Object value, Type type)
+        public void UpdateValue(String name, Object value, Type type)
         {
-            Contract.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
-            Contract.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
-            Contract.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
+            Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
+            Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
+            Debug.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
 
             int index = FindElement(name);
             if (index < 0)
@@ -477,11 +459,11 @@ namespace System.Runtime.Serialization
                 throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name));
             }
 
-            Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
-            Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
+            Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
+            Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
 
             foundType = m_types[index];
-            Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
+            Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
             return m_data[index];
         }
 
@@ -495,11 +477,11 @@ namespace System.Runtime.Serialization
                 return null;
             }
 
-            Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
-            Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
+            Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
+            Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
 
             foundType = m_types[index];
-            Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
+            Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
             return m_data[index];
         }
 
@@ -508,7 +490,6 @@ namespace System.Runtime.Serialization
         // form requested.  
         //
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Object GetValue(String name, Type type)
         {
 
@@ -526,53 +507,36 @@ namespace System.Runtime.Serialization
             Object value;
 
             value = GetElement(name, out foundType);
-#if FEATURE_REMOTING
-            if (RemotingServices.IsTransparentProxy(value))
+
+            if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
             {
-                RealProxy proxy = RemotingServices.GetRealProxy(value);
-                if (RemotingServices.ProxyCheckCast(proxy, rt))
-                    return value;
+                return value;
             }
-            else
-#endif
-                if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
-                {
-                    return value;
-                }
 
-            Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
+            Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
 
             return m_converter.Convert(value, type);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.InteropServices.ComVisible(true)]
         internal Object GetValueNoThrow(String name, Type type)
         {
             Type foundType;
             Object value;
 
-            Contract.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
-            Contract.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
+            Debug.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
+            Debug.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
 
             value = GetElementNoThrow(name, out foundType);
             if (value == null)
                 return null;
-#if FEATURE_REMOTING
-            if (RemotingServices.IsTransparentProxy(value))
+
+            if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
             {
-                RealProxy proxy = RemotingServices.GetRealProxy(value);
-                if (RemotingServices.ProxyCheckCast(proxy, (RuntimeType)type))
-                    return value;
+                return value;
             }
-            else
-#endif
-                if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
-                {
-                    return value;
-                }
 
-            Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
+            Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
 
             return m_converter.Convert(value, type);
         }
index 6b256a6..32c6549 100644 (file)
@@ -14,6 +14,7 @@
 ============================================================*/
 namespace System.Runtime.Serialization {
     using System;
+    using System.Diagnostics;
     using System.Collections;
     using System.Diagnostics.Contracts;
 
@@ -66,13 +67,13 @@ namespace System.Runtime.Serialization {
         bool     m_current;
 
         internal SerializationInfoEnumerator(String[] members, Object[] info, Type[] types, int numItems) {
-            Contract.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null");
-            Contract.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null");
-            Contract.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null");
-            Contract.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0");
-            Contract.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems");
-            Contract.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems");
-            Contract.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems");
+            Debug.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null");
+            Debug.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null");
+            Debug.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null");
+            Debug.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0");
+            Debug.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems");
+            Debug.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems");
+            Debug.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems");
 
             m_members = members;
             m_data = info;
index b06c424..6bf8f8c 100644 (file)
@@ -21,13 +21,11 @@ namespace System.Runtime.Versioning
                 *                        
                 *     These apis are for internal use only for FX assmeblies. It has not been decided if they can be used by OOB components due to EULA restrictions
                 */
-        [System.Security.SecurityCritical]
         public static bool IsEnabled(string compatibilitySwitchName)
         {
             return IsEnabledInternalCall(compatibilitySwitchName, true);
         }
 
-        [System.Security.SecurityCritical]
         public static string GetValue(string compatibilitySwitchName)
         {
             // This is used by AppContext.TryGetSwitch to check switch overrides in the Windows Quirk DB
@@ -36,19 +34,16 @@ namespace System.Runtime.Versioning
             return GetValueInternalCall(compatibilitySwitchName, true);
         }
 
-        [System.Security.SecurityCritical]
         internal static bool IsEnabledInternal(string compatibilitySwitchName)
         {
             return IsEnabledInternalCall(compatibilitySwitchName, false);
         }
 
-        [System.Security.SecurityCritical]
         internal static string GetValueInternal(string compatibilitySwitchName)
         {
             return GetValueInternalCall(compatibilitySwitchName, false);
         }
 
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.InternalCall)]
         internal static extern string GetAppContextOverridesInternalCall();
 
index 4aa4af4..127da1e 100644 (file)
@@ -48,11 +48,9 @@ namespace System
             return type;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsInstanceOfType(RuntimeType type, Object o);
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers)
         {
             Type type = typeStart;
@@ -127,14 +125,12 @@ namespace System
 
         public IntPtr Value
         {
-            [SecurityCritical]
             get
             {
                 return m_type != null ? m_type.m_handle : IntPtr.Zero;
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         internal static extern IntPtr GetValueInternal(RuntimeTypeHandle handle);
 
@@ -148,7 +144,6 @@ namespace System
             return m_type == null; 
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsPrimitive(RuntimeType type)
         {
             CorElementType corElemType = GetCorElementType(type);
@@ -157,35 +152,30 @@ namespace System
                     corElemType == CorElementType.U;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsByRef(RuntimeType type)
         {
             CorElementType corElemType = GetCorElementType(type);
             return (corElemType == CorElementType.ByRef);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsPointer(RuntimeType type)
         {
             CorElementType corElemType = GetCorElementType(type);
             return (corElemType == CorElementType.Ptr);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsArray(RuntimeType type)
         {
             CorElementType corElemType = GetCorElementType(type);
             return (corElemType == CorElementType.Array || corElemType == CorElementType.SzArray);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsSzArray(RuntimeType type)
         {
             CorElementType corElemType = GetCorElementType(type);
             return (corElemType == CorElementType.SzArray);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool HasElementType(RuntimeType type)
         {
             CorElementType corElemType = GetCorElementType(type);
@@ -195,7 +185,6 @@ namespace System
                    || (corElemType == CorElementType.ByRef));                                      // IsByRef
         }
 
-        [SecurityCritical]
         internal static IntPtr[] CopyRuntimeTypeHandles(RuntimeTypeHandle[] inHandles, out int length)
         {
             if (inHandles == null || inHandles.Length == 0)
@@ -213,7 +202,6 @@ namespace System
             return outHandles;
         }
 
-        [SecurityCritical]
         internal static IntPtr[] CopyRuntimeTypeHandles(Type[] inHandles, out int length)
         {
             if (inHandles == null || inHandles.Length == 0)
@@ -231,19 +219,15 @@ namespace System
             return outHandles;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, bool noCheck, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor, ref bool bNeedSecurityCheck);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern Object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern Object Allocate(RuntimeType type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern Object CreateInstanceForAnotherGenericParameter(RuntimeType type, RuntimeType genericParameter);
         
@@ -252,15 +236,12 @@ namespace System
             return m_type;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static CorElementType GetCorElementType(RuntimeType type);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static RuntimeAssembly GetAssembly(RuntimeType type);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal extern static RuntimeModule GetModule(RuntimeType type);
@@ -272,31 +253,24 @@ namespace System
             return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type));
         }
         
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static RuntimeType GetBaseType(RuntimeType type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static TypeAttributes GetAttributes(RuntimeType type); 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static RuntimeType GetElementType(RuntimeType type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool CompareCanonicalHandles(RuntimeType left, RuntimeType right);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static int GetArrayRank(RuntimeType type); 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static int GetToken(RuntimeType type); 
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot);
 
@@ -306,14 +280,12 @@ namespace System
             bool                    _firstCall;
             RuntimeMethodHandleInternal _handle;
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
             internal IntroducedMethodEnumerator(RuntimeType type)
             {
                 _handle = RuntimeTypeHandle.GetFirstIntroducedMethod(type);
                 _firstCall = true;
             }
         
-            [System.Security.SecuritySafeCritical]  // auto-generated
             public bool MoveNext() 
             {
                 if (_firstCall)
@@ -346,28 +318,22 @@ namespace System
             return new IntroducedMethodEnumerator(type);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern RuntimeMethodHandleInternal GetFirstIntroducedMethod(RuntimeType type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool GetFields(RuntimeType type, IntPtr* result, int* count);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static Type[] GetInterfaces(RuntimeType type);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetConstraints(RuntimeTypeHandle handle, ObjectHandleOnStack types);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal Type[] GetConstraints()
         {
             Type[] types = null;
@@ -376,118 +342,96 @@ namespace System
             return types;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static IntPtr GetGCHandle(RuntimeTypeHandle handle, GCHandleType type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal IntPtr GetGCHandle(GCHandleType type)
         {
             return GetGCHandle(GetNativeHandle(), type);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static int GetNumVirtuals(RuntimeType type); 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void VerifyInterfaceIsImplemented(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal void VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
         {
             VerifyInterfaceIsImplemented(GetNativeHandle(), interfaceHandle.GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle)
         {
             return GetInterfaceMethodImplementationSlot(GetNativeHandle(), interfaceHandle.GetNativeHandle(), interfaceMethodHandle);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsComObject(RuntimeType type, bool isGenericCOM); 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsContextful(RuntimeType type); 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsInterface(RuntimeType type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private extern static bool _IsVisible(RuntimeTypeHandle typeHandle);
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsVisible(RuntimeType type)
         {
             return _IsVisible(new RuntimeTypeHandle(type));
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool IsSecurityCritical(RuntimeTypeHandle typeHandle);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsSecurityCritical()
         {
             return IsSecurityCritical(GetNativeHandle());
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool IsSecuritySafeCritical(RuntimeTypeHandle typeHandle);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsSecuritySafeCritical()
         {
             return IsSecuritySafeCritical(GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool IsSecurityTransparent(RuntimeTypeHandle typeHandle);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsSecurityTransparent()
         {
             return IsSecurityTransparent(GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool HasProxyAttribute(RuntimeType type);
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsValueType(RuntimeType type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void ConstructName(RuntimeTypeHandle handle, TypeNameFormatFlags formatFlags, StringHandleOnStack retString);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal string ConstructName(TypeNameFormatFlags formatFlags)
         {
             string name = null;
@@ -495,34 +439,27 @@ namespace System
             return name;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static void* _GetUtf8Name(RuntimeType type);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Utf8String GetUtf8Name(RuntimeType type)
         {
             return new Utf8String(_GetUtf8Name(type));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool CanCastTo(RuntimeType type, RuntimeType target);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static RuntimeType GetDeclaringType(RuntimeType type);
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetDefaultConstructor(RuntimeTypeHandle handle, ObjectHandleOnStack method);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal IRuntimeMethodInfo GetDefaultConstructor()       
         {
             IRuntimeMethodInfo ctor = null;
@@ -530,7 +467,6 @@ namespace System
             return ctor;
         }
        
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, StackCrawlMarkHandle stackMark, 
@@ -543,7 +479,6 @@ namespace System
             return GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly, ref stackMark, IntPtr.Zero, loadTypeFromPartialName);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark,
                                                   IntPtr pPrivHostBinder,
                                                   bool loadTypeFromPartialName)
@@ -573,12 +508,10 @@ namespace System
             return GetTypeByName(name, false, false, false, ref stackMark, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetTypeByNameUsingCARules(string name, RuntimeModule scope, ObjectHandleOnStack type);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope)
         {
             if (name == null || name.Length == 0)
@@ -591,12 +524,10 @@ namespace System
             return type;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal extern static void GetInstantiation(RuntimeTypeHandle type, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal RuntimeType[] GetInstantiationInternal()
         {
             RuntimeType[] types = null;
@@ -604,7 +535,6 @@ namespace System
             return types;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal Type[] GetInstantiationPublic()
         {
             Type[] types = null;
@@ -612,12 +542,10 @@ namespace System
             return types;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal RuntimeType Instantiate(Type[] inst)
         {
             // defensive copy to be sure array is not mutated from the outside during processing
@@ -633,12 +561,10 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void MakeArray(RuntimeTypeHandle handle, int rank, ObjectHandleOnStack type);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal RuntimeType MakeArray(int rank)
         {
             RuntimeType type = null;
@@ -646,12 +572,10 @@ namespace System
             return type;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void MakeSZArray(RuntimeTypeHandle handle, ObjectHandleOnStack type);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal RuntimeType MakeSZArray()
         {
             RuntimeType type = null;
@@ -659,12 +583,10 @@ namespace System
             return type;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void MakeByRef(RuntimeTypeHandle handle, ObjectHandleOnStack type);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal RuntimeType MakeByRef()
         {
             RuntimeType type = null;
@@ -672,12 +594,10 @@ namespace System
             return type;
         }
        
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void MakePointer(RuntimeTypeHandle handle, ObjectHandleOnStack type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal RuntimeType MakePointer()
         {
             RuntimeType type = null;
@@ -685,14 +605,10 @@ namespace System
             return type;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal extern static bool IsCollectible(RuntimeTypeHandle handle);
         
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-#endif
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool HasInstantiation(RuntimeType type);
 
@@ -701,12 +617,10 @@ namespace System
             return HasInstantiation(GetTypeChecked());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetGenericTypeDefinition(RuntimeTypeHandle type, ObjectHandleOnStack retType);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeType GetGenericTypeDefinition(RuntimeType type)
         {
             RuntimeType retType = type;
@@ -717,11 +631,9 @@ namespace System
             return retType;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsGenericTypeDefinition(RuntimeType type);
        
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsGenericVariable(RuntimeType type);
 
@@ -730,11 +642,9 @@ namespace System
             return IsGenericVariable(GetTypeChecked());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static int GetGenericVariableIndex(RuntimeType type);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal int GetGenericVariableIndex()
         {
             RuntimeType type = GetTypeChecked();
@@ -745,21 +655,17 @@ namespace System
             return GetGenericVariableIndex(type);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool ContainsGenericVariables(RuntimeType handle);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool ContainsGenericVariables()
         {
             return ContainsGenericVariables(GetTypeChecked());
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static bool SatisfiesConstraints(RuntimeType paramType, IntPtr *pTypeContext, int typeContextLength, IntPtr *pMethodContext, int methodContextLength, RuntimeType toType);
 
-        [System.Security.SecurityCritical]
         internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType)
         {
             int typeContextLength;
@@ -778,17 +684,14 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static IntPtr _GetMetadataImport(RuntimeType type);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static MetadataImport GetMetadataImport(RuntimeType type)
         {
             return new MetadataImport(_GetMetadataImport(type), type);
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         private RuntimeTypeHandle(SerializationInfo info, StreamingContext context)
         {
             if(info == null) 
@@ -803,7 +706,6 @@ namespace System
                 throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
         }
 
-        [System.Security.SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context) 
         {
             if(info == null) 
@@ -815,16 +717,6 @@ namespace System
 
             info.AddValue("TypeObj", m_type, typeof(RuntimeType));
         }
-
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-        [MethodImpl(MethodImplOptions.InternalCall)]
-        internal static extern bool IsEquivalentTo(RuntimeType rtType1, RuntimeType rtType2);
-
-        [System.Security.SecuritySafeCritical]
-        [MethodImpl(MethodImplOptions.InternalCall)]
-        internal static extern bool IsEquivalentType(RuntimeType type);
-#endif // FEATURE_CORECLR
     }
 
     // This type is used to remove the expense of having a managed reference object that is dynamically 
@@ -853,14 +745,12 @@ namespace System
 
         internal IntPtr Value
         {
-            [SecurityCritical]
             get
             {
                 return m_handle;
             }
         }
 
-        [SecurityCritical]
         internal RuntimeMethodHandleInternal(IntPtr value)
         {
             m_handle = value;
@@ -877,7 +767,6 @@ namespace System
             m_value = methodHandleValue;
         }
 
-        [SecurityCritical]
         public RuntimeMethodInfoStub(IntPtr methodHandleValue, object keepalive)
         {
             m_keepalive = keepalive;
@@ -895,10 +784,8 @@ namespace System
         object m_e;
         object m_f;
         object m_g;
-#if FEATURE_REMOTING
-        object m_h;
-#endif
 #pragma warning restore 169
+
         public RuntimeMethodHandleInternal m_value;
 
         RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
@@ -948,14 +835,12 @@ namespace System
         }
 
         // Used by EE
-        [SecurityCritical]
         private static IntPtr GetValueInternal(RuntimeMethodHandle rmh)
         {
             return rmh.Value;
         }
         
         // ISerializable interface
-        [System.Security.SecurityCritical]  // auto-generated
         private RuntimeMethodHandle(SerializationInfo info, StreamingContext context)
         {
             if(info == null)
@@ -970,7 +855,6 @@ namespace System
                 throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
         }
 
-        [System.Security.SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context) 
         {
             if (info == null) 
@@ -988,21 +872,18 @@ namespace System
 
         public IntPtr Value
         {
-            [SecurityCritical]
             get
             {
                 return m_value != null ? m_value.Value.Value : IntPtr.Zero;
             }
         }
 
-        [SecuritySafeCritical]
         public override int GetHashCode()
         {
             return ValueType.GetHashCodeOfPtr(Value);
         }
 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [SecuritySafeCritical]
         public override bool Equals(object obj)
         {
             if (!(obj is RuntimeMethodHandle))
@@ -1024,7 +905,6 @@ namespace System
         }
 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [SecuritySafeCritical]
         public bool Equals(RuntimeMethodHandle handle)
         {
             return handle.Value == Value;
@@ -1036,12 +916,10 @@ namespace System
             return m_value == null; 
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal extern static IntPtr GetFunctionPointer(RuntimeMethodHandleInternal handle);
 
-        [System.Security.SecurityCritical]  // auto-generated
         public IntPtr GetFunctionPointer()
         {
             IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value).Value);
@@ -1049,11 +927,9 @@ namespace System
             return ptr;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal unsafe extern static void CheckLinktimeDemands(IRuntimeMethodInfo method, RuntimeModule module, bool isDecoratedTargetSecurityTransparent);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal extern static bool IsCAVisibleFromDecoratedType(
@@ -1062,21 +938,17 @@ namespace System
             RuntimeTypeHandle sourceTypeHandle,
             RuntimeModule sourceModule);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern IRuntimeMethodInfo _GetCurrentMethod(ref StackCrawlMark stackMark);
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark)
         {
             return _GetCurrentMethod(ref stackMark);
         }
         
         [Pure]
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static MethodAttributes GetAttributes(IRuntimeMethodInfo method)
         {
             MethodAttributes retVal = RuntimeMethodHandle.GetAttributes(method.Value);
@@ -1084,16 +956,13 @@ namespace System
             return retVal;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format, StringHandleOnStack retString);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format)
         {
             string name = null;
@@ -1101,11 +970,9 @@ namespace System
             return name;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static RuntimeType GetDeclaringType(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method)
         {
             RuntimeType type = RuntimeMethodHandle.GetDeclaringType(method.Value);
@@ -1113,11 +980,9 @@ namespace System
             return type;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static int GetSlot(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static int GetSlot(IRuntimeMethodInfo method)
         {
             Contract.Requires(method != null);
@@ -1127,15 +992,12 @@ namespace System
             return slot;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static int GetMethodDef(IRuntimeMethodInfo method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static string GetName(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static string GetName(IRuntimeMethodInfo method)
         {
             string name = RuntimeMethodHandle.GetName(method.Value);
@@ -1143,53 +1005,33 @@ namespace System
             return name;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static void* _GetUtf8Name(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static Utf8String GetUtf8Name(RuntimeMethodHandleInternal method)
         {
             return new Utf8String(_GetUtf8Name(method));
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool MatchesNameHash(RuntimeMethodHandleInternal method, uint hash);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor);
 
 #region Private Invocation Helpers
-        [System.Security.SecurityCritical]  // auto-generated
         internal static INVOCATION_FLAGS GetSecurityFlags(IRuntimeMethodInfo handle)
         {
             return (INVOCATION_FLAGS)RuntimeMethodHandle.GetSpecialSecurityFlags(handle);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static extern internal uint GetSpecialSecurityFlags(IRuntimeMethodInfo method);
 
-#if !FEATURE_CORECLR
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        static extern internal void PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, uint invocationFlags);
-
-        [System.Security.SecurityCritical]
-        static internal void PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, uint invocationFlags)
-        {
-            RuntimeMethodHandle.PerformSecurityCheck(obj, method.Value, parent, invocationFlags);
-            GC.KeepAlive(method);
-            return;
-        }
-#endif //!FEATURE_CORECLR
 #endregion
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DebuggerStepThroughAttribute]
         [Diagnostics.DebuggerHidden]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
@@ -1198,62 +1040,48 @@ namespace System
 
         // This returns true if the token is SecurityTransparent: 
         // just the token - does not consider including module/type etc.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool _IsTokenSecurityTransparent(RuntimeModule module, int metaDataToken);
         
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-#else
-        [System.Security.SecurityCritical]
-#endif
         internal static bool IsTokenSecurityTransparent(Module module, int metaDataToken)
         {
             return _IsTokenSecurityTransparent(module.ModuleHandle.GetRuntimeModule(), metaDataToken);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool _IsSecurityCritical(IRuntimeMethodInfo method);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsSecurityCritical(IRuntimeMethodInfo method)
         {
             return _IsSecurityCritical(method);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool _IsSecuritySafeCritical(IRuntimeMethodInfo method);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsSecuritySafeCritical(IRuntimeMethodInfo method)
         {
             return _IsSecuritySafeCritical(method);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool _IsSecurityTransparent(IRuntimeMethodInfo method);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsSecurityTransparent(IRuntimeMethodInfo method)
         {
             return _IsSecurityTransparent(method);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
                [SuppressUnmanagedCodeSecurity]
         private extern static void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method)
         {
             RuntimeType[] types = null;
@@ -1262,7 +1090,6 @@ namespace System
             return types;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method)
         {
             RuntimeType[] types = null;
@@ -1270,7 +1097,6 @@ namespace System
             return types;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method)
         {
             RuntimeType[] types = null;
@@ -1279,11 +1105,9 @@ namespace System
             return types;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool HasMethodInstantiation(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool HasMethodInstantiation(IRuntimeMethodInfo method)
         {
             bool fRet = RuntimeMethodHandle.HasMethodInstantiation(method.Value);
@@ -1291,19 +1115,15 @@ namespace System
             return fRet;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static bool IsGenericMethodDefinition(IRuntimeMethodInfo method)
         {
             bool fRet = RuntimeMethodHandle.IsGenericMethodDefinition(method.Value);
@@ -1312,16 +1132,13 @@ namespace System
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsTypicalMethodDefinition(IRuntimeMethodInfo method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetTypicalMethodDefinition(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
  
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method)
         {
             if (!IsTypicalMethodDefinition(method))
@@ -1330,12 +1147,10 @@ namespace System
             return method;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void StripMethodInstantiation(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
  
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method)
         {
             IRuntimeMethodInfo strippedMethod = method;
@@ -1345,25 +1160,20 @@ namespace System
             return strippedMethod;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static bool IsDynamicMethod(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal extern static void Destroy(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static Resolver GetResolver(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetCallerType(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retType);
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeType GetCallerType(ref StackCrawlMark stackMark)
         {
             RuntimeType type = null;
@@ -1372,14 +1182,11 @@ namespace System
         }
 
         [MethodImpl(MethodImplOptions.InternalCall)]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal extern static MethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         internal extern static bool IsConstructor(RuntimeMethodHandleInternal method);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         internal extern static LoaderAllocator GetLoaderAllocator(RuntimeMethodHandleInternal method);
     }
@@ -1410,14 +1217,12 @@ namespace System
 
         internal IntPtr Value
         {
-            [SecurityCritical]
             get
             {
                 return m_handle;
             }
         }
 
-        [SecurityCritical]
         internal RuntimeFieldHandleInternal(IntPtr value)
         {
             m_handle = value;
@@ -1437,7 +1242,6 @@ namespace System
     [StructLayout(LayoutKind.Sequential)]
     internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
     {
-        [SecuritySafeCritical]
         public RuntimeFieldInfoStub(IntPtr methodHandleValue, object keepalive)
         {
             m_keepalive = keepalive;
@@ -1451,9 +1255,6 @@ namespace System
         object m_d;
         int m_b;
         object m_e;
-#if FEATURE_REMOTING
-        object m_f;
-#endif
         RuntimeFieldHandleInternal m_fieldHandle;
 #pragma warning restore 169
 
@@ -1494,7 +1295,6 @@ namespace System
 
         public IntPtr Value
         {
-            [SecurityCritical]
             get
             {
                 return m_ptr != null ? m_ptr.Value.Value : IntPtr.Zero;
@@ -1506,14 +1306,12 @@ namespace System
             return m_ptr == null; 
         }
 
-        [SecuritySafeCritical]
         public override int GetHashCode()
         {
             return ValueType.GetHashCodeOfPtr(Value);
         }
         
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [SecuritySafeCritical]
         public override bool Equals(object obj)
         {
             if (!(obj is RuntimeFieldHandle))
@@ -1525,7 +1323,6 @@ namespace System
         }
 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [SecuritySafeCritical]
         public unsafe bool Equals(RuntimeFieldHandle handle)
         {
             return handle.Value == Value;
@@ -1541,30 +1338,23 @@ namespace System
             return !left.Equals(right);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
         internal static extern String GetName(RtFieldInfo field); 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
         private static extern unsafe void* _GetUtf8Name(RuntimeFieldHandleInternal field); 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static unsafe Utf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new Utf8String(_GetUtf8Name(field)); }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field); 
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field)
         {
             RuntimeType type = GetApproxDeclaringType(field.Value);
@@ -1572,77 +1362,62 @@ namespace System
             return type;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
         internal static extern int GetToken(RtFieldInfo field); 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
         internal static extern Object GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
         internal static extern Object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void *pTypedRef, RuntimeType contextType);
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
         internal static extern void SetValue(RtFieldInfo field, Object obj, Object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, Object value, RuntimeType contextType);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool AcquiresContextFromThis(RuntimeFieldHandleInternal field);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool IsSecurityCritical(RuntimeFieldHandle fieldHandle);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsSecurityCritical()
         {
             return IsSecurityCritical(GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool IsSecuritySafeCritical(RuntimeFieldHandle fieldHandle);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsSecuritySafeCritical()
         {
             return IsSecuritySafeCritical(GetNativeHandle());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Bool)]
         private static extern bool IsSecurityTransparent(RuntimeFieldHandle fieldHandle);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal bool IsSecurityTransparent()
         {
             return IsSecurityTransparent(GetNativeHandle());
         }
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal static extern void CheckAttributeAccess(RuntimeFieldHandle fieldHandle, RuntimeModule decoratedTarget);
 
         // ISerializable interface
-        [System.Security.SecurityCritical]  // auto-generated
         private RuntimeFieldHandle(SerializationInfo info, StreamingContext context)
         {
             if(info==null)
@@ -1660,7 +1435,6 @@ namespace System
                 throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
         }
 
-        [System.Security.SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context) 
         {
             if (info == null) 
@@ -1744,11 +1518,9 @@ namespace System
             return !left.Equals(right);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern IRuntimeMethodInfo GetDynamicMethod(DynamicMethod method, RuntimeModule module, string name, byte[] sig, Resolver resolver);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int GetToken(RuntimeModule module);
 
@@ -1770,7 +1542,6 @@ namespace System
             return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
         {
             ValidateModulePointer(module);
@@ -1792,7 +1563,6 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void ResolveType(RuntimeModule module,
@@ -1812,7 +1582,6 @@ namespace System
             return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
         {
             int typeInstCount, methodInstCount;
@@ -1827,7 +1596,6 @@ namespace System
             return retVal;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[] typeInstantiationContext, int typeInstCount, IntPtr[] methodInstantiationContext, int methodInstCount)
         {
             ValidateModulePointer(module);
@@ -1841,7 +1609,6 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static RuntimeMethodHandleInternal ResolveMethod(RuntimeModule module,
@@ -1857,7 +1624,6 @@ namespace System
         public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
             { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
         {
             ValidateModulePointer(module);
@@ -1880,7 +1646,6 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void ResolveField(RuntimeModule module,
@@ -1891,23 +1656,19 @@ namespace System
                                                       int methodInstCount,
                                                       ObjectHandleOnStack retField);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static bool _ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash)
         {
             return _ContainsPropertyMatchingHash(module.GetNativeHandle(), propertyToken, hash);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetAssembly(RuntimeModule handle, ObjectHandleOnStack retAssembly);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeAssembly GetAssembly(RuntimeModule module)
         {
             RuntimeAssembly retAssembly = null;
@@ -1915,12 +1676,10 @@ namespace System
             return retAssembly;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal extern static void GetModuleType(RuntimeModule handle, ObjectHandleOnStack type);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static RuntimeType GetModuleType(RuntimeModule module)
         {
             RuntimeType type = null;
@@ -1928,13 +1687,11 @@ namespace System
             return type;
         }
  
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private extern static void GetPEKind(RuntimeModule handle, out int peKind, out int machine);
    
         // making this internal, used by Module.GetPEKind
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine)
         {
             int lKind, lMachine;
@@ -1943,21 +1700,17 @@ namespace System
             machine = (ImageFileMachine)lMachine;
         }
    
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
         internal extern static int GetMDStreamVersion(RuntimeModule module);
 
         public int MDStreamVersion
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return GetMDStreamVersion(GetRuntimeModule().GetNativeHandle()); }
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern static IntPtr _GetMetadataImport(RuntimeModule module);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static MetadataImport GetMetadataImport(RuntimeModule module)
         {
             return new MetadataImport(_GetMetadataImport(module.GetNativeHandle()), module);
@@ -1990,7 +1743,6 @@ namespace System
 #endregion
 
 #region FCalls
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]        
         private extern void GetSignature(
             void* pCorSig, int cCorSig,
@@ -2006,7 +1758,6 @@ namespace System
         internal RuntimeType m_declaringType;
         internal RuntimeType m_returnTypeORfieldType;
         internal object m_keepalive;
-        [SecurityCritical]
         internal void* m_sig;
         internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags
         internal int m_nSizeOfArgStack;
@@ -2015,7 +1766,6 @@ namespace System
 #endregion
 
 #region Constructors
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Signature (
             IRuntimeMethodInfo method,
             RuntimeType[] arguments,
@@ -2030,20 +1780,17 @@ namespace System
             GetSignature(null, 0, new RuntimeFieldHandleInternal(), method, null);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Signature(IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
         {
             GetSignature(null, 0, new RuntimeFieldHandleInternal(), methodHandle, declaringType);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType)
         {
             GetSignature(null, 0, fieldHandle.Value, null, declaringType);
             GC.KeepAlive(fieldHandle);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public Signature(void* pCorSig, int cCorSig, RuntimeType declaringType)
         {
             GetSignature(pCorSig, cCorSig, new RuntimeFieldHandleInternal(), null, declaringType);
@@ -2056,11 +1803,9 @@ namespace System
         internal RuntimeType ReturnType { get { return m_returnTypeORfieldType; } }
         internal RuntimeType FieldType { get { return m_returnTypeORfieldType; } }
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool CompareSig(Signature sig1, Signature sig2);
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern Type[] GetCustomModifiers(int position, bool required);
 #endregion
@@ -2083,12 +1828,10 @@ namespace System
         internal abstract RuntimeType GetJitContext(ref int securityControlFlags);
         internal abstract byte[] GetCodeInfo(ref int stackSize, ref int initLocals, ref int EHCount);
         internal abstract byte[] GetLocalsSignature();
-        [System.Security.SecurityCritical] // takes a pointer parameter
         internal abstract unsafe void GetEHInfo(int EHNumber, void* exception);
         internal abstract unsafe byte[] GetRawEHInfo();
         // token resolution
         internal abstract String GetStringLiteral(int token);
-        [System.Security.SecurityCritical] // passes a pointer out
         internal abstract void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle);
         internal abstract byte[] ResolveSignature(int token, int fromMethod);
         // 
index a9ec9cf..da6ac5c 100644 (file)
@@ -73,13 +73,11 @@ namespace System {
     
             
         // Provides a string representation of a byte.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
@@ -95,7 +93,6 @@ namespace System {
             return ToString(format, NumberFormatInfo.GetInstance(provider));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private String ToString(String format, NumberFormatInfo info) {
             Contract.Ensures(Contract.Result<String>() != null);
 
index c52176a..20f5c5f 100644 (file)
@@ -70,12 +70,6 @@ namespace System.Security.AccessControl
 
     [Flags]
     public enum AccessControlActions {
-#if FEATURE_MACL
-        None = 0,
-        View = 1,
-        Change = 2
-#else
         None = 0
-#endif
     }
 }
index e29dec3..4853957 100644 (file)
@@ -6,6 +6,7 @@
 // 
 
 using System;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Security.Permissions;
 using Microsoft.Win32;
@@ -180,30 +181,6 @@ namespace System.Security
                                Flags = ""SkipVerification"" />
                </PermissionSet>";
 
-#if FEATURE_CAS_POLICY
-        private const string s_wpfExtensionXml =
-            @"<PermissionSet class = ""System.Security.PermissionSet""
-                             version = ""1"">
-                  <IPermission class = ""System.Security.Permissions.MediaPermission, " + AssemblyRef.WindowsBase + @"""
-                               version = ""1""
-                               Audio=""SafeAudio"" Video=""SafeVideo"" Image=""SafeImage"" />
-                  <IPermission class = ""System.Security.Permissions.WebBrowserPermission, " + AssemblyRef.WindowsBase + @"""
-                               version = ""1""
-                               Level=""Safe"" />
-              </PermissionSet>";
-
-        private const string s_wpfExtensionUnrestrictedXml =
-            @"<PermissionSet class = ""System.Security.PermissionSet""
-                             version = ""1"">
-                  <IPermission class = ""System.Security.Permissions.MediaPermission, " + AssemblyRef.WindowsBase + @"""
-                               version = ""1""
-                               Unrestricted = ""true"" />
-                  <IPermission class = ""System.Security.Permissions.WebBrowserPermission, " + AssemblyRef.WindowsBase + @"""
-                               version = ""1""
-                               Unrestricted = ""true"" />
-              </PermissionSet>";
-#endif //FEATURE_CAS_POLICY
-
         //
         // Built in permission set objects
         // 
@@ -222,11 +199,7 @@ namespace System.Security
 
         internal static NamedPermissionSet Everything
         {
-            get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml
-#if FEATURE_CAS_POLICY
-                     , s_wpfExtensionUnrestrictedXml
-#endif // FEATURE_CAS_POLICY
-                     ); }
+            get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml); }
         }
 
         internal static NamedPermissionSet Execution
@@ -241,20 +214,12 @@ namespace System.Security
 
         internal static NamedPermissionSet Internet
         {
-            get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml
-#if FEATURE_CAS_POLICY
-                     , s_wpfExtensionXml
-#endif // FEATURE_CAS_POLICY
-                     ); }
+            get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml); }
         }
 
         internal static NamedPermissionSet LocalIntranet
         {
-            get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml
-#if FEATURE_CAS_POLICY
-                     , s_wpfExtensionXml
-#endif // FEATURE_CAS_POLICY
-                     ); }
+            get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml); }
         }
 
         internal static NamedPermissionSet Nothing
@@ -272,71 +237,19 @@ namespace System.Security
         // set extensions if necessary
         //
 
-        private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet(ref NamedPermissionSet permissionSet,
-                                                                                  string permissionSetXml
-#if FEATURE_CAS_POLICY
-                                                                                  ,string extensionXml
-#endif // FEATURE_CAS_POLICY
-                                                                                  )
+        private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet(
+            ref NamedPermissionSet permissionSet,
+            string permissionSetXml)
         {
             Contract.Requires(!String.IsNullOrEmpty(permissionSetXml));
-#if FEATURE_CAS_POLICY
-            Contract.Requires(!String.IsNullOrEmpty(extensionXml));
-#endif // FEATURE_CAS_POLICY
-
-            if (permissionSet == null)
-            {
-#if FEATURE_CAS_POLICY
-                SecurityElement securityElement = SecurityElement.FromString(permissionSetXml);
-                NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement);
-
-                PermissionSet extensions = GetPermissionSetExtensions(extensionXml);
-                deserializedPermissionSet.InplaceUnion(extensions);
-
-                permissionSet = deserializedPermissionSet;
-#endif // FEATURE_CAS_POLICY
-            }
-
             return permissionSet.Copy() as NamedPermissionSet;
         }
 
         private static NamedPermissionSet GetOrDeserializePermissionSet(ref NamedPermissionSet permissionSet,
                                                                         string permissionSetXml)
         {
-            Contract.Assert(!String.IsNullOrEmpty(permissionSetXml));
-
-#if FEATURE_CAS_POLICY
-            if (permissionSet == null)
-            {
-                SecurityElement securityElement = SecurityElement.FromString(permissionSetXml);
-                NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement);
-                
-                permissionSet = deserializedPermissionSet;
-            }
-#endif // FEATURE_CAS_POLICY
-
+            Debug.Assert(!String.IsNullOrEmpty(permissionSetXml));
             return permissionSet.Copy() as NamedPermissionSet;
         }
-
-#if FEATURE_CAS_POLICY
-        private static PermissionSet GetPermissionSetExtensions(string extensionXml)
-        {
-            Contract.Requires(!String.IsNullOrEmpty(extensionXml));
-
-            SecurityElement se = SecurityElement.FromString(extensionXml);
-
-            // Return the permission set extension only if WPF is in the present framework profile.
-            // XMLUtil.GetClassFromElement() helps do the quickest check, with no exception thrown and 
-            // minimal parsing.
-            SecurityElement firstPermission = (SecurityElement)se.Children[0];
-            if (System.Security.Util.XMLUtil.GetClassFromElement(firstPermission, /*ignoreTypeLoadFailures*/true) != null)
-            {
-                PermissionSet extensions = new NamedPermissionSet(se);
-                return extensions;
-            }
-
-            return null;
-        }
-#endif // FEATURE_CAS_POLICY
     }
 }
index 46a1286..70504d9 100644 (file)
@@ -13,20 +13,16 @@ namespace System.Security
     using System.Collections;
     using System.Text;
     using System;
-    using  System.Diagnostics;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using IUnrestrictedPermission = System.Security.Permissions.IUnrestrictedPermission;
 
     [Serializable]
-#if !FEATURE_CORECLR
-    [SecurityPermissionAttribute( SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true )]
-#endif
     [System.Runtime.InteropServices.ComVisible(true)]
     abstract public class CodeAccessPermission
         : IPermission, ISecurityEncodable, IStackWalk
     {
         // Static methods for manipulation of stack
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static void RevertAssert()
         {
@@ -34,7 +30,6 @@ namespace System.Security
             SecurityRuntime.RevertAssert(ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
         public static void RevertDeny()
@@ -43,7 +38,6 @@ namespace System.Security
             SecurityRuntime.RevertDeny(ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static void RevertPermitOnly()
         {
@@ -51,7 +45,6 @@ namespace System.Security
             SecurityRuntime.RevertPermitOnly(ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static void RevertAll()
         {
@@ -66,7 +59,6 @@ namespace System.Security
 
         // Mark this method as requiring a security object on the caller's frame
         // so the caller won't be inlined (which would mess up stack crawling).
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public void Demand()
@@ -78,7 +70,6 @@ namespace System.Security
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         internal static void Demand(PermissionType permissionType)
@@ -87,7 +78,7 @@ namespace System.Security
             //    without having to create objects.
             //    The security annotation fxcop rule that flags all methods with a Demand() has logic
             //    which checks for methods named Demand in types that implement IPermission or IStackWalk. 
-            Contract.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand");
+            Debug.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand");
             
             StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
             CodeAccessSecurityEngine.SpecialDemand(permissionType, ref stackMark);
@@ -96,7 +87,6 @@ namespace System.Security
         // Metadata for this method should be flaged with REQ_SQ so that
         // EE can allocate space on the stack frame for FrameSecurityDescriptor
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public void Assert()
@@ -106,7 +96,6 @@ namespace System.Security
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable    
         static internal void Assert(bool allPossible)
@@ -115,7 +104,7 @@ namespace System.Security
             //    without having to new a PermissionSet.
             //    The security annotation fxcop rule that flags all methods with an Assert() has logic
             //    which checks for methods named Assert in types that implement IPermission or IStackWalk. 
-            Contract.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert");
+            Debug.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert");
             
             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
             SecurityRuntime.AssertAllPossible(ref stackMark);
@@ -124,7 +113,6 @@ namespace System.Security
         // Metadata for this method should be flaged with REQ_SQ so that
         // EE can allocate space on the stack frame for FrameSecurityDescriptor
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
@@ -137,7 +125,6 @@ namespace System.Security
         // Metadata for this method should be flaged with REQ_SQ so that
         // EE can allocate space on the stack frame for FrameSecurityDescriptor
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public void PermitOnly()
@@ -160,48 +147,6 @@ namespace System.Security
             // otherwise we don't support it.
             throw new NotSupportedException(Environment.GetResourceString( "NotSupported_SecurityPermissionUnion" ));
         }
-        
-#if FEATURE_CAS_POLICY
-        static internal SecurityElement CreatePermissionElement( IPermission perm, String permname )
-        {
-            SecurityElement root = new SecurityElement( "IPermission" );
-            XMLUtil.AddClassAttribute( root, perm.GetType(), permname );
-            // If you hit this assert then most likely you are trying to change the name of this class. 
-            // This is ok as long as you change the hard coded string above and change the assert below.
-            Contract.Assert( perm.GetType().FullName.Equals( permname ), "Incorrect class name passed in! Was: " + permname + " Should be " + perm.GetType().FullName);
-
-            root.AddAttribute( "version", "1" );
-            return root;
-        }
-        
-        static internal void ValidateElement( SecurityElement elem, IPermission perm )
-        {
-            if (elem == null)
-                throw new ArgumentNullException( nameof(elem) );
-            Contract.EndContractBlock();
-                
-            if (!XMLUtil.IsPermissionElement( perm, elem ))
-                throw new ArgumentException( Environment.GetResourceString( "Argument_NotAPermissionElement"));
-                
-            String version = elem.Attribute( "version" );
-            
-            if (version != null && !version.Equals( "1" ))
-                throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXMLBadVersion") );
-        }
-
-        abstract public SecurityElement ToXml();
-        abstract public void FromXml( SecurityElement elem );
-
-        //
-        // Unimplemented interface methods 
-        // (as a reminder only)
-        //
-
-        public override String ToString()
-        {
-            return ToXml().ToString();
-        }
-#endif // FEATURE_CAS_POLICY
 
         //
         // HELPERS FOR IMPLEMENTING ABSTRACT METHODS
@@ -258,26 +203,26 @@ namespace System.Security
 
         internal bool CheckDemand(CodeAccessPermission grant)
         {
-            Contract.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" );
+            Debug.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" );
             return IsSubsetOf( grant );
         }
 
         internal bool CheckPermitOnly(CodeAccessPermission permitted)
         {
-            Contract.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
+            Debug.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
             return IsSubsetOf( permitted );
         }
 
         internal bool CheckDeny(CodeAccessPermission denied)
         {
-            Contract.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" );
+            Debug.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" );
             IPermission intersectPerm = Intersect(denied);
             return (intersectPerm == null || intersectPerm.IsSubsetOf(null));
         }
 
         internal bool CheckAssert(CodeAccessPermission asserted)
         {
-            Contract.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
+            Debug.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
             return IsSubsetOf( asserted );
         }
     }
index 2a1cf9a..d86897c 100644 (file)
@@ -15,6 +15,7 @@ namespace System.Security {
     using System.Globalization;
     using System.Security.Policy;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // Used in DemandInternal, to remember the result of previous demands
@@ -52,40 +53,22 @@ namespace System.Security {
         internal static SecurityPermission AssertPermission; 
         internal static PermissionToken AssertPermissionToken; 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void SpecialDemand(PermissionType whatPermission, ref StackCrawlMark stackMark);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [System.Diagnostics.Conditional( "_DEBUG" )]
         private static void DEBUG_OUT( String str )
         {
-#if _DEBUG        
+#if _DEBUG
             if (debug)
-            {
-#if !FEATURE_CORECLR
-                if (to_file)
-                {
-                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
-                    sb.Append( str );
-                    sb.Append ((char)13) ;
-                    sb.Append ((char)10) ;
-                    PolicyManager.DebugOut( file, sb.ToString() );
-                }
-                else
-#endif                    
-                    Console.WriteLine( str );
-             }
-#endif             
+                Console.WriteLine( str );
+#endif
         }
-        
-#if _DEBUG 
+
+#if _DEBUG
         private static bool debug = false;
-#if !FEATURE_CORECLR
-        private static readonly bool to_file = false;
-#endif
         private const String file = "d:\\foo\\debug.txt";
-#endif  
+#endif
 
         // static default constructor. This will be called before any of the static members are accessed.
         static CodeAccessSecurityEngine()
@@ -96,7 +79,6 @@ namespace System.Security {
             AssertPermissionToken = PermissionToken.GetToken(AssertPermission);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
 #pragma warning disable 618
         private static void ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
 #pragma warning restore 618
@@ -109,20 +91,15 @@ namespace System.Security {
                 // there will be an infinite recursion that overflows the stack.
                 PermissionSet.s_fullTrust.Assert();
                 asmName = asm.GetName();
-#if FEATURE_CAS_POLICY
-                if(asm != Assembly.GetExecutingAssembly()) // this condition is to avoid having to marshal mscorlib's evidence (which is always in teh default domain) to the current domain
-                    asmEvidence = asm.Evidence;
-#endif // FEATURE_CAS_POLICY
             }
             throw SecurityException.MakeSecurityException(asmName, asmEvidence, granted, refused, rmh, action, demand, permThatFailed);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
 #pragma warning disable 618
         private static void ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
 #pragma warning restore 618
         {
-            Contract.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here");
+            Debug.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here");
             
             if (assemblyOrString == null || assemblyOrString is RuntimeAssembly)
                 ThrowSecurityException((RuntimeAssembly)assemblyOrString, granted, refused, rmh, action, demand, permThatFailed);
@@ -134,7 +111,6 @@ namespace System.Security {
         }
 
 #if FEATURE_COMPRESSEDSTACK
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void CheckSetHelper(CompressedStack cs,
                                            PermissionSet grants,
                                            PermissionSet refused,
@@ -149,9 +125,6 @@ namespace System.Security {
                 CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true);
         }
 #else // FEATURE_COMPRESSEDSTACK
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
 #pragma warning disable 618
         internal static void CheckSetHelper(Object notUsed,
                                            PermissionSet grants,
@@ -165,14 +138,13 @@ namespace System.Security {
             // To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object,
             // we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be
             // corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.)
-            Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
+            Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
 
             CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true);
         }
 
 #endif // FEATURE_COMPRESSEDSTACK
 
-        [System.Security.SecurityCritical]  // auto-generated
 #pragma warning disable 618
         internal static bool CheckSetHelper(PermissionSet grants,
                                            PermissionSet refused,
@@ -183,19 +155,7 @@ namespace System.Security {
                                            bool throwException)
 #pragma warning restore 618
         {
-
-            Contract.Assert(demands != null, "Should not reach here with a null demand set");
-#if _DEBUG && FEATURE_CAS_POLICY
-            if (debug)
-            {
-                DEBUG_OUT("Granted: ");
-                DEBUG_OUT(grants.ToXml().ToString());
-                DEBUG_OUT("Refused: ");
-                DEBUG_OUT(refused != null ? refused.ToXml().ToString() : "<null>");
-                DEBUG_OUT("Demanded: ");
-                DEBUG_OUT(demands!=null ? demands.ToXml().ToString() : "<null>");
-            }
-#endif // _DEBUG && FEATURE_CAS_POLICY
+            Debug.Assert(demands != null, "Should not reach here with a null demand set");
 
             IPermission permThatFailed = null;
             if (grants != null)
@@ -248,7 +208,6 @@ namespace System.Security {
             return true;
         }
 #if FEATURE_COMPRESSEDSTACK
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void CheckHelper(CompressedStack cs,
                                         PermissionSet grantedSet,
                                         PermissionSet refusedSet,
@@ -264,9 +223,6 @@ namespace System.Security {
                 CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true);
         }
 #else // FEATURE_COMPRESSEDSTACK
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
 #pragma warning disable 618
         internal static void CheckHelper(Object notUsed,
                                         PermissionSet grantedSet,
@@ -281,11 +237,10 @@ namespace System.Security {
             // To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object,
             // we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be
             // corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.)
-            Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
+            Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
             CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true);
         }
 #endif // FEATURE_COMPRESSEDSTACK
-        [System.Security.SecurityCritical]  // auto-generated
 #pragma warning disable 618
         internal static bool CheckHelper(PermissionSet grantedSet,
                                         PermissionSet refusedSet,
@@ -298,19 +253,7 @@ namespace System.Security {
 #pragma warning restore 618
         {
             // We should never get here with a null demand
-            Contract.Assert(demand != null, "Should not reach here with a null demand");
-            
-#if _DEBUG && FEATURE_CAS_POLICY
-            if (debug)
-            {
-                DEBUG_OUT("Granted: ");
-                DEBUG_OUT(grantedSet.ToXml().ToString());
-                DEBUG_OUT("Refused: ");
-                DEBUG_OUT(refusedSet != null ? refusedSet.ToXml().ToString() : "<null>");
-                DEBUG_OUT("Demanded: ");
-                DEBUG_OUT(demand.ToString());
-            }
-#endif // _DEBUG && FEATURE_CAS_POLICY
+            Debug.Assert(demand != null, "Should not reach here with a null demand");
 
             if (permToken == null)
                 permToken = PermissionToken.GetToken(demand);
@@ -339,7 +282,7 @@ namespace System.Security {
                     // If we aren't unrestricted, there is a refused set, or our permission is not of the unrestricted
                     // variety, we need to do the proper callback.
 
-                    Contract.Assert(demand != null,"demand != null");
+                    Debug.Assert(demand != null,"demand != null");
 
                     // Find the permission of matching type in the permission set.
 
@@ -411,420 +354,35 @@ namespace System.Security {
             return true;
         }
 
-#if FEATURE_CAS_POLICY
-        /// <summary>
-        ///     Demand for the grant set of an assembly
-        /// </summary>
-        /// <remarks>
-        ///     Managed half of SecurityStackWalk::DemandGrantSet.
-        /// </remarks>
-        [System.Security.SecurityCritical]  // auto-generated
-        private static void CheckGrantSetHelper(PermissionSet grantSet)
-        {
-            Contract.Assert(grantSet != null, "Missing grant set");
-            grantSet.CopyWithNoIdentityPermissions().Demand();
-        }
-
-        /// <summary>
-        ///     Perform a security demand which succeeds if either a compatibilty permission is granted to the
-        ///     call stack, or restricted member access and the grant set of the target of the reflection
-        ///     operation is granted.
-        /// </summary>
-        /// <param name="permission">compatibility permission to check</param>
-        /// <param name="targetGrant">grant set of the reflection target</param>
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static void ReflectionTargetDemandHelper(PermissionType permission, PermissionSet targetGrant)
-        {
-            ReflectionTargetDemandHelper((int)permission, targetGrant);
-        }
-
-        /// <summary>
-        ///     Perform a security demand which succeeds if either a compatibilty permission is granted to the
-        ///     call stack, or restricted member access and the grant set of the target of the reflection
-        ///     operation is granted.
-        /// </summary>
-        /// <remarks>
-        ///     Managed half of SecurityStackWalk::ReflectionTargetDemand.
-        /// </remarks>
-        /// <param name="permission">compatibility permission to check (See PermissionType)</param>
-        /// <param name="targetGrant">grant set of the reflection target</param>
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
-        private static void ReflectionTargetDemandHelper(int permission, PermissionSet targetGrant)
-        {
-            // Capture a compressed stack so that we can make both permission checks without walking the stack
-            // multiple times.
-            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-            CompressedStack cs = CompressedStack.GetCompressedStack(ref stackMark);
-
-            ReflectionTargetDemandHelper(permission, targetGrant, cs);
-        }
-
-        /// <summary>
-        ///     Perform a reflection target demand against a given access context
-        /// </summary>
-        /// <remarks>
-        ///     Managed half of SecurityStackWalk::ReflectionTargetDemand
-        /// </remarks>
-        /// <param name="permission">compatibility permission to check (See PermissionType)</param>
-        /// <param name="targetGrant">grant set of the reflection target</param>
-        /// <param name="accessContext">access context to do the demand against</param>
-        [System.Security.SecurityCritical]  // auto-generated
-        private static void ReflectionTargetDemandHelper(int permission,
-                                                         PermissionSet targetGrant,
-                                                         Resolver accessContext)
-        {
-            ReflectionTargetDemandHelper(permission, targetGrant, accessContext.GetSecurityContext());
-        }
-
-        /// <summary>
-        ///     Perform a reflection target demand against a given compressed stack
-        /// </summary>
-        /// <remarks>
-        ///     Managed half of SecurityStackWalk::ReflectionTargetDemand
-        /// </remarks>
-        /// <param name="permission">compatibility permission to check (See PermissionType)</param>
-        /// <param name="targetGrant">grant set of the reflection target</param>
-        /// <param name="securityContext">compressed stack to do the demand against</param>
-        [System.Security.SecurityCritical]  // auto-generated
-        private static void ReflectionTargetDemandHelper(int permission,
-                                                         PermissionSet targetGrant,
-                                                         CompressedStack securityContext)
-        {
-            Contract.Assert(securityContext != null, "securityContext != null");
-
-            // We need to remove all identity permissions from the grant set of the target, otherwise the
-            // disjunctive demand will fail unless we're reflecting on the same assembly.
-            PermissionSet demandSet = null;
-            if (targetGrant == null)
-            {
-                demandSet = new PermissionSet(PermissionState.Unrestricted);
-            }
-            else
-            {
-                demandSet = targetGrant.CopyWithNoIdentityPermissions();
-                demandSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));
-            }
-
-            securityContext.DemandFlagsOrGrantSet((1 << (int)permission), demandSet);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static void GetZoneAndOriginHelper( CompressedStack cs, PermissionSet grantSet, PermissionSet refusedSet, ArrayList zoneList, ArrayList originList )
-        {
-            if (cs != null)
-                cs.GetZoneAndOrigin(zoneList, originList, PermissionToken.GetToken(typeof(ZoneIdentityPermission)), PermissionToken.GetToken(typeof(UrlIdentityPermission)));
-            else
-        {
-            ZoneIdentityPermission zone = (ZoneIdentityPermission)grantSet.GetPermission( typeof( ZoneIdentityPermission ) );
-            UrlIdentityPermission url = (UrlIdentityPermission)grantSet.GetPermission( typeof( UrlIdentityPermission ) );
-
-            if (zone != null)
-                zoneList.Add( zone.SecurityZone );
-
-            if (url != null)
-                originList.Add( url.Url );
-            }
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static void GetZoneAndOrigin( ref StackCrawlMark mark, out ArrayList zone, out ArrayList origin )
-        {
-            zone = new ArrayList();
-            origin = new ArrayList();
-
-            GetZoneAndOriginInternal( zone, origin, ref mark);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern void GetZoneAndOriginInternal(ArrayList zoneList, 
-                                  ArrayList originList, 
-                                  ref StackCrawlMark stackMark);
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static void CheckAssembly(RuntimeAssembly asm, CodeAccessPermission demand )
-        {
-            Contract.Assert( asm != null, "Must pass in a good assembly" );
-            Contract.Assert( demand != null, "Must pass in a good demand" );
-
-            PermissionSet granted, refused;
-            asm.GetGrantSet( out granted, out refused );
-#pragma warning disable 618
-                CheckHelper( granted, refused, demand, PermissionToken.GetToken(demand), RuntimeMethodHandleInternal.EmptyHandle, asm, SecurityAction.Demand, true );
-#pragma warning restore 618
-        }
-
-        // Check - Used to initiate a code-access security check.
-        // This method invokes a stack walk after skipping to the frame
-        // referenced by stackMark.
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern void Check (Object demand,
-                                  ref StackCrawlMark stackMark, 
-                                  bool isPermSet);
-
-  
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        internal static extern bool QuickCheckForAllDemands();
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        internal static extern bool AllDomainsHomogeneousWithNoStackModifiers();
-#endif // FEATURE_CAS_POLICY
-
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void Check(CodeAccessPermission cap, ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            Check(cap,
-                  ref stackMark,
-                  false);
-#endif // FEATURE_CAS_POLICY
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void Check(PermissionSet permSet, ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            Check(permSet,
-                 ref stackMark,
-                 true);
-#endif // FEATURE_CAS_POLICY
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern FrameSecurityDescriptor CheckNReturnSO(PermissionToken permToken, 
                                                                     CodeAccessPermission demand, 
                                                                     ref StackCrawlMark stackMark,
                                                                     int create );
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void Assert(CodeAccessPermission cap, ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            // Make sure the caller of assert has the permission to assert
-            //WARNING: The placement of the call here is just right to check
-            //         the appropriate frame.
-            
-            // Note: if the "AssertPermission" is not a permission that implements IUnrestrictedPermission
-            // you need to change the last parameter to a zero.
-            Contract.Assert(AssertPermissionToken != null && AssertPermission != null, "Assert Permission not setup correctly");
-            FrameSecurityDescriptor secObj = CheckNReturnSO(AssertPermissionToken,
-                                                            AssertPermission,
-                                                            ref stackMark,
-                                                            1 );
-            if (secObj == null)
-            {
-                // Security: REQ_SQ flag is missing. Bad compiler ?
-                // This can happen when you create delegates over functions that need the REQ_SQ 
-                System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-            else
-            {
-                if (secObj.HasImperativeAsserts())
-                    throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
-                secObj.SetAssert(cap);
-            }
-#endif // FEATURE_CAS_POLICY
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void Deny(CodeAccessPermission cap, ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            // Deny is only valid in legacy mode
-            if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
-            {
-                throw new NotSupportedException(Environment.GetResourceString("NotSupported_CasDeny"));
-            }
-
-            FrameSecurityDescriptor secObj =
-                SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
-            if (secObj == null)
-            {
-                // Security: REQ_SQ flag is missing. Bad compiler ?
-                // This can happen when you create delegates over functions that need the REQ_SQ 
-                System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-            else
-            {
-                if (secObj.HasImperativeDenials())
-                    throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
-                secObj.SetDeny(cap);
-            }
-#endif // FEATURE_CAS_POLICY
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void PermitOnly(CodeAccessPermission cap, ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            FrameSecurityDescriptor secObj =
-                SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
-            if (secObj == null)
-            {
-                // Security: REQ_SQ flag is missing. Bad compiler ?
-                // This can happen when you create delegates over functions that need the REQ_SQ 
-                System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-            else
-            {
-                if (secObj.HasImperativeRestrictions())
-                    throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
-                secObj.SetPermitOnly(cap);
-            }
-#endif // FEATURE_CAS_POLICY
-        }
-        
-#if FEATURE_CAS_POLICY
-        // Called from the VM to do a pre-domain initialization check of the security state of the
-        // AppDomain.  This method looks at the state of the security of an AppDomain before it is
-        // completely initialized - so the output of this method does not always match what will be true
-        // when the domain is completely initialized.  Instead, it is used to read what the input parameters
-        // to the domain setup say about the domain.
-        private static void PreResolve(out bool isFullyTrusted, out bool isHomogeneous)
-        {
-            //
-            // There are three main cases:
-            //   1. The AppDomain has an explict ApplicationTrust - we can use this to read the input state
-            //      of the AppDomain.
-            //   2. The AppDomain is using legacy CAS policy - this means we can't tell much about the
-            //      domain itself without a full policy resolution.
-            //   3. The domain is a standard v4+ AppDomain - these are always full trust and homogenous by
-            //      default.
-            //
-
-            // If the AppDomain is setup with an ApplicationTrust then it is always homogenous and we can
-            // tell its grant set right from the ApplicaitonTrust
-            ApplicationTrust domainTrust = AppDomain.CurrentDomain.SetupInformation.ApplicationTrust;
-            if (domainTrust != null)
-            {
-                isFullyTrusted = domainTrust.DefaultGrantSet.PermissionSet.IsUnrestricted();
-                isHomogeneous = true;
-                return;
-            }
-
-            // Otherwise, see if the domain is being configured on input to use legacy CAS policy
-            if (CompatibilitySwitches.IsNetFx40LegacySecurityPolicy || AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
-            {
-                isFullyTrusted = false;
-                isHomogeneous = false;
-                return;
-            }
-
-            // If none of the above is true, then we must be a standard AppDomain
-            isFullyTrusted = true;
-            isHomogeneous = true;
-        }
-
-        // Called from the VM when either a HostSecurityManager or simple sandbox domain can determine the
-        // grant set of an assembly
-        private static PermissionSet ResolveGrantSet(Evidence evidence, out int specialFlags, bool checkExecutionPermission)
-        {
-            Contract.Assert(evidence != null);
-            Contract.Assert(!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled); // This API does not do CAS policy resolution
-
-            PermissionSet grantSet = null;
-            if (!TryResolveGrantSet(evidence, out grantSet))
-            {
-                // If we couldn't figure out a grant set from the domain or the host, then we treat the
-                // assembly as fully trusted.
-                grantSet = new PermissionSet(PermissionState.Unrestricted);
-            }
-
-            // Make sure the grant set includes the ability to execute code if that has been requested.
-            if (checkExecutionPermission)
-            {
-                SecurityPermission executionPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
-                if (!grantSet.Contains(executionPermission))
-                {
-                    throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"),
-                                              System.__HResults.CORSEC_E_NO_EXEC_PERM);
-                }
-            }
-
-            specialFlags = SecurityManager.GetSpecialFlags(grantSet, null);
-            return grantSet;
-        }
-
-        // Consult the host and the current AppDomain if it is homogenous to determine what the grant set
-        // of an assembly is.  This API returns true if it was able to determine a grant set for the evidence,
-        // false if it cannot and other policy needs to be applied.
-        [SecuritySafeCritical]
-        internal static bool TryResolveGrantSet(Evidence evidence, out PermissionSet grantSet)
-        {
-            Contract.Assert(evidence != null);
-
-            HostSecurityManager securityManager = AppDomain.CurrentDomain.HostSecurityManager;
-
-            // GAC assemblies always are fully trusted
-            if (evidence.GetHostEvidence<GacInstalled>() != null)
-            {
-                grantSet = new PermissionSet(PermissionState.Unrestricted);
-                return true;
-            }
-            // If the host wants to participate in policy resolution, then our next option is to ask it for
-            // a grant set
-            else if ((securityManager.Flags & HostSecurityManagerOptions.HostResolvePolicy) == HostSecurityManagerOptions.HostResolvePolicy)
-            {
-                PermissionSet hostGrantSet = securityManager.ResolvePolicy(evidence);
-
-                if (hostGrantSet == null)
-                {
-                    throw new PolicyException(Environment.GetResourceString("Policy_NullHostGrantSet", securityManager.GetType().FullName));
-                }
-
-                // If we're in a homogenous domain, we don't want to allow the host to create multiple
-                // levels of permissions within the domain.  So, if we see the host return something other
-                // than full trust or the homogenous grant set, we reject the grant set.
-                if (AppDomain.CurrentDomain.IsHomogenous)
-                {
-                    // Some hosts, such as ASP.NET, return Nothing as a way of saying that the assembly should
-                    // not be allowed to run in the AppDomain.  Reject that with a specific
-                    // no-execution-allowed-here exception message, rather than the return value validation
-                    // exception message we'd hit below.
-                    if (hostGrantSet.IsEmpty())
-                    {
-                        throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"));
-                    }
-
-                    PermissionSet homogenousGrantSet = AppDomain.CurrentDomain.ApplicationTrust.DefaultGrantSet.PermissionSet;
-                    bool isValidGrantSet = hostGrantSet.IsUnrestricted() ||
-                                           (hostGrantSet.IsSubsetOf(homogenousGrantSet) && homogenousGrantSet.IsSubsetOf(hostGrantSet));
-
-                    if (!isValidGrantSet)
-                    {
-                        throw new PolicyException(Environment.GetResourceString("Policy_GrantSetDoesNotMatchDomain", securityManager.GetType().FullName));
-                    }
-                }
-
-                grantSet = hostGrantSet;
-                return true;
-            }
-            // If we're in a homogenous domain, we can get the grant set directly from the application trust
-            else if (AppDomain.CurrentDomain.IsHomogenous)
-            {
-                grantSet = AppDomain.CurrentDomain.GetHomogenousGrantSet(evidence);
-                return true;
-            }
-            // Otherwise we have no way to figure out what the grant set is
-            else
-            {
-                grantSet = null;
-                return false;
-            }
         }
-#endif // FEATURE_CAS_POLICY
 
 #if FEATURE_PLS
         // Update the PLS used for optimization in the AppDomain: called from the VM
-        [System.Security.SecurityCritical]  // auto-generated
         private static PermissionListSet UpdateAppDomainPLS(PermissionListSet adPLS, PermissionSet grantedPerms, PermissionSet refusedPerms) {
             if (adPLS == null) {
                 adPLS = new PermissionListSet();
index 8f25bda..0ef5afd 100644 (file)
@@ -12,6 +12,7 @@ namespace System.Security {
     using System.Globalization;
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 #if !FEATURE_PAL
     using Microsoft.Win32.SafeHandles;
@@ -40,10 +41,8 @@ namespace System.Security {
         // if this frame contains a call to any WindowsIdentity.Impersonate(), 
         // we save the previous SafeTokenHandles here (in the next two fields)
         // Used during exceptionstackwalks to revert impersonation before calling filters        
-        [System.Security.SecurityCritical] // auto-generated
         [NonSerialized]
         private SafeAccessTokenHandle     m_callerToken; 
-        [System.Security.SecurityCritical] // auto-generated
         [NonSerialized]
         private SafeAccessTokenHandle     m_impToken;                               
 #endif
@@ -56,16 +55,12 @@ namespace System.Security {
 
  
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void IncrementOverridesCount();
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void DecrementOverridesCount();
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void IncrementAssertCount();
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void DecrementAssertCount();
 
@@ -105,14 +100,12 @@ namespace System.Security {
             // we store declarative actions in both fields, so check if they are different
             return (m_restriction != null);
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetAssert(IPermission perm)
         {            
             m_assertions = CreateSingletonSet(perm);
             IncrementAssertCount();
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetAssert(PermissionSet permSet)
         {            
             m_assertions = permSet.Copy();
@@ -125,7 +118,6 @@ namespace System.Security {
             return (fDeclarative) ? m_DeclarativeAssertions : m_assertions;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetAssertAllPossible()
         {
             m_assertAllPossible = true;
@@ -141,19 +133,12 @@ namespace System.Security {
         // D E N Y
         //-----------------------------------------------------------+
     
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetDeny(IPermission perm)
         {
-#if FEATURE_CAS_POLICY
-            BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Deny is only valid in legacy CAS mode");
-#endif // FEATURE_CAS_POLICY
-
             m_denials = CreateSingletonSet(perm);
             IncrementOverridesCount();
-
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetDeny(PermissionSet permSet)
         {
             m_denials = permSet.Copy();
@@ -169,14 +154,12 @@ namespace System.Security {
         // R E S T R I C T
         //-----------------------------------------------------------+
     
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetPermitOnly(IPermission perm)
         {
             m_restriction  = CreateSingletonSet(perm);
             IncrementOverridesCount();
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetPermitOnly(PermissionSet permSet)
         {
             // permSet must not be null
@@ -193,7 +176,6 @@ namespace System.Security {
         //-----------------------------------------------------------+
         // SafeAccessTokenHandle (Impersonation + EH purposes)
         //-----------------------------------------------------------+
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetTokenHandles (SafeAccessTokenHandle callerToken, SafeAccessTokenHandle impToken)
         {
             m_callerToken = callerToken;
@@ -204,7 +186,6 @@ namespace System.Security {
         // R E V E R T
         //-----------------------------------------------------------+
     
-        [System.Security.SecurityCritical]  // auto-generated
         internal void RevertAssert()
         {
             if (m_assertions != null)
@@ -224,7 +205,6 @@ namespace System.Security {
             }
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal void RevertAssertAllPossible()
         {
             if (m_assertAllPossible)
@@ -234,7 +214,6 @@ namespace System.Security {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void RevertDeny()
         {
             if (HasImperativeDenials())
@@ -244,7 +223,6 @@ namespace System.Security {
             }
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal void RevertPermitOnly()
         {
             if (HasImperativeRestrictions())
@@ -254,7 +232,6 @@ namespace System.Security {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void RevertAll()
         {
             RevertAssert();
@@ -270,7 +247,6 @@ namespace System.Security {
 
  
         // This will get called when we hit a FSD while evaluating a demand on the call stack or compressedstack
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
         {
             // imperative security
@@ -283,13 +259,12 @@ namespace System.Security {
             return fContinue;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckDemand2(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh, bool fDeclarative)
         {
             PermissionSet permSet;
             
             // If the demand is null, there is no need to continue
-            Contract.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point");
+            Debug.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point");
 
             // decode imperative
             if (GetPermitOnly(fDeclarative) != null)
@@ -397,7 +372,6 @@ namespace System.Security {
             return SecurityRuntime.StackContinue;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckSetDemand(PermissionSet demandSet,
                                                                    out PermissionSet alteredDemandSet,
                                                                    RuntimeMethodHandleInternal rmh)
@@ -429,7 +403,6 @@ namespace System.Security {
             return fContinue;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckSetDemand2(PermissionSet demandSet,
                                                                    out PermissionSet alteredDemandSet,
                                                                    RuntimeMethodHandleInternal rmh, bool fDeclarative)
index ffdc607..b08fccd 100644 (file)
@@ -120,7 +120,6 @@ namespace System.Security
 
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info==null)
index 15d98c0..5313798 100644 (file)
@@ -34,11 +34,7 @@ namespace System.Security
         AllFlags                        = 0x001F
     }
 
-    [System.Security.SecurityCritical]  // auto-generated_required
     [Serializable]
-#if !FEATURE_CORECLR
-    [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)]
-#endif
     [System.Runtime.InteropServices.ComVisible(true)]
     public class HostSecurityManager {
         public HostSecurityManager () {}
@@ -52,20 +48,6 @@ namespace System.Security
             }
         }
 
-#if FEATURE_CAS_POLICY
-        // provide policy for the AppDomain.
-        [Obsolete("AppDomain policy levels are obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
-        public virtual PolicyLevel DomainPolicy {
-            get {
-                if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
-                {
-                    throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
-                }
-
-                return null;
-            }
-        }
-#endif
         public virtual Evidence ProvideAppDomainEvidence (Evidence inputEvidence) {
             // The default implementation does not modify the input evidence.
             return inputEvidence;
index 93f82a6..592ab53 100644 (file)
@@ -2,19 +2,10 @@
 // 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.Security {
-    using System.Runtime.Remoting;
-    using System;
-    using System.Security.Policy;
-[System.Runtime.InteropServices.ComVisible(true)]
+namespace System.Security
+{
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface IEvidenceFactory
     {
-#if FEATURE_CAS_POLICY        
-        Evidence Evidence
-        {
-            get;
-        }
-#endif // FEATURE_CAS_POLICY
     }
-
 }
index 9915da3..689b3e4 100644 (file)
@@ -8,22 +8,10 @@
 // implement this interface
 //
 
-namespace System.Security  {
-    
-    using System;
-    using System.Security.Util;
-    
-    
-[System.Runtime.InteropServices.ComVisible(true)]
+namespace System.Security
+{
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface ISecurityEncodable
     {
-#if FEATURE_CAS_POLICY
-        SecurityElement ToXml();
-    
-        void FromXml( SecurityElement e );
-#endif // FEATURE_CAS_POLICY
     }
-
 }
-
-
index b1c8d16..567e41e 100644 (file)
@@ -8,21 +8,10 @@
 // implement this interface
 //
 
-namespace System.Security  {
-    
-    using System;
-    using System.Security.Util;
-    using System.Security.Policy;
-    
-    
-[System.Runtime.InteropServices.ComVisible(true)]
+namespace System.Security
+{
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface ISecurityPolicyEncodable
     {
-#if FEATURE_CAS_POLICY
-        SecurityElement ToXml( PolicyLevel level );
-    
-        void FromXml( SecurityElement e, PolicyLevel level );
-#endif // FEATURE_CAS_POLICY
     }
-
 }
index a8779ad..1bc166f 100644 (file)
 //  Extends PermissionSet to allow an associated name and description
 //
 
-namespace System.Security {
-    
+namespace System.Security
+{
     using System;
-    using System.Security.Util;
     using System.Security.Permissions;
-    using System.Runtime.Serialization;
-    using System.Diagnostics.Contracts;
 
-#if !FEATURE_CAS_POLICY
-    using Microsoft.Win32;
-    using System.Collections;
-    using System.Globalization;
-    using System.IO;
-    using System.Reflection;
-    using System.Runtime.InteropServices;
-    using System.Runtime.Remoting;
-    using System.Runtime.Versioning;
-    using System.Text;
-    
-#else // FEATURE_CAS_POLICY
-    
-    using System.Threading;
-
-#endif // FEATURE_CAS_POLICY
-    
     [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class NamedPermissionSet : PermissionSet
     {
-#if FEATURE_CAS_POLICY
-        // The name of this PermissionSet
-        private String m_name;
-        
-        // The description of this PermissionSet
-        private String m_description;
-        [OptionalField(VersionAdded = 2)]                
-        internal String m_descrResource;
-
-        internal NamedPermissionSet()
-            : base()
-        {
-        }
-        
-        public NamedPermissionSet( String name )
-            : base()
-        {
-            CheckName( name );
-            m_name = name;
-        }
-        
-        public NamedPermissionSet( String name, PermissionState state)
-            : base( state )
-        {
-            CheckName( name );
-            m_name = name;
-        }
-        
-        
-        public NamedPermissionSet( String name, PermissionSet permSet )
-            : base( permSet )
-        {
-            CheckName( name );
-            m_name = name;
-        }
-
-        public NamedPermissionSet( NamedPermissionSet permSet )
-            : base( permSet )
-        {
-            m_name = permSet.m_name;
-            m_description = permSet.Description;
-        }
-
-        internal NamedPermissionSet(SecurityElement permissionSetXml)
-            : base(PermissionState.None)
-        {
-            Contract.Assert(permissionSetXml != null);
-            FromXml(permissionSetXml);
-        }
-
-        public String Name {
-            get { return m_name; }
-            set { CheckName( value ); m_name = value; }
-        }
-    
-        private static void CheckName( String name )
-        {
-            if (name == null || name.Equals( "" ))
-                throw new ArgumentException( Environment.GetResourceString( "Argument_NPMSInvalidName" ));
-            Contract.EndContractBlock();
-        }
-        
-        public String Description {
-            get
-            {
-                if(m_descrResource != null)
-                {
-                    m_description = Environment.GetResourceString(m_descrResource);
-                    m_descrResource = null;
-                }
-                return m_description;
-            }
-
-            set
-            {
-                m_description = value;
-                m_descrResource = null;
-            }
-        }
-        
-        public override PermissionSet Copy()
-        {
-            return new NamedPermissionSet( this );
-        }
-        
-        public NamedPermissionSet Copy( String name )
-        {
-            NamedPermissionSet set = new NamedPermissionSet( this );
-            set.Name = name;
-            return set;
-        }
-        
-        public override SecurityElement ToXml()
-        {
-            SecurityElement elem = base.ToXml("System.Security.NamedPermissionSet");
-            // If you hit this assert then most likely you are trying to change the name of this class. 
-            // This is ok as long as you change the hard coded string above and change the assert below.
-            Contract.Assert( this.GetType().FullName.Equals( "System.Security.NamedPermissionSet" ), "Class name changed!" );
-
-            if (m_name != null && !m_name.Equals( "" ))
-            {
-                elem.AddAttribute( "Name", SecurityElement.Escape( m_name ) );
-            }
-            
-            if (Description != null && !Description.Equals( "" ))
-            {
-                elem.AddAttribute( "Description", SecurityElement.Escape( Description ) );
-            }
-            
-            return elem;
-        }
-        
-        public override void FromXml( SecurityElement et )
-        {
-            FromXml( et, false, false );
-        }
-
-        internal override void FromXml( SecurityElement et, bool allowInternalOnly, bool ignoreTypeLoadFailures )
-        {
-            if (et == null)
-                throw new ArgumentNullException( nameof(et) );
-            Contract.EndContractBlock();
-
-            String elem;
-
-            elem = et.Attribute( "Name" );
-            m_name = elem == null ? null : elem;
-
-            elem = et.Attribute( "Description" );
-            m_description = (elem == null ? "" : elem);
-            m_descrResource = null;
-
-            base.FromXml( et, allowInternalOnly, ignoreTypeLoadFailures );
-        }
-
-        internal void FromXmlNameOnly( SecurityElement et )
+        internal static PermissionSet GetBuiltInSet(string name)
         {
-            // This function gets only the name for the permission set, ignoring all other info.
-
-            String elem;
-
-            elem = et.Attribute( "Name" );
-            m_name = (elem == null ? null : elem);
-        }
-
-        // NamedPermissionSet Equals should have the exact semantic as PermissionSet.
-        // We explicitly override them here to make sure that no one accidently
-        // changes this.
-
-        [System.Runtime.InteropServices.ComVisible(false)]
-        public override bool Equals( Object obj )
-        {
-            return base.Equals( obj );
-        }
-
-        [System.Runtime.InteropServices.ComVisible(false)]
-        public override int GetHashCode()
-        {
-            return base.GetHashCode();
-        }
-
-        private static Object s_InternalSyncObject;
-        private static Object InternalSyncObject {
-            get {
-                if (s_InternalSyncObject == null) {
-                    Object o = new Object();
-                    Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
-                }
-                return s_InternalSyncObject;
-            }
-        }
-#else // FEATURE_CAS_POLICY
-
-        internal static PermissionSet GetBuiltInSet(string name) {
             // Used by PermissionSetAttribute to create one of the built-in,
             // immutable permission sets.
-        
             if (name == null)
                 return null;
             else if (name.Equals("FullTrust"))
@@ -264,6 +71,5 @@ namespace System.Security {
             
 
         }
-#endif // !FEATURE_CAS_POLICY
     }
 }
index 7eb13a7..093542a 100644 (file)
@@ -23,6 +23,7 @@ namespace System.Security
     using System.Threading;
     using System.Collections;
     using System.Collections.Generic;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -53,15 +54,13 @@ namespace System.Security
         }
 
 #if FEATURE_PLS
-        [System.Security.SecurityCritical]  // auto-generated
         internal void UpdateDomainPLS (PermissionListSet adPLS) {
             if (adPLS != null && adPLS.m_firstPermSetTriple != null)
                 UpdateDomainPLS(adPLS.m_firstPermSetTriple.GrantSet, adPLS.m_firstPermSetTriple.RefusedSet);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void UpdateDomainPLS (PermissionSet grantSet, PermissionSet deniedSet) {
-            Contract.Assert(m_permSetTriples == null, "m_permSetTriples != null");
+            Debug.Assert(m_permSetTriples == null, "m_permSetTriples != null");
             if (m_firstPermSetTriple == null)
                 m_firstPermSetTriple = new PermissionSetTriple();
 
@@ -76,7 +75,6 @@ namespace System.Security
             UpdateTripleListAndCreateNewTriple(currentTriple, null);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void Terminate(PermissionSetTriple currentTriple, PermissionListSet pls)
         {
 #if FEATURE_COMPRESSEDSTACK
@@ -86,7 +84,6 @@ namespace System.Security
             this.UpdateTripleListAndCreateNewTriple(currentTriple, null);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private bool Update(PermissionSetTriple currentTriple, PermissionListSet pls)
         {
 #if FEATURE_COMPRESSEDSTACK
@@ -95,7 +92,6 @@ namespace System.Security
             return this.UpdatePermissions(currentTriple, pls);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private bool Update(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd)
         {
 #if FEATURE_COMPRESSEDSTACK
@@ -117,7 +113,6 @@ namespace System.Security
         }
 
 #if FEATURE_COMPRESSEDSTACK
-        [System.Security.SecurityCritical]
         private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptorWithResolver fsdWithResolver)
         {
             System.Reflection.Emit.DynamicResolver resolver = fsdWithResolver.Resolver;
@@ -127,7 +122,6 @@ namespace System.Security
         }
 #endif // FEATURE_COMPRESSEDSTACK
 
-        [System.Security.SecurityCritical]  // auto-generated
         private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd, bool fDeclarative)
         {
             // Deny
@@ -187,7 +181,6 @@ namespace System.Security
 
             return false;
         }
-        [System.Security.SecurityCritical]  // auto-generated
         private void Update(PermissionSetTriple currentTriple, PermissionSet in_g, PermissionSet in_r)
         {
 #if FEATURE_COMPRESSEDSTACK
@@ -203,7 +196,6 @@ namespace System.Security
         }
 
         // Called from the VM for HG CS construction        
-        [System.Security.SecurityCritical]  // auto-generated
         private void Update(PermissionSet in_g)
         {
             if (m_firstPermSetTriple == null)
@@ -226,7 +218,6 @@ namespace System.Security
         }
 #endif // FEATURE_COMPRESSEDSTACK
 
-        [System.Security.SecurityCritical]  // auto-generated
         private bool UpdatePermissions(PermissionSetTriple currentTriple, PermissionListSet pls)
         {
             if (pls != null)
@@ -322,7 +313,6 @@ namespace System.Security
             }
         }
 
-[System.Security.SecurityCritical]  // auto-generated
 [System.Runtime.InteropServices.ComVisible(true)]
         // public(internal) interface begins...
         // Creation functions
@@ -370,7 +360,6 @@ namespace System.Security
             return pls;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal PermissionListSet CreateCompressedState(IntPtr unmanagedDCS, out bool bHaltConstruction)
         {
             PermissionListSet pls = new PermissionListSet();
@@ -411,7 +400,6 @@ namespace System.Security
             return pls;
             
         }
-        [System.Security.SecurityCritical]  // auto-generated
         static internal PermissionListSet CreateCompressedState_HG()
         {
             PermissionListSet pls = new PermissionListSet();
@@ -420,11 +408,10 @@ namespace System.Security
         }
 #endif // #if FEATURE_COMPRESSEDSTACK
         // Private Demand evaluation functions - only called from the VM
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckDemandNoThrow(CodeAccessPermission demand)
         {
             // AppDomain permissions - no asserts. So there should only be one triple to work with
-            Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
+            Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
             
 
             
@@ -436,18 +423,16 @@ namespace System.Security
                 
 
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckSetDemandNoThrow(PermissionSet pSet)
         {
             // AppDomain permissions - no asserts. So there should only be one triple to work with
-            Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
+            Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
 
             
             return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet);
         }
 
         // Demand evauation functions
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
         {
             bool bRet = SecurityRuntime.StackContinue;
@@ -467,7 +452,6 @@ namespace System.Security
             return bRet;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckSetDemand(PermissionSet pset , RuntimeMethodHandleInternal rmh)
         {
             PermissionSet unused;
@@ -475,7 +459,6 @@ namespace System.Security
             return SecurityRuntime.StackHalt; //  CS demand check always terminates the stackwalk    
         }
 
-        [System.Security.SecurityCritical]
         internal bool CheckSetDemandWithModification(PermissionSet pset, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh)
         {
             bool bRet = SecurityRuntime.StackContinue;
@@ -503,10 +486,9 @@ namespace System.Security
         ///     Check to see if the PLS satisfies a demand for the special permissions encoded in flags
         /// </summary>
         /// <param name="flags">set of flags to check (See PermissionType)</param>
-        [System.Security.SecurityCritical]  // auto-generated
         private bool CheckFlags(int flags)
         {
-            Contract.Assert(flags != 0, "Invalid permission flag demand");
+            Debug.Assert(flags != 0, "Invalid permission flag demand");
 
             bool check = true;
 
@@ -531,7 +513,6 @@ namespace System.Security
         /// </summary>
         /// <param name="flags">set of flags to check (See PermissionType)</param>
         /// <param name="grantSet">alternate permission set to check</param>
-        [System.Security.SecurityCritical]  // auto-generated
         internal void DemandFlagsOrGrantSet(int flags, PermissionSet grantSet)
         {
             if (CheckFlags(flags))
index 195323b..11ca02a 100644 (file)
@@ -21,6 +21,7 @@ namespace System.Security {
     using System.Text;
     using System.Globalization;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable] 
@@ -36,9 +37,6 @@ namespace System.Security {
 #if FEATURE_SERIALIZATION
     [Serializable]
 #endif
-#if !FEATURE_CORECLR
-    [StrongNameIdentityPermissionAttribute(SecurityAction.InheritanceDemand, Name = "mscorlib", PublicKey = "0x" + AssemblyRef.EcmaPublicKeyFull)]
-#endif
     [System.Runtime.InteropServices.ComVisible(true)]
     public class PermissionSet : ISecurityEncodable, ICollection, IStackWalk
 #if FEATURE_SERIALIZATION
@@ -114,71 +112,13 @@ namespace System.Security {
 
         internal static readonly PermissionSet s_fullTrust = new PermissionSet( true );
 
-#if FEATURE_REMOTING
-        [OnDeserializing]
-        private void OnDeserializing(StreamingContext ctx)
-        {
-            Reset();
-        }   
-
-        [OnDeserialized]
-        private void OnDeserialized(StreamingContext ctx)
-        {
-            if (m_serializedPermissionSet != null)
-            {
-                // Whidbey non X-AD case
-                FromXml(SecurityElement.FromString(m_serializedPermissionSet));
-            }
-            else if (m_normalPermSet != null)
-            {
-                // Everett non X-AD case
-                m_permSet = m_normalPermSet.SpecialUnion(m_unrestrictedPermSet);
-            }
-            else if (m_unrestrictedPermSet != null)
-            {
-                // Everett non X-AD case
-                m_permSet = m_unrestrictedPermSet.SpecialUnion(m_normalPermSet);
-            }
-
-            m_serializedPermissionSet = null;
-            m_normalPermSet = null;
-            m_unrestrictedPermSet = null;
-
-        }
-
-        [OnSerializing]
-        private void OnSerializing(StreamingContext ctx)
-        {
-
-            if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
-            {
-                m_serializedPermissionSet = ToString(); // For v2.x and beyond
-                if (m_permSet != null)
-                    m_permSet.SpecialSplit(ref m_unrestrictedPermSet, ref m_normalPermSet, m_ignoreTypeLoadFailures);
-                m_permSetSaved = m_permSet;
-                m_permSet = null;
-            }
-        }
-#endif // !FEATURE_REMOTING
-
-#if FEATURE_REMOTING || _DEBUG
+#if _DEBUG
         [OnSerialized]
         private void OnSerialized(StreamingContext context)
         {
-#if FEATURE_REMOTING
-            if ((context.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
-            {
-                m_serializedPermissionSet = null;
-                m_permSet = m_permSetSaved;
-                m_permSetSaved = null;
-                m_unrestrictedPermSet = null;
-                m_normalPermSet = null;
-            }
-#else // !FEATURE_REMOTING
-            Contract.Assert(false, "PermissionSet does not support serialization on CoreCLR");
-#endif // !FEATURE_REMOTING
+            Debug.Assert(false, "PermissionSet does not support serialization on CoreCLR");
         }
-#endif // FEATURE_REMOTING || _DEBUG
+#endif // _DEBUG
 
         internal PermissionSet()
         {
@@ -233,19 +173,11 @@ namespace System.Security {
                 {
                     Object obj = m_permSet.GetItem(i);
                     IPermission perm = obj as IPermission;
-#if FEATURE_CAS_POLICY
-                    ISecurityElementFactory elem = obj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
+
                     if (perm != null)
                     {
                         m_permSet.SetItem(i, perm.Copy());
                     }
-#if FEATURE_CAS_POLICY
-                    else if (elem != null)
-                    {
-                        m_permSet.SetItem(i, elem.Copy());
-                    }
-#endif // FEATURE_CAS_POLICY
                 }
             }
         }
@@ -365,19 +297,7 @@ namespace System.Security {
             Object obj = m_permSet.GetItem( index );
             if (obj == null)
                 return null;
-            IPermission perm = obj as IPermission;
-            if (perm != null)
-                return perm;
-#if FEATURE_CAS_POLICY
-            perm = CreatePermission(obj, index);
-#endif // FEATURE_CAS_POLICY
-            if (perm == null)
-                return null;  
-            Contract.Assert( PermissionToken.IsTokenProperlyAssigned( perm, PermissionToken.GetToken( perm ) ),
-                             "PermissionToken was improperly assigned" );
-            Contract.Assert( PermissionToken.GetToken( perm ).m_index == index,
-                             "Assigning permission to incorrect index in tokenbasedset" );
-            return perm;
+            return obj as IPermission;
         }
 
         internal IPermission GetPermission(PermissionToken permToken)
@@ -396,21 +316,6 @@ namespace System.Security {
             return GetPermission(PermissionToken.GetToken( perm ));
         }
 
-#if FEATURE_CAS_POLICY
-        public IPermission GetPermission(Type permClass)
-        {
-            return GetPermissionImpl(permClass);
-        }
-
-        protected virtual IPermission GetPermissionImpl(Type permClass)
-        {
-            if (permClass == null)
-                return null;
-
-            return GetPermission(PermissionToken.FindToken(permClass));
-        }
-#endif // FEATURE_CAS_POLICY
-
         public IPermission SetPermission(IPermission perm)
         {
             return SetPermissionImpl(perm);
@@ -494,29 +399,6 @@ namespace System.Security {
             return (IPermission)m_permSet.RemoveItem( index ); // this cast is safe because the call to GetPermission will guarantee it is an IPermission
         }
 
-#if FEATURE_CAS_POLICY
-        public IPermission RemovePermission(Type permClass)
-        {
-            return RemovePermissionImpl(permClass);
-        }
-
-        protected virtual IPermission RemovePermissionImpl(Type permClass)
-        {
-            if (permClass == null)
-            {
-                return null;
-            }
-
-            PermissionToken permToken = PermissionToken.FindToken(permClass);
-            if (permToken == null)
-            {
-                return null;
-            }
-
-            return RemovePermission(permToken.m_index);
-        }
-#endif // FEATURE_CAS_POLICY
-
         // Make this internal soon.
         internal void SetUnrestricted(bool unrestricted)
         {
@@ -527,12 +409,12 @@ namespace System.Security {
                 m_permSet = null;
             }
         }
-    
+
         public bool IsUnrestricted()
         {
             return m_Unrestricted;
         }
-    
+
         internal enum IsSubsetOfType
         {
             Normal,
@@ -580,7 +462,7 @@ namespace System.Security {
                     IPermission targetPerm = target.GetPermission(i);
 #if _DEBUG                    
                     PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
-                    Contract.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized");
+                    Debug.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized");
 #endif
 
                     if (target.m_Unrestricted)
@@ -692,7 +574,7 @@ namespace System.Security {
 
         internal void CheckDecoded( CodeAccessPermission demandedPerm, PermissionToken tokenDemandedPerm )
         {
-            Contract.Assert( demandedPerm != null, "Expected non-null value" );
+            Debug.Assert( demandedPerm != null, "Expected non-null value" );
 
             if (this.m_allPermissionsDecoded || this.m_permSet == null)
                 return;
@@ -700,7 +582,7 @@ namespace System.Security {
             if (tokenDemandedPerm == null)
                 tokenDemandedPerm = PermissionToken.GetToken( demandedPerm );
 
-            Contract.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" );
+            Debug.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" );
         
             CheckDecoded( tokenDemandedPerm.m_index );
         }
@@ -715,7 +597,7 @@ namespace System.Security {
 
         internal void CheckDecoded(PermissionSet demandedSet)
         {
-            Contract.Assert(demandedSet != null, "Expected non-null value");
+            Debug.Assert(demandedSet != null, "Expected non-null value");
 
             if (this.m_allPermissionsDecoded || this.m_permSet == null)
                 return;
@@ -728,37 +610,6 @@ namespace System.Security {
             }
         }
 
-#if FEATURE_CAS_POLICY
-        static internal void SafeChildAdd( SecurityElement parent, ISecurityElementFactory child, bool copy )
-        {
-            if (child == parent)
-                return;
-            if (child.GetTag().Equals( "IPermission" ) || child.GetTag().Equals( "Permission" ))
-            {
-                parent.AddChild( child );
-            }
-            else if (parent.Tag.Equals( child.GetTag() ))
-            {
-                Contract.Assert( child is SecurityElement, "SecurityElement expected" );
-                SecurityElement elChild = (SecurityElement)child;
-                Contract.Assert( elChild.InternalChildren != null,
-                    "Non-permission elements should have children" );
-                    
-                for (int i = 0; i < elChild.InternalChildren.Count; ++i)
-                {
-                    ISecurityElementFactory current = (ISecurityElementFactory)elChild.InternalChildren[i];
-                    Contract.Assert( !current.GetTag().Equals( parent.Tag ),
-                        "Illegal to insert a like-typed element" );
-                    parent.AddChildNoDuplicates( current );
-                }
-            }
-            else
-            {
-                parent.AddChild( (ISecurityElementFactory)(copy ? child.Copy() : child) );
-            }
-        }
-#endif // FEATURE_CAS_POLICY
-
         internal void InplaceIntersect( PermissionSet other )
         {
             Exception savedException = null;
@@ -796,81 +647,24 @@ namespace System.Security {
             {
                 Object thisObj = this.m_permSet.GetItem( i );
                 IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
 
                 Object otherObj = other.m_permSet.GetItem( i );
                 IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
 
                 if (thisObj == null && otherObj == null)
                     continue;
 
-#if FEATURE_CAS_POLICY
-                if (thisElem != null && otherElem != null)
-                {
-                    // If we already have an intersection node, just add another child
-                    if (thisElem.GetTag().Equals( s_str_PermissionIntersection ) ||
-                        thisElem.GetTag().Equals( s_str_PermissionUnrestrictedIntersection ))
-                    {
-                        Contract.Assert( thisElem is SecurityElement, "SecurityElement expected" );
-                        SafeChildAdd( (SecurityElement)thisElem, otherElem, true );
-                    }
-                    // If either set is unrestricted, intersect the nodes unrestricted
-                    else
-                    {
-                        bool copyOther = true;
-                        if (this.IsUnrestricted())
-                        {
-                            SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
-                            newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) );
-                            SafeChildAdd( newElemUU, thisElem, false );
-                            thisElem = newElemUU;
-                        }
-                        if (other.IsUnrestricted())
-                        {
-                            SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
-                            newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) );
-                            SafeChildAdd( newElemUU, otherElem, true );
-                            otherElem = newElemUU;
-                            copyOther = false;
-                        }
-                        
-                        SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection );
-                        newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
-                        
-                        SafeChildAdd( newElem, thisElem, false );
-                        SafeChildAdd( newElem, otherElem, copyOther );
-                        this.m_permSet.SetItem( i, newElem );
-                    }
-                }
-                else
-#endif // FEATURE_CAS_POLICY
                 if (thisObj == null)
                 {
                     // There is no object in <this>, so intersection is empty except for IUnrestrictedPermissions
                     if (this.IsUnrestricted())
                     {
-#if FEATURE_CAS_POLICY
-                        if (otherElem != null)
-                        {
-                            SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
-                            newElem.AddAttribute( "class", otherElem.Attribute( "class" ) );
-                            SafeChildAdd( newElem, otherElem, true );
-                            this.m_permSet.SetItem( i, newElem );
-                            Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
-                        }
-                        else
-#endif // FEATURE_CAS_POLICY
                         {
                             PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                             if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
                             {
                                 this.m_permSet.SetItem( i, otherPerm.Copy() );
-                                Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+                                Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                             }
                         }
                     }
@@ -879,16 +673,6 @@ namespace System.Security {
                 {
                     if (other.IsUnrestricted())
                     {
-#if FEATURE_CAS_POLICY
-                        if (thisElem != null)
-                        {
-                            SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
-                            newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
-                            SafeChildAdd( newElem, thisElem, false );
-                            this.m_permSet.SetItem( i, newElem );
-                        }
-                        else
-#endif // FEATURE_CAS_POLICY
                         {
                             PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                             if ((token.m_type & PermissionTokenType.IUnrestricted) == 0)
@@ -902,13 +686,6 @@ namespace System.Security {
                 }
                 else
                 {
-#if FEATURE_CAS_POLICY
-                    if (thisElem != null)
-                        thisPerm = this.CreatePermission(thisElem, i);
-                    if (otherElem != null)
-                        otherPerm = other.CreatePermission(otherElem, i);
-#endif // FEATURE_CAS_POLICY
-
                     try
                     {
                         IPermission intersectPerm;
@@ -968,71 +745,23 @@ namespace System.Security {
             {
                 Object thisObj = this.m_permSet.GetItem( i );
                 IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
-
                 Object otherObj = other.m_permSet.GetItem( i );
                 IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
 
                 if (thisObj == null && otherObj == null)
                     continue;
 
-#if FEATURE_CAS_POLICY
-                if (thisElem != null && otherElem != null)
-                {
-                    bool copyOther = true;
-                    bool copyThis = true;
-                    SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection );
-                    newElem.AddAttribute( "class", otherElem.Attribute( "class" ) );
-                    if (this.IsUnrestricted())
-                    {
-                        SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
-                        newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) );
-                        SafeChildAdd( newElemUU, thisElem, true );
-                        copyThis = false;
-                        thisElem = newElemUU;
-                    }
-                    if (other.IsUnrestricted())
-                    {
-                        SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
-                        newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) );
-                        SafeChildAdd( newElemUU, otherElem, true );
-                        copyOther = false;
-                        otherElem = newElemUU;
-                    }
-
-                    SafeChildAdd( newElem, otherElem, copyOther );
-                    SafeChildAdd( newElem, thisElem, copyThis );
-                    pset.m_permSet.SetItem( i, newElem );
-                }
-                else
-#endif // FEATURE_CAS_POLICY
                 if (thisObj == null)
                 {
                     if (this.m_Unrestricted)
                     {
-#if FEATURE_CAS_POLICY
-                        if (otherElem != null)
-                        {
-                            SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
-                            newElem.AddAttribute( "class", otherElem.Attribute( "class" ) );
-                            SafeChildAdd( newElem, otherElem, true );
-                            pset.m_permSet.SetItem( i, newElem );
-                            Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
-                        }
-                        else
-#endif // FEATURE_CAS_POLICY
                         if (otherPerm != null)
                         {
                             PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                             if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
                             {
                                 pset.m_permSet.SetItem( i, otherPerm.Copy() );
-                                Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+                                Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                             }
                         }
                     }
@@ -1041,37 +770,19 @@ namespace System.Security {
                 {
                     if (other.m_Unrestricted)
                     {
-#if FEATURE_CAS_POLICY
-                        if (thisElem != null)
-                        {
-                            SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
-                            newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
-                            SafeChildAdd( newElem, thisElem, true );
-                            pset.m_permSet.SetItem( i, newElem );
-                            Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
-                        }
-                        else
-#endif // FEATURE_CAS_POLICY
                         if (thisPerm != null)
                         {
                             PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                             if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
                             {
                                 pset.m_permSet.SetItem( i, thisPerm.Copy() );
-                                Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+                                Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                             }
                         }
                     }
                 }
                 else
                 {
-#if FEATURE_CAS_POLICY
-                    if (thisElem != null)
-                        thisPerm = this.CreatePermission(thisElem, i);
-                    if (otherElem != null)
-                        otherPerm = other.CreatePermission(otherElem, i);
-#endif // FEATURE_CAS_POLICY
-
                     IPermission intersectPerm;
                     if (thisPerm == null)
                         intersectPerm = otherPerm;
@@ -1080,7 +791,7 @@ namespace System.Security {
                     else
                         intersectPerm = thisPerm.Intersect( otherPerm );
                     pset.m_permSet.SetItem( i, intersectPerm );
-                    Contract.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+                    Debug.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                 }
             }
 
@@ -1102,13 +813,9 @@ namespace System.Security {
             // Quick out conditions, union doesn't change this PermissionSet
             if (other == null || other.FastIsEmpty())
                 return;
-    
-    
-            m_CheckedForNonCas = false;
-            
 
+            m_CheckedForNonCas = false;
 
-                
             this.m_Unrestricted = this.m_Unrestricted || other.m_Unrestricted;
 
             if (this.m_Unrestricted)
@@ -1124,7 +831,7 @@ namespace System.Security {
             int maxMax = -1;            
             if (other.m_permSet != null)
             {
-                maxMax = other.m_permSet.GetMaxUsedIndex();                        
+                maxMax = other.m_permSet.GetMaxUsedIndex();
                 this.CheckSet();
             }
             // Save exceptions until the end
@@ -1134,52 +841,15 @@ namespace System.Security {
             {
                 Object thisObj = this.m_permSet.GetItem( i );
                 IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
 
                 Object otherObj = other.m_permSet.GetItem( i );
                 IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
 
                 if (thisObj == null && otherObj == null)
                     continue;
 
-#if FEATURE_CAS_POLICY
-                if (thisElem != null && otherElem != null)
-                {
-                    if (thisElem.GetTag().Equals( s_str_PermissionUnion ) ||
-                        thisElem.GetTag().Equals( s_str_PermissionUnrestrictedUnion ))
-                    {
-                        Contract.Assert( thisElem is SecurityElement, "SecurityElement expected" );
-                        SafeChildAdd( (SecurityElement)thisElem, otherElem, true );
-                    }
-                    else
-                    {
-                        SecurityElement newElem;
-                        if (this.IsUnrestricted() || other.IsUnrestricted())
-                            newElem = new SecurityElement( s_str_PermissionUnrestrictedUnion );
-                        else
-                            newElem = new SecurityElement( s_str_PermissionUnion );
-                        newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
-                        SafeChildAdd( newElem, thisElem, false );
-                        SafeChildAdd( newElem, otherElem, true );
-                        this.m_permSet.SetItem( i, newElem );
-                    }
-                }
-                else
-#endif // FEATURE_CAS_POLICY
                 if (thisObj == null)
                 {
-#if FEATURE_CAS_POLICY
-                    if (otherElem != null)
-                    {
-                        this.m_permSet.SetItem( i, otherElem.Copy() );
-                    }
-                    else
-#endif // FEATURE_CAS_POLICY
                     if (otherPerm != null)
                     {
                         PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
@@ -1195,13 +865,6 @@ namespace System.Security {
                 }
                 else
                 {
-#if FEATURE_CAS_POLICY
-                    if (thisElem != null)
-                        thisPerm = this.CreatePermission(thisElem, i);
-                    if (otherElem != null)
-                        otherPerm = other.CreatePermission(otherElem, i);
-#endif // FEATURE_CAS_POLICY
-
                     try
                     {
                         IPermission unionPerm;
@@ -1260,82 +923,39 @@ namespace System.Security {
             {
                 Object thisObj = this.m_permSet.GetItem( i );
                 IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
 
                 Object otherObj = other.m_permSet.GetItem( i );
                 IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
 
                 if (thisObj == null && otherObj == null)
                     continue;
 
-#if FEATURE_CAS_POLICY
-                if (thisElem != null && otherElem != null)
-                {
-                    SecurityElement newElem;
-                    if (this.IsUnrestricted() || other.IsUnrestricted())
-                        newElem = new SecurityElement( s_str_PermissionUnrestrictedUnion );
-                    else
-                        newElem = new SecurityElement( s_str_PermissionUnion );
-                    newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
-                    SafeChildAdd( newElem, thisElem, true );
-                    SafeChildAdd( newElem, otherElem, true );
-                    pset.m_permSet.SetItem( i, newElem );
-                }
-                else
-#endif // FEATURE_CAS_POLICY
                 if (thisObj == null)
                 {
-#if FEATURE_CAS_POLICY
-                    if (otherElem != null)
-                    {
-                        pset.m_permSet.SetItem( i, otherElem.Copy() );
-                        Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
-                    }
-                    else
-#endif // FEATURE_CAS_POLICY
                     if (otherPerm != null)
                     {
                         PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                         if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted)
                         {
                             pset.m_permSet.SetItem( i, otherPerm.Copy() );
-                            Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+                            Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                         }
                     }
                 }
                 else if (otherObj == null)
                 {
-#if FEATURE_CAS_POLICY
-                    if (thisElem != null)
-                    {
-                        pset.m_permSet.SetItem( i, thisElem.Copy() );
-                    }
-                    else
-#endif // FEATURE_CAS_POLICY
                     if (thisPerm != null)
                     {
                         PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                         if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted)
                         {
                             pset.m_permSet.SetItem( i, thisPerm.Copy() );
-                            Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+                            Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                         }
                     }
                 }
                 else
                 {
-#if FEATURE_CAS_POLICY
-                    if (thisElem != null)
-                        thisPerm = this.CreatePermission(thisElem, i);
-                    if (otherElem != null)
-                        otherPerm = other.CreatePermission(otherElem, i);
-#endif // FEATURE_CAS_POLICY
-
                     IPermission unionPerm;
                     if(thisPerm == null)
                         unionPerm = otherPerm;
@@ -1344,10 +964,10 @@ namespace System.Security {
                     else
                         unionPerm = thisPerm.Union( otherPerm );
                     pset.m_permSet.SetItem( i, unionPerm );
-                    Contract.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+                    Debug.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                 }
             }
-            
+
             return pset;
         }
 
@@ -1492,7 +1112,6 @@ namespace System.Security {
     
         // Mark this method as requiring a security object on the caller's frame
         // so the caller won't be inlined (which would mess up stack crawling).
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public void Demand()
@@ -1513,7 +1132,6 @@ namespace System.Security {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void DemandNonCAS()
         {
             ContainsNonCodeAccessPermissions();
@@ -1536,7 +1154,6 @@ namespace System.Security {
         // Metadata for this method should be flaged with REQ_SQ so that
         // EE can allocate space on the stack frame for FrameSecurityDescriptor
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public void Assert() 
@@ -1548,7 +1165,6 @@ namespace System.Security {
         // Metadata for this method should be flaged with REQ_SQ so that
         // EE can allocate space on the stack frame for FrameSecurityDescriptor
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         [Obsolete("Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
@@ -1561,7 +1177,6 @@ namespace System.Security {
         // Metadata for this method should be flaged with REQ_SQ so that
         // EE can allocate space on the stack frame for FrameSecurityDescriptor
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public void PermitOnly()
@@ -1588,21 +1203,7 @@ namespace System.Security {
         {
             // Explicitly make a new PermissionSet, rather than copying, since we may have a
             // ReadOnlyPermissionSet which cannot have identity permissions removed from it in a true copy.
-            PermissionSet copy = new PermissionSet(this);
-
-            // There's no easy way to distinguish an identity permission from any other CodeAccessPermission,
-            // so remove them directly.
-#if FEATURE_CAS_POLICY
-            copy.RemovePermission(typeof(GacIdentityPermission));
-#if FEATURE_X509
-            copy.RemovePermission(typeof(PublisherIdentityPermission));
-#endif
-            copy.RemovePermission(typeof(StrongNameIdentityPermission));
-            copy.RemovePermission(typeof(UrlIdentityPermission));
-            copy.RemovePermission(typeof(ZoneIdentityPermission));
-#endif // FEATURE_CAS_POLICY
-
-            return copy;
+            return new PermissionSet(this);
         }
 
         public IEnumerator GetEnumerator()
@@ -1620,13 +1221,6 @@ namespace System.Security {
             return new PermissionSetEnumeratorInternal(this);
         }
 
-#if FEATURE_CAS_POLICY
-        public override String ToString()
-        {
-            return ToXml().ToString();
-        }
-#endif // FEATURE_CAS_POLICY
-
         private void NormalizePermissionSet()
         {
             // This function guarantees that all the permissions are placed at
@@ -1645,12 +1239,6 @@ namespace System.Security {
                 {
                     Object obj = this.m_permSet.GetItem(i);
                     IPermission perm = obj as IPermission;
-#if FEATURE_CAS_POLICY
-                    ISecurityElementFactory elem = obj as ISecurityElementFactory;
-
-                    if (elem != null)
-                        perm = CreatePerm( elem );
-#endif // FEATURE_CAS_POLICY
                     if (perm != null)
                         permSetTemp.SetPermission( perm );
                 }
@@ -1659,29 +1247,6 @@ namespace System.Security {
             this.m_permSet = permSetTemp.m_permSet;
         }
 
-#if FEATURE_CAS_POLICY
-        private bool DecodeXml(byte[] data, HostProtectionResource fullTrustOnlyResources, HostProtectionResource inaccessibleResources )
-        {
-            if (data != null && data.Length > 0)
-            {
-                FromXml( new Parser( data, Tokenizer.ByteTokenEncoding.UnicodeTokens ).GetTopElement() );
-            }
-
-            FilterHostProtectionPermissions(fullTrustOnlyResources, inaccessibleResources);
-
-            // We call this method from unmanaged to code a set we are going to use declaratively.  In
-            // this case, all the lazy evaluation for partial policy resolution is wasted since we'll
-            // need to decode all of these shortly to make the demand for whatever.  Therefore, we
-            // pay that price now so that we can calculate whether all the permissions in the set
-            // implement the IUnrestrictedPermission interface (the common case) for use in some
-            // unmanaged optimizations.
-
-            DecodeAllPermissions();
-
-            return true;
-        }
-#endif // FEATURE_CAS_POLICY
-
         private void DecodeAllPermissions()
         {
             if (m_permSet == null)
@@ -1710,11 +1275,7 @@ namespace System.Security {
             HostProtectionPermission newHpp = (HostProtectionPermission)hpp.Intersect(new HostProtectionPermission(fullTrustOnly));
             if (newHpp == null)
             {
-#if FEATURE_CAS_POLICY
-                RemovePermission(typeof(HostProtectionPermission));
-#else // !FEATURE_CAS_POLICY
                 RemovePermission(HostProtectionPermission.GetTokenIndex());
-#endif // FEATURE_CAS_POLICY
             }
             else if (newHpp.Resources != hpp.Resources)
             {
@@ -1722,539 +1283,8 @@ namespace System.Security {
             }
         }
 
-#if FEATURE_CAS_POLICY
-        public virtual void FromXml( SecurityElement et )
-        {
-            FromXml( et, false, false );
-        }
-
-        internal static bool IsPermissionTag( String tag, bool allowInternalOnly )
-        {
-            if (tag.Equals( s_str_Permission ) ||
-                tag.Equals( s_str_IPermission ))
-            {
-                return true;
-            }
-
-            if (allowInternalOnly &&
-                (tag.Equals( s_str_PermissionUnion ) ||
-                 tag.Equals( s_str_PermissionIntersection ) ||
-                 tag.Equals( s_str_PermissionUnrestrictedIntersection ) ||
-                 tag.Equals( s_str_PermissionUnrestrictedUnion)))
-            {
-                return true;
-            }
-
-            return false;
-        }
-
-        internal virtual void FromXml( SecurityElement et, bool allowInternalOnly, bool ignoreTypeLoadFailures )
-        {
-            if (et == null)
-                throw new ArgumentNullException(nameof(et));
-
-            if (!et.Tag.Equals(s_str_PermissionSet))
-                throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PermissionSet), this.GetType().FullName) );
-            Contract.EndContractBlock();
-
-            Reset();
-            m_ignoreTypeLoadFailures = ignoreTypeLoadFailures;
-            m_allPermissionsDecoded = false;
-            m_Unrestricted = XMLUtil.IsUnrestricted( et );
-
-            if (et.InternalChildren != null)
-            {
-                int childCount = et.InternalChildren.Count;
-                for (int i = 0; i < childCount; ++i)
-                {
-                    SecurityElement elem = (SecurityElement)et.Children[i];
-                
-                    if (IsPermissionTag( elem.Tag, allowInternalOnly ))
-                    {
-                        String className = elem.Attribute( "class" );
-
-                        PermissionToken token;
-                        Object objectToInsert;
-                        
-                        if (className != null)
-                        {
-                            token = PermissionToken.GetToken( className );
-                            if (token == null)
-                            {
-                                objectToInsert = CreatePerm( elem );
-#if _DEBUG
-                                PermissionToken tokenDebug = PermissionToken.GetToken( (IPermission)objectToInsert );
-                                Contract.Assert( tokenDebug != null && (tokenDebug.m_type & PermissionTokenType.BuiltIn) != 0, "This should only be called for built-ins" );
-#endif
-                                if (objectToInsert != null)
-                                {
-                                    Contract.Assert( objectToInsert.GetType().Module.Assembly == System.Reflection.Assembly.GetExecutingAssembly(),
-                                        "PermissionToken.GetToken returned null for non-mscorlib permission" );
-                                    token = PermissionToken.GetToken( (IPermission)objectToInsert );
-                                    Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should always know the permission type when getting a token from an instance" );
-                                }
-                            }
-                            else
-                            {
-                                objectToInsert = elem;
-                            }
-                        }
-                        else
-                        {
-                            IPermission ip = CreatePerm( elem );
-                            if (ip == null)
-                            {
-                                token = null;
-                                objectToInsert = null;
-                            }
-                            else
-                            {
-                                token = PermissionToken.GetToken( ip );
-                                Contract.Assert( PermissionToken.IsTokenProperlyAssigned( ip, token ),
-                                                 "PermissionToken was improperly assigned" );
-                                objectToInsert = ip;
-                            }
-                        }
-
-                        if (token != null && objectToInsert != null)
-                        {
-                            if (m_permSet == null)
-                                m_permSet = new TokenBasedSet();
-
-                            if (this.m_permSet.GetItem( token.m_index ) != null)
-                            {
-                                // If there is already something in that slot, let's union them
-                                // together.
-
-                                IPermission permInSlot;
-
-                                if (this.m_permSet.GetItem( token.m_index ) is IPermission)
-                                    permInSlot = (IPermission)this.m_permSet.GetItem( token.m_index );
-                                else
-                                    permInSlot = CreatePerm( (SecurityElement)this.m_permSet.GetItem( token.m_index ) );
-                                    
-                                if (objectToInsert is IPermission)
-                                    objectToInsert = ((IPermission)objectToInsert).Union( permInSlot );
-                                else
-                                    objectToInsert = CreatePerm( (SecurityElement)objectToInsert ).Union( permInSlot );
-                            }
-
-                            if(m_Unrestricted && objectToInsert is IPermission)
-                                objectToInsert = null;
-
-                            this.m_permSet.SetItem( token.m_index, objectToInsert );
-                        }
-                    }
-                }
-            }
-        }
-
-        internal virtual void FromXml( SecurityDocument doc, int position, bool allowInternalOnly )
-        {
-            if (doc == null)
-                throw new ArgumentNullException(nameof(doc));
-            Contract.EndContractBlock();
-            
-            if (!doc.GetTagForElement( position ).Equals(s_str_PermissionSet))
-                throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PermissionSet), this.GetType().FullName) );
-            
-            Reset();
-            m_allPermissionsDecoded = false;
-            Exception savedException = null;
-            String strUnrestricted = doc.GetAttributeForElement( position, "Unrestricted" );
-            if (strUnrestricted != null)
-                m_Unrestricted = strUnrestricted.Equals( "True" ) || strUnrestricted.Equals( "true" ) || strUnrestricted.Equals( "TRUE" );
-            else
-                m_Unrestricted = false;
-
-            ArrayList childrenIndices = doc.GetChildrenPositionForElement( position );
-            int childCount = childrenIndices.Count;
-            for (int i = 0; i < childCount; ++i)
-            {
-                int childIndex = (int)childrenIndices[i];
-                if (IsPermissionTag( doc.GetTagForElement( childIndex ), allowInternalOnly ))
-                {
-                    try
-                    {
-                        String className = doc.GetAttributeForElement( childIndex, "class" );
-
-                        PermissionToken token;
-                        Object objectToInsert;
-                        
-                        if (className != null)
-                        {
-                            token = PermissionToken.GetToken( className );
-                            if (token == null)
-                            {
-                                objectToInsert = CreatePerm( doc.GetElement( childIndex, true ) );
-
-                                if (objectToInsert != null)
-                                {
-#if _DEBUG
-                                    PermissionToken tokenDebug = PermissionToken.GetToken( (IPermission)objectToInsert );
-                                    Contract.Assert((tokenDebug != null), "PermissionToken.GetToken returned null ");
-                                    Contract.Assert( (tokenDebug.m_type & PermissionTokenType.BuiltIn) != 0, "This should only be called for built-ins" );
-#endif
-                                    Contract.Assert( objectToInsert.GetType().Module.Assembly == System.Reflection.Assembly.GetExecutingAssembly(),
-                                        "PermissionToken.GetToken returned null for non-mscorlib permission" );
-                                    token = PermissionToken.GetToken( (IPermission)objectToInsert );
-                                    Contract.Assert((token != null), "PermissionToken.GetToken returned null ");
-                                    Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should always know the permission type when getting a token from an instance" );
-                                }
-                            }
-                            else
-                            {
-                                objectToInsert = ((ISecurityElementFactory)new SecurityDocumentElement(doc, childIndex)).CreateSecurityElement();
-                            }
-                        }
-                        else
-                        {
-                            IPermission ip = CreatePerm( doc.GetElement( childIndex, true ) );
-                            if (ip == null)
-                            {
-                                token = null;
-                                objectToInsert = null;
-                            }
-                            else
-                            {
-                                token = PermissionToken.GetToken( ip );
-                                Contract.Assert( PermissionToken.IsTokenProperlyAssigned( ip, token ),
-                                                 "PermissionToken was improperly assigned" );
-                                objectToInsert = ip;
-                            }
-                        }
-
-                        if (token != null && objectToInsert != null)
-                        {
-                            if (m_permSet == null)
-                                m_permSet = new TokenBasedSet();
-
-                            IPermission permInSlot = null;
-                            if (this.m_permSet.GetItem( token.m_index ) != null)
-                            {
-                                // If there is already something in that slot, let's union them
-                                // together.
-                                
-                                if (this.m_permSet.GetItem( token.m_index ) is IPermission)
-                                    permInSlot = (IPermission)this.m_permSet.GetItem( token.m_index );
-                                else
-                                    permInSlot = CreatePerm( this.m_permSet.GetItem( token.m_index ) );
-                            }
-
-                            if (permInSlot != null)
-                            {
-                                if (objectToInsert is IPermission)
-                                    objectToInsert = permInSlot.Union((IPermission)objectToInsert);
-                                else
-                                    objectToInsert = permInSlot.Union(CreatePerm( objectToInsert ));
-                            }
-
-                            if(m_Unrestricted && objectToInsert is IPermission)
-                                objectToInsert = null;
-
-                            this.m_permSet.SetItem( token.m_index, objectToInsert );
-                        }
-                    }
-                    catch (Exception e)
-                    {
-#if _DEBUG
-                        if (debug)
-                            DEBUG_WRITE( "error while decoding permission set =\n" + e.ToString() );
-#endif
-                        if (savedException == null)
-                            savedException = e;
-
-                    }
-                }
-            }
-
-            if (savedException != null)
-                throw savedException;
-                
-        }
-
-        private  IPermission CreatePerm(Object obj)
-        {
-            return CreatePerm(obj, m_ignoreTypeLoadFailures);
-        }
-
-        internal static IPermission CreatePerm(Object obj, bool ignoreTypeLoadFailures)
-        {
-            SecurityElement el = obj as SecurityElement;
-            ISecurityElementFactory isf = obj as ISecurityElementFactory;
-            if (el == null && isf != null)
-            {
-                el = isf.CreateSecurityElement();
-            }
-
-            IEnumerator enumerator;
-            IPermission finalPerm = null;
-
-            switch (el.Tag)
-            {
-            case s_str_PermissionUnion:
-                enumerator = el.Children.GetEnumerator();
-                while (enumerator.MoveNext())
-                {
-                    IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures);
-
-                    if (finalPerm != null)
-                        finalPerm = finalPerm.Union( tempPerm );
-                    else
-                        finalPerm = tempPerm;
-                }
-                break;
-
-            case s_str_PermissionIntersection:
-                enumerator = el.Children.GetEnumerator();
-                while (enumerator.MoveNext())
-                {
-                    IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures);
-
-                    if (finalPerm != null)
-                        finalPerm = finalPerm.Intersect( tempPerm );
-                    else
-                        finalPerm = tempPerm;
-
-                    if (finalPerm == null)
-                        return null;
-                }
-                break;
-
-            case s_str_PermissionUnrestrictedUnion:
-                enumerator = el.Children.GetEnumerator();
-                bool first = true;
-                while (enumerator.MoveNext())
-                {
-                    IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures );
-                    
-                    if (tempPerm == null)
-                        continue;
-
-                    PermissionToken token = PermissionToken.GetToken( tempPerm );
-
-                    Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should know the permission type already" );
-
-                    if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
-                    {
-                        finalPerm = XMLUtil.CreatePermission( GetPermissionElement((SecurityElement)enumerator.Current), PermissionState.Unrestricted, ignoreTypeLoadFailures );
-                        first = false;
-                        break;
-                    }
-                    else
-                    {
-                        Contract.Assert( tempPerm != null, "We should only come here if we have a real permission" );
-                        if (first)
-                            finalPerm = tempPerm;
-                        else
-                            finalPerm = tempPerm.Union( finalPerm );
-                        first = false;
-                    }
-                }
-                break;
-
-            case s_str_PermissionUnrestrictedIntersection:
-                enumerator = el.Children.GetEnumerator();
-                while (enumerator.MoveNext())
-                {
-                    IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures );
-                    
-                    if (tempPerm == null)
-                        return null;
-
-                    PermissionToken token = PermissionToken.GetToken( tempPerm );
-
-                    Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should know the permission type already" );
-
-                    if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
-                    {
-                        if (finalPerm != null)
-                            finalPerm = tempPerm.Intersect( finalPerm );
-                        else
-                            finalPerm = tempPerm;
-                    }
-                    else
-                    {
-                        finalPerm = null;
-                    }
-
-                    if (finalPerm == null)
-                        return null;
-                }
-                break;
-
-            case "IPermission":
-            case "Permission":
-                finalPerm = el.ToPermission(ignoreTypeLoadFailures);
-                break;
-
-            default:
-                Contract.Assert( false, "Unrecognized case found during permission creation" );
-                break;
-            }
-
-            return finalPerm;
-        }
-
-        internal IPermission CreatePermission(Object obj, int index)
-        {
-            IPermission perm = CreatePerm(obj);
-            if(perm == null)
-                return null;
-
-            // See if the PermissionSet.m_Unrestricted flag covers this permission
-            if(m_Unrestricted)
-                perm = null;
-
-            // Store the decoded result
-            CheckSet();
-            m_permSet.SetItem(index, perm);
-
-            // Do some consistency checks
-            Contract.Assert(perm == null || PermissionToken.IsTokenProperlyAssigned( perm, PermissionToken.GetToken( perm ) ), "PermissionToken was improperly assigned");
-            if (perm != null)
-            {
-                PermissionToken permToken = PermissionToken.GetToken(perm);
-                if (permToken != null && permToken.m_index != index)
-                    throw new ArgumentException( Environment.GetResourceString( "Argument_UnableToGeneratePermissionSet"));
-            }
-            
-
-            return perm;
-        }
-
-        private static SecurityElement GetPermissionElement( SecurityElement el )
-        {
-            switch (el.Tag)
-            {
-            case "IPermission":
-            case "Permission":
-                return el;
-            }
-            IEnumerator enumerator = el.Children.GetEnumerator();
-            if (enumerator.MoveNext())
-                return GetPermissionElement((SecurityElement)enumerator.Current);
-            Contract.Assert( false, "No Permission or IPermission tag found" );
-            return null;
-        }
-
-        internal static SecurityElement CreateEmptyPermissionSetXml()
-        {
-            
-            SecurityElement elTrunk = new SecurityElement("PermissionSet");
-            elTrunk.AddAttribute( "class", "System.Security.PermissionSet" );
-
-            elTrunk.AddAttribute( "version", "1" );
-            return elTrunk;
-        
-        }
-        // internal helper which takes in the hardcoded permission name to avoid lookup at runtime
-        // can be called from classes that derive from PermissionSet
-        internal SecurityElement ToXml(String permName)
-        {
-            SecurityElement elTrunk = new SecurityElement("PermissionSet");
-            elTrunk.AddAttribute( "class", permName );
-
-            elTrunk.AddAttribute( "version", "1" );
-        
-            PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this);
-    
-            if (m_Unrestricted)
-            {
-                elTrunk.AddAttribute(s_str_Unrestricted, "true" );
-            }
-   
-            while (enumerator.MoveNext())
-            {
-                IPermission perm = (IPermission)enumerator.Current;
-
-                if (!m_Unrestricted)
-                    elTrunk.AddChild( perm.ToXml() );
-            }
-            return elTrunk;
-        }
-
-        internal SecurityElement InternalToXml()
-        {
-            SecurityElement elTrunk = new SecurityElement("PermissionSet");
-            elTrunk.AddAttribute( "class", this.GetType().FullName);
-            elTrunk.AddAttribute( "version", "1" );
-        
-            if (m_Unrestricted)
-            {
-                elTrunk.AddAttribute(s_str_Unrestricted, "true" );
-            }
-    
-            if (this.m_permSet != null)
-            {
-                int maxIndex = this.m_permSet.GetMaxUsedIndex();
-
-                for (int i = m_permSet.GetStartingIndex(); i <= maxIndex; ++i)
-                {
-                    Object obj = this.m_permSet.GetItem( i );
-                    if (obj != null)
-                    {
-                        if (obj is IPermission)
-                        {
-                            if (!m_Unrestricted)
-                                elTrunk.AddChild( ((IPermission)obj).ToXml() );
-                        }
-                        else
-                        {
-                            elTrunk.AddChild( (SecurityElement)obj );
-                        }
-                    }
-
-                }
-            }
-            return elTrunk ;
-        }
-
-        public virtual SecurityElement ToXml()
-        {
-            // If you hit this assert then most likely you are trying to change the name of this class. 
-            // This is ok as long as you change the hard coded string above and change the assert below.
-            Contract.Assert( this.GetType().FullName.Equals( "System.Security.PermissionSet" ), "Class name changed! Was: System.Security.PermissionSet Should be:" +  this.GetType().FullName);
-                        
-            return ToXml("System.Security.PermissionSet");   
-        }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CAS_POLICY && FEATURE_SERIALIZATION
-        internal
-        byte[] EncodeXml()
-        {
-            MemoryStream ms = new MemoryStream();
-            BinaryWriter writer = new BinaryWriter( ms, Encoding.Unicode );
-            writer.Write( this.ToXml().ToString() );
-            writer.Flush();
-
-            // The BinaryWriter is going to place
-            // two bytes indicating a Unicode stream.
-            // We want to chop those off before returning
-            // the bytes out.
-
-            ms.Position = 2;
-            int countBytes = (int)ms.Length - 2;
-            byte[] retval = new byte[countBytes];
-            ms.Read( retval, 0, retval.Length );
-            return retval;
-        }
-
-        /// <internalonly/>
-        [Obsolete("This method is obsolete and shoud no longer be used.")]
-        public static byte[] ConvertPermissionSet(String inFormat, byte[] inData, String outFormat)
-        {
-            // Since this method has shipped and is public, we cannot remove it without being a breaking change
-            throw new NotImplementedException();
-        }
-#endif
-
         // Determines whether the permission set contains any non-code access
         // security permissions.
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         public bool ContainsNonCodeAccessPermissions()
         {
             if (m_CheckedForNonCas)
@@ -2324,59 +1354,11 @@ namespace System.Security {
             return pset;
         }
 
-#if FEATURE_CAS_POLICY
-        private const String s_str_PermissionSet = "PermissionSet";
-        private const String s_str_Permission    = "Permission";
-        private const String s_str_IPermission    = "IPermission";
-        private const String s_str_Unrestricted  = "Unrestricted";
-        private const String s_str_PermissionUnion = "PermissionUnion";
-        private const String s_str_PermissionIntersection = "PermissionIntersection";
-        private const String s_str_PermissionUnrestrictedUnion = "PermissionUnrestrictedUnion";
-        private const String s_str_PermissionUnrestrictedIntersection = "PermissionUnrestrictedIntersection";
-
-        // This method supports v1.x security attrbutes only - we'll require legacy CAS policy mode
-        // to be enabled for that to work.
-#pragma warning disable 618
-        // Internal routine used to setup a special security context
-        // for creating and manipulated security custom attributes
-        // that we use when the Runtime is hosted.
-        [System.Security.SecurityCritical]  // auto-generated
-        private static void SetupSecurity()
-        {
-            PolicyLevel level = PolicyLevel.CreateAppDomainLevel();
-
-            CodeGroup rootGroup = new UnionCodeGroup( new AllMembershipCondition(), level.GetNamedPermissionSet( "Execution" ) );
-
-            StrongNamePublicKeyBlob microsoftBlob = new StrongNamePublicKeyBlob( AssemblyRef.MicrosoftPublicKeyFull );
-            CodeGroup microsoftGroup = new UnionCodeGroup( new StrongNameMembershipCondition( microsoftBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) );
-
-            StrongNamePublicKeyBlob ecmaBlob = new StrongNamePublicKeyBlob( AssemblyRef.EcmaPublicKeyFull );
-            CodeGroup ecmaGroup = new UnionCodeGroup( new StrongNameMembershipCondition( ecmaBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) );
-
-            CodeGroup gacGroup = new UnionCodeGroup( new GacMembershipCondition(), level.GetNamedPermissionSet( "FullTrust" ) );
-
-            rootGroup.AddChild( microsoftGroup );
-            rootGroup.AddChild( ecmaGroup );
-            rootGroup.AddChild( gacGroup );
-
-            level.RootCodeGroup = rootGroup;
-
-            try
-            {
-                AppDomain.CurrentDomain.SetAppDomainPolicy( level );
-            }
-            catch (PolicyException)
-            {
-            }
-        }
-#endif
-#pragma warning restore 618
-
         // Internal routine used by CreateSerialized to add a permission to the set
         private static void MergePermission(IPermission perm, bool separateCasFromNonCas, ref PermissionSet casPset, ref PermissionSet nonCasPset)
         {
-            Contract.Assert(casPset == null || !casPset.IsReadOnly);
-            Contract.Assert(nonCasPset == null || !nonCasPset.IsReadOnly);
+            Debug.Assert(casPset == null || !casPset.IsReadOnly);
+            Debug.Assert(nonCasPset == null || !nonCasPset.IsReadOnly);
 
             if (perm == null)
                 return;
@@ -2402,9 +1384,6 @@ namespace System.Security {
         }
 
         // Converts an array of SecurityAttributes to a PermissionSet
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         private static byte[] CreateSerialized(Object[] attrs,
                                                bool serialize,
                                                ref byte[] nonCasBlob,
@@ -2422,7 +1401,7 @@ namespace System.Security {
             for (int i = 0; i < attrs.Length; i++)
             {
 #pragma warning disable 618
-                Contract.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions");
+                Debug.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions");
 #pragma warning restore 618
                 if (attrs[i] is PermissionSetAttribute)
                 {
@@ -2451,7 +1430,7 @@ namespace System.Security {
                     MergePermission(perm, serialize, ref casPset, ref nonCasPset);
                 }
             }
-            Contract.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true");
+            Debug.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true");
 
             //
             // Filter HostProtection permission.  In the VM, some optimizations are done based upon these
@@ -2475,22 +1454,8 @@ namespace System.Security {
                     nonCasPset = null;
             }
 
-            // Serialize the set(s).
-            byte[] casBlob = null;
-            nonCasBlob = null;
-#if FEATURE_CAS_POLICY
-            if(serialize)
-            {
-                if(casPset != null)
-                    casBlob = casPset.EncodeXml();
-                if(nonCasPset != null)
-                    nonCasBlob = nonCasPset.EncodeXml();
-            }
-#else // FEATURE_CAS_POLICY
-            Contract.Assert(!serialize, "Cannot serialize permission sets on CoreCLR");
-#endif // FEATURE_CAS_POLICY
-
-            return casBlob;
+            Debug.Assert(!serialize, "Cannot serialize permission sets on CoreCLR");
+            return null;
         }
 
 #if FEATURE_SERIALIZATION
@@ -2502,7 +1467,6 @@ namespace System.Security {
         }
 #endif
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static void RevertAssert()
         {
@@ -2512,7 +1476,7 @@ namespace System.Security {
 
         internal static PermissionSet RemoveRefusedPermissionSet(PermissionSet assertSet, PermissionSet refusedSet, out bool bFailedToCompress)
         {
-            Contract.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here");
+            Debug.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here");
             PermissionSet retPs = null;
             bFailedToCompress = false;
             if (assertSet == null)
@@ -2568,7 +1532,7 @@ namespace System.Security {
 
         internal static void RemoveAssertedPermissionSet(PermissionSet demandSet, PermissionSet assertSet, out PermissionSet alteredDemandSet)
         {
-            Contract.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted");
+            Debug.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted");
             alteredDemandSet = null;
             
             PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(demandSet);
index 55b56cb..7b234e9 100644 (file)
@@ -81,20 +81,6 @@ namespace System.Security
                     enm.Current = perm;
                     return true;
                 }
-
-#if FEATURE_CAS_POLICY
-                SecurityElement elem = obj as SecurityElement;
-
-                if (elem != null)
-                {
-                    perm = m_permSet.CreatePermission(elem, enm.Index);
-                    if (perm != null)
-                    {
-                        enm.Current = perm;
-                        return true;
-                    }
-                }
-#endif // FEATURE_CAS_POLICY
             }
             return false;
         }
index f1527ac..56eb229 100644 (file)
@@ -19,6 +19,7 @@ namespace System.Security
     using System.Security;
     using System.Security.Permissions;
     using System.Runtime.InteropServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
 
@@ -53,7 +54,6 @@ namespace System.Security
 
         private PermissionToken ZoneToken
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (s_zoneToken == null)
@@ -63,7 +63,6 @@ namespace System.Security
         }            
         private PermissionToken UrlToken
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (s_urlToken == null)
@@ -71,7 +70,6 @@ namespace System.Security
                 return s_urlToken;
             }
         }            
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool Update(PermissionSetTriple psTriple, out PermissionSetTriple retTriple)
         {
             retTriple = null;
@@ -86,13 +84,12 @@ namespace System.Security
             return false;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
         {
             PermissionSetTriple retTriple = null;
             if (in_a != null)
             {
-                Contract.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null");
+                Debug.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null");
                 // if we're already asserting in_a, nothing to do
                 if (in_a.IsSubsetOf(AssertSet))
                     return null;
@@ -128,7 +125,6 @@ namespace System.Security
             }
             return retTriple;
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal void UpdateGrant(PermissionSet in_g, out ZoneIdentityPermission z,out UrlIdentityPermission u)
         {
             z = null;
@@ -145,7 +141,6 @@ namespace System.Security
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void UpdateGrant(PermissionSet in_g)
         {
             if (in_g != null)
@@ -168,7 +163,6 @@ namespace System.Security
         } 
 
         
-        [System.Security.SecurityCritical]  // auto-generated
         static bool CheckAssert(PermissionSet pSet, CodeAccessPermission demand, PermissionToken permToken)
         {
             if (pSet != null)
@@ -193,7 +187,6 @@ namespace System.Security
             return SecurityRuntime.StackContinue;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static bool CheckAssert(PermissionSet assertPset, PermissionSet demandSet, out PermissionSet newDemandSet)
         {
             newDemandSet = null;
@@ -210,7 +203,6 @@ namespace System.Security
         }
 
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
         {
             if (CheckAssert(AssertSet, demand, permToken) == SecurityRuntime.StackHalt)
@@ -222,7 +214,6 @@ namespace System.Security
 
             return SecurityRuntime.StackContinue;
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckSetDemand(PermissionSet demandSet , out PermissionSet alteredDemandset, RuntimeMethodHandleInternal rmh)
         {
             alteredDemandset = null;
@@ -239,18 +230,16 @@ namespace System.Security
 
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckDemandNoThrow(CodeAccessPermission demand, PermissionToken permToken)
         {
-            Contract.Assert(AssertSet == null, "AssertSet not null");
+            Debug.Assert(AssertSet == null, "AssertSet not null");
 #pragma warning disable 618
             return CodeAccessSecurityEngine.CheckHelper(GrantSet, RefusedSet, demand, permToken, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false);
 #pragma warning restore 618
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckSetDemandNoThrow(PermissionSet demandSet)
         {
-            Contract.Assert(AssertSet == null, "AssertSet not null");
+            Debug.Assert(AssertSet == null, "AssertSet not null");
 
 #pragma warning disable 618
             return CodeAccessSecurityEngine.CheckSetHelper(GrantSet, RefusedSet, demandSet, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false);
@@ -263,7 +252,6 @@ namespace System.Security
         ///     If the triple asserts for one of the bits in the flags, it is zeroed out.
         /// </remarks>
         /// <param name="flags">set of flags to check (See PermissionType)</param>
-        [System.Security.SecurityCritical]  // auto-generated
         internal bool CheckFlags(ref int flags)
         {
             if (AssertSet != null)
index 1896dd9..5c6a322 100644 (file)
@@ -2,7 +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.
 
-namespace System.Security {
+namespace System.Security
+{
     using System;
     using System.Security.Util;
     using System.Security.Permissions;
@@ -11,6 +12,7 @@ namespace System.Security {
     using System.Threading;
     using System.Globalization;
     using System.Runtime.CompilerServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Flags]
@@ -34,7 +36,6 @@ namespace System.Security {
             _info = CultureInfo.InvariantCulture.TextInfo;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public int Compare(Object a, Object b)
         {
             String strA = a as String;
@@ -90,20 +91,13 @@ namespace System.Security {
     internal sealed class PermissionToken : ISecurityEncodable
     {
         private static readonly PermissionTokenFactory s_theTokenFactory;
-#if FEATURE_CAS_POLICY
-        private static volatile ReflectionPermission s_reflectPerm = null;
-#endif // FEATURE_CAS_POLICY
-
         private const string c_mscorlibName = System.CoreLib.Name;
         internal int    m_index;
         internal volatile PermissionTokenType m_type;
-#if FEATURE_CAS_POLICY
-        internal String m_strTypeName;
-#endif // FEATURE_CAS_POLICY
         static internal TokenBasedSet s_tokenSet = new TokenBasedSet();
 
         internal static bool IsMscorlibClassName (string className) {
-            Contract.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(),
+            Debug.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(),
                 System.CoreLib.Name+" name mismatch" );
 
             // If the class name does not look like a fully qualified name, we cannot simply determine if it's 
@@ -119,11 +113,7 @@ namespace System.Security {
 
             // Search for the string 'mscorlib' in the classname. If we find it, we will conservatively assume it's an mscorlib.dll type and load it.
             for (int i = index; i < className.Length; i++) {
-#if FEATURE_CORECLR
-                if (className[i] == 's' || className[i] == 'S') 
-#else
-                if (className[i] == 'm' || className[i] == 'M') 
-#endif                 
+                if (className[i] == 's' || className[i] == 'S')
                 {
                     if (String.Compare(className, i, c_mscorlibName, 0, c_mscorlibName.Length, StringComparison.OrdinalIgnoreCase) == 0)
                         return true;
@@ -145,39 +135,14 @@ namespace System.Security {
         {
             m_index = index;
             m_type = type;
-#if FEATURE_CAS_POLICY
-            m_strTypeName = strTypeName;
-#endif // FEATURE_CAS_POLICY
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public static PermissionToken GetToken(Type cls)
         {
             if (cls == null)
                 return null;
-            
-#if FEATURE_CAS_POLICY
-            if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null)
-            {
-                if (s_reflectPerm == null)
-                    s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted);
-                s_reflectPerm.Assert();
-                MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic );
-                Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" );
-
-                // GetTokenIndex needs to be invoked without any security checks, since doing a security check
-                // will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the
-                // token.
-                RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo;
-                Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo");
-                int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null);
-                return s_theTokenFactory.BuiltInGetToken(token, null, cls);
-            }
-            else
-#endif // FEATURE_CAS_POLICY
-            {
-                return s_theTokenFactory.GetToken(cls, null);
-            }
+
+            return s_theTokenFactory.GetToken(cls, null);
         }
 
         public static PermissionToken GetToken(IPermission perm)
@@ -193,82 +158,6 @@ namespace System.Security {
                 return s_theTokenFactory.GetToken(perm.GetType(), perm);
         }
 
-#if FEATURE_CAS_POLICY
-        public static PermissionToken GetToken(String typeStr)
-        {
-            return GetToken( typeStr, false );
-        }
-
-#if _DEBUG
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
-        private static void GetTokenHelper(String typeStr)
-        {
-            new PermissionSet(PermissionState.Unrestricted).Assert();
-            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-            Type type = RuntimeTypeHandle.GetTypeByName( typeStr.Trim().Replace( '\'', '\"' ), ref stackMark);
-            Contract.Assert( (type == null) || (type.Module.Assembly != System.Reflection.Assembly.GetExecutingAssembly()) || (typeStr.IndexOf("mscorlib", StringComparison.Ordinal) < 0),
-                "We should not go through this path for mscorlib based permissions" );
-        }
-#endif
-
-        public static PermissionToken GetToken(String typeStr, bool bCreateMscorlib)
-        {
-            if (typeStr == null)
-                return null;
-
-            if (IsMscorlibClassName( typeStr ))
-            {
-                if (!bCreateMscorlib)
-                {
-                    return null;
-                }
-                else
-                {
-                    return FindToken( Type.GetType( typeStr ) );
-                }
-            }
-            else
-            {
-                PermissionToken token = s_theTokenFactory.GetToken(typeStr);
-#if _DEBUG
-                GetTokenHelper(typeStr);
-#endif
-                return token;
-            }
-        }
-
-        [SecuritySafeCritical]
-        public static PermissionToken FindToken( Type cls )
-        {
-            if (cls == null)
-                return null;
-             
-#if FEATURE_CAS_POLICY
-            if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null)
-            {
-                if (s_reflectPerm == null)
-                    s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted);
-                s_reflectPerm.Assert();
-                MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic );
-                Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" );
-
-                // GetTokenIndex needs to be invoked without any security checks, since doing a security check
-                // will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the
-                // token.
-                RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo;
-                Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo");
-                int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null);
-                return s_theTokenFactory.BuiltInGetToken(token, null, cls);
-            }
-            else
-#endif // FEATURE_CAS_POLICY
-            {
-                return s_theTokenFactory.FindToken( cls );
-            }
-        }
-#endif // FEATURE_CAS_POLICY
-
         public static PermissionToken FindTokenByIndex( int i )
         {
             return s_theTokenFactory.FindTokenByIndex( i );
@@ -289,41 +178,6 @@ namespace System.Security {
 
             return true;
         }
-
-#if FEATURE_CAS_POLICY
-        public SecurityElement ToXml()
-        {
-            Contract.Assert( (m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when ToXml is called" );
-            SecurityElement elRoot = new SecurityElement( "PermissionToken" );
-            if ((m_type & PermissionTokenType.BuiltIn) != 0)
-                elRoot.AddAttribute( "Index", "" + this.m_index );
-            else
-                elRoot.AddAttribute( "Name", SecurityElement.Escape( m_strTypeName ) );
-            elRoot.AddAttribute("Type", m_type.ToString("F"));
-            return elRoot;
-        }
-
-        public void FromXml(SecurityElement elRoot)
-        {
-            // For the most part there is no parameter checking here since this is an
-            // internal class and the serialization/deserialization path is controlled.
-
-            if (!elRoot.Tag.Equals( "PermissionToken" ))
-                Contract.Assert( false, "Tried to deserialize non-PermissionToken element here" );
-
-            String strName = elRoot.Attribute( "Name" );
-            PermissionToken realToken;
-            if (strName != null)
-                realToken = GetToken( strName, true );
-            else
-                realToken = FindTokenByIndex( Int32.Parse( elRoot.Attribute( "Index" ), CultureInfo.InvariantCulture ) );
-            
-            this.m_index = realToken.m_index;
-            this.m_type = (PermissionTokenType) Enum.Parse(typeof(PermissionTokenType), elRoot.Attribute("Type"));
-            Contract.Assert((this.m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when FromXml is called.");
-            this.m_strTypeName = realToken.m_strTypeName;
-        }
-#endif // FEATURE_CAS_POLICY
     }
 
     // Package access only
@@ -357,33 +211,6 @@ namespace System.Security {
             m_indexTable = new Hashtable(size);
         }
 
-#if FEATURE_CAS_POLICY
-        [SecuritySafeCritical]
-        internal PermissionToken FindToken( Type cls )
-        {
-            IntPtr typePtr = cls.TypeHandle.Value;
-            PermissionToken tok = (PermissionToken)m_handleTable[typePtr];
-
-            if (tok != null)
-                return tok;
-
-            if (m_tokenTable == null)
-                return null;
-
-            tok = (PermissionToken)m_tokenTable[cls.AssemblyQualifiedName];
-
-            if (tok != null)
-            {
-                lock (this)
-                {
-                    m_handleTable.Add(typePtr, tok);
-                }
-            }
-
-            return tok;
-        }
-#endif // FEATURE_CAS_POLICY
-
         internal PermissionToken FindTokenByIndex( int i )
         {
             PermissionToken token;
@@ -400,10 +227,9 @@ namespace System.Security {
             return token;
         }
 
-        [SecuritySafeCritical]
         internal PermissionToken GetToken(Type cls, IPermission perm)
         {
-            Contract.Assert( cls != null, "Must pass in valid type" );
+            Debug.Assert( cls != null, "Must pass in valid type" );
 
             IntPtr typePtr = cls.TypeHandle.Value;
             object tok = m_handleTable[typePtr];
@@ -459,22 +285,16 @@ namespace System.Security {
             {
                 if (perm != null)
                 {
-                    Contract.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" );
+                    Debug.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" );
                     ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted;
-#if FEATURE_CAS_POLICY
-                    ((PermissionToken)tok).m_strTypeName = perm.GetType().AssemblyQualifiedName;
-#endif // FEATURE_CAS_POLICY
                 }
                 else
                 {
-                    Contract.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" );
+                    Debug.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" );
                     if (cls.GetInterface(s_unrestrictedPermissionInferfaceName) != null)
                         ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted;
                     else
                         ((PermissionToken)tok).m_type = PermissionTokenType.Normal;
-#if FEATURE_CAS_POLICY
-                    ((PermissionToken)tok).m_strTypeName = cls.AssemblyQualifiedName;
-#endif // FEATURE_CAS_POLICY
                 }
             }
 
index 8208ed3..567fe51 100644 (file)
@@ -56,7 +56,6 @@ namespace System.Security.Permissions {
             return str;
         }
 
-        [SecuritySafeCritical]
         public override string ToString()
         {
             // SafeCritical: we're not storing path information in the strings, so exposing them out is fine ...
@@ -103,7 +102,6 @@ namespace System.Security.Permissions {
             AddPathList( flag, pathList );
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AddPathList( EnvironmentPermissionAccess flag, String pathList )
         {
             VerifyFlag( flag );
@@ -204,7 +202,6 @@ namespace System.Security.Permissions {
         //
         //------------------------------------------------------
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsSubsetOf(IPermission target)
         {
             if (target == null)
@@ -232,7 +229,6 @@ namespace System.Security.Permissions {
             }
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override IPermission Intersect(IPermission target)
         {
             if (target == null)
@@ -275,7 +271,6 @@ namespace System.Security.Permissions {
             return intersectPermission;
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override IPermission Union(IPermission other)
         {
             if (other == null)
@@ -334,61 +329,8 @@ namespace System.Security.Permissions {
                 }
     
             }
-            return copy;   
+            return copy;
         }
-       
-#if FEATURE_CAS_POLICY
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.EnvironmentPermission" );
-            if (!IsUnrestricted())
-            {
-                if (this.m_read != null && !this.m_read.IsEmpty())
-                {
-                    esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) );
-                }
-                if (this.m_write != null && !this.m_write.IsEmpty())
-                {
-                    esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) );
-                }
-            }
-            else
-            {
-                esd.AddAttribute( "Unrestricted", "true" );
-            }
-            return esd;
-        }
-
-        public override void FromXml(SecurityElement esd)
-        {
-            CodeAccessPermission.ValidateElement( esd, this );
-
-            String et;
-            
-            if (XMLUtil.IsUnrestricted(esd))
-            {
-                m_unrestricted = true;
-                return;
-            }
-
-            m_unrestricted = false;
-            m_read = null;
-            m_write = null;
-
-            et = esd.Attribute( "Read" );
-            if (et != null)
-            {
-                m_read = new EnvironmentStringExpressionSet( et );
-            }
-            
-            et = esd.Attribute( "Write" );
-            if (et != null)
-            {
-                m_write = new EnvironmentStringExpressionSet( et );
-            }
-    
-        }
-#endif // FEATURE_CAS_POLICY
 
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
index 6d6c221..98a7d54 100644 (file)
@@ -66,22 +66,6 @@ namespace System.Security.Permissions {
             return new FileDialogPermission(this.access);
         }
 
-#if FEATURE_CAS_POLICY
-        public override void FromXml(SecurityElement esd) {
-            CodeAccessPermission.ValidateElement(esd, this);
-            if (XMLUtil.IsUnrestricted(esd)) {
-                SetUnrestricted(true);
-                return;
-            }
-
-            access = FileDialogPermissionAccess.None;
-
-            string accessXml = esd.Attribute("Access");
-            if (accessXml != null)
-                access = (FileDialogPermissionAccess)Enum.Parse(typeof(FileDialogPermissionAccess), accessXml);
-        }
-#endif // FEATURE_CAS_POLICY
-
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex() {
             return FileDialogPermission.GetTokenIndex();
@@ -152,21 +136,6 @@ namespace System.Security.Permissions {
             }
         }
 
-#if FEATURE_CAS_POLICY
-        public override SecurityElement ToXml() {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileDialogPermission" );
-            if (!IsUnrestricted()) {
-                if (access != FileDialogPermissionAccess.None) {
-                    esd.AddAttribute("Access", Enum.GetName(typeof(FileDialogPermissionAccess), access));
-                }
-            }
-            else {
-                esd.AddAttribute("Unrestricted", "true");
-            }
-            return esd;
-        }
-#endif // FEATURE_CAS_POLICY
-
         public override IPermission Union(IPermission target) {
             if (target == null) {
                 return this.Copy();
@@ -177,7 +146,7 @@ namespace System.Security.Permissions {
 
             FileDialogPermission operand = (FileDialogPermission)target;
             return new FileDialogPermission(access | operand.Access);
-        }        
+        }
 
         static void VerifyAccess(FileDialogPermissionAccess access) {
             if ((access & ~FileDialogPermissionAccess.OpenSave) != 0 ) {
index b524318..34b9f1e 100644 (file)
@@ -2,13 +2,11 @@
 // 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.Security.Permissions {
+namespace System.Security.Permissions
+{
     using System;
     using System.Runtime.CompilerServices;
     using System.Runtime.InteropServices;
-#if FEATURE_CAS_POLICY
-    using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
     using System.Security.AccessControl;
     using System.Security.Util;
     using System.IO;
@@ -16,11 +14,12 @@ namespace System.Security.Permissions {
     using System.Globalization;
     using System.Runtime.Serialization;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
-[Serializable]
+    [Serializable]
     [Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public enum FileIOPermissionAccess
     {
         NoAccess = 0x00,
@@ -30,9 +29,8 @@ namespace System.Security.Permissions {
         PathDiscovery = 0x08,
         AllAccess = 0x0F,
     }
-    
-    
-[System.Runtime.InteropServices.ComVisible(true)]
+
+    [System.Runtime.InteropServices.ComVisible(true)]
     [Serializable]
     sealed public class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
     {
@@ -62,7 +60,6 @@ namespace System.Security.Permissions {
             }
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public FileIOPermission( FileIOPermissionAccess access, String path )
         {
             VerifyAccess( access );
@@ -71,7 +68,6 @@ namespace System.Security.Permissions {
             AddPathList( access, pathList, false, true, false );
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public FileIOPermission( FileIOPermissionAccess access, String[] pathList )
         {
             VerifyAccess( access );
@@ -79,24 +75,6 @@ namespace System.Security.Permissions {
             AddPathList( access, pathList, false, true, false );
         }
 
-#if FEATURE_MACL
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String path )
-        {
-            VerifyAccess( access );
-        
-            String[] pathList = new String[] { path };
-            AddPathList( access, control, pathList, false, true, false );
-        }
-        
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList )
-            : this( access, control, pathList, true, true )
-        {
-        }
-#endif
-
-        [System.Security.SecurityCritical]  // auto-generated
         internal FileIOPermission( FileIOPermissionAccess access, String[] pathList, bool checkForDuplicates, bool needFullPath )
         {
             VerifyAccess( access );
@@ -104,16 +82,6 @@ namespace System.Security.Permissions {
             AddPathList( access, pathList, checkForDuplicates, needFullPath, true );
         }
 
-#if FEATURE_MACL
-        [System.Security.SecurityCritical]  // auto-generated
-        internal FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates, bool needFullPath )
-        {
-            VerifyAccess( access );
-        
-            AddPathList( access, control, pathList, checkForDuplicates, needFullPath, true );
-        }
-#endif
-
         public void SetPathList( FileIOPermissionAccess access, String path )
         {
             String[] pathList;
@@ -135,7 +103,6 @@ namespace System.Security.Permissions {
             SetPathList( access, AccessControlActions.None, pathList, checkForDuplicates );
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal void SetPathList( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates )
         {
             VerifyAccess( access );
@@ -152,26 +119,13 @@ namespace System.Security.Permissions {
             if ((access & FileIOPermissionAccess.PathDiscovery) != 0)
                 m_pathDiscovery = null;
 
-#if FEATURE_MACL
-            if ((control & AccessControlActions.View) != 0)
-                m_viewAcl = null;
-
-            if ((control & AccessControlActions.Change) != 0)
-                m_changeAcl = null;
-#else
             m_viewAcl = null;
             m_changeAcl = null;
-#endif
-            
             m_unrestricted = false;
-#if FEATURE_MACL
-            AddPathList( access, control, pathList, checkForDuplicates, true, true );
-#else
+
             AddPathList( access, pathList, checkForDuplicates, true, true );
-#endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AddPathList( FileIOPermissionAccess access, String path )
         {
             String[] pathList;
@@ -182,19 +136,16 @@ namespace System.Security.Permissions {
             AddPathList( access, pathList, false, true, false );
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AddPathList( FileIOPermissionAccess access, String[] pathList )
         {
             AddPathList( access, pathList, true, true, true );
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void AddPathList( FileIOPermissionAccess access, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList )
         {
             AddPathList( access, AccessControlActions.None, pathListOrig, checkForDuplicates, needFullPath, copyPathList );
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList)
         {
             if (pathListOrig == null)
@@ -267,29 +218,8 @@ namespace System.Security.Permissions {
                 }
                 m_pathDiscovery.AddExpressions( pathArrayList, checkForDuplicates);
             }
-
-#if FEATURE_MACL
-            if ((control & AccessControlActions.View) != 0)
-            {
-                if (m_viewAcl == null)
-                {
-                    m_viewAcl = new FileIOAccess();
-                }
-                m_viewAcl.AddExpressions( pathArrayList, checkForDuplicates);
-            }
-
-            if ((control & AccessControlActions.Change) != 0)
-            {
-                if (m_changeAcl == null)
-                {
-                    m_changeAcl = new FileIOAccess();
-                }
-                m_changeAcl.AddExpressions( pathArrayList, checkForDuplicates);
-            }
-#endif
         }
-        
-        [SecuritySafeCritical]
+
         public String[] GetPathList( FileIOPermissionAccess access )
         {
             VerifyAccess( access );
@@ -335,7 +265,6 @@ namespace System.Security.Permissions {
             
             return null;
         }
-        
 
         public FileIOPermissionAccess AllLocalFiles
         {
@@ -785,123 +714,6 @@ namespace System.Security.Permissions {
             }
             return copy;   
         }
-   
-#if FEATURE_CAS_POLICY
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileIOPermission" );
-            if (!IsUnrestricted())
-            {
-                if (this.m_read != null && !this.m_read.IsEmpty())
-                {
-                    esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) );
-                }
-                if (this.m_write != null && !this.m_write.IsEmpty())
-                {
-                    esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) );
-                }
-                if (this.m_append != null && !this.m_append.IsEmpty())
-                {
-                    esd.AddAttribute( "Append", SecurityElement.Escape( m_append.ToString() ) );
-                }
-                if (this.m_pathDiscovery != null && !this.m_pathDiscovery.IsEmpty())
-                {
-                    esd.AddAttribute( "PathDiscovery", SecurityElement.Escape( m_pathDiscovery.ToString() ) );
-                }
-                if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty())
-                {
-                    esd.AddAttribute( "ViewAcl", SecurityElement.Escape( m_viewAcl.ToString() ) );
-                }
-                if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty())
-                {
-                    esd.AddAttribute( "ChangeAcl", SecurityElement.Escape( m_changeAcl.ToString() ) );
-                }
-
-            }
-            else
-            {
-                esd.AddAttribute( "Unrestricted", "true" );
-            }
-            return esd;
-        }
-        
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public override void FromXml(SecurityElement esd)
-        {
-            CodeAccessPermission.ValidateElement( esd, this );
-            String et;
-            
-            if (XMLUtil.IsUnrestricted(esd))
-            {
-                m_unrestricted = true;
-                return;
-            }
-    
-            
-            m_unrestricted = false;
-            
-            et = esd.Attribute( "Read" );
-            if (et != null)
-            {
-                m_read = new FileIOAccess( et );
-            }
-            else
-            {
-                m_read = null;
-            }
-            
-            et = esd.Attribute( "Write" );
-            if (et != null)
-            {
-                m_write = new FileIOAccess( et );
-            }
-            else
-            {
-                m_write = null;
-            }
-    
-            et = esd.Attribute( "Append" );
-            if (et != null)
-            {
-                m_append = new FileIOAccess( et );
-            }
-            else
-            {
-                m_append = null;
-            }
-
-            et = esd.Attribute( "PathDiscovery" );
-            if (et != null)
-            {
-                m_pathDiscovery = new FileIOAccess( et );
-                m_pathDiscovery.PathDiscovery = true;
-            }
-            else
-            {
-                m_pathDiscovery = null;
-            }
-
-            et = esd.Attribute( "ViewAcl" );
-            if (et != null)
-            {
-                m_viewAcl = new FileIOAccess( et );
-            }
-            else
-            {
-                m_viewAcl = null;
-            }
-
-            et = esd.Attribute( "ChangeAcl" );
-            if (et != null)
-            {
-                m_changeAcl = new FileIOAccess( et );
-            }
-            else
-            {
-                m_changeAcl = null;
-            }
-        }
-#endif // FEATURE_CAS_POLICY
 
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
@@ -993,19 +805,9 @@ namespace System.Security.Permissions {
         /// 
         /// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify
         /// </summary>
-        [System.Security.SecuritySafeCritical]
         internal static void QuickDemand(FileIOPermissionAccess access, string fullPath, bool checkForDuplicates = false, bool needFullPath = false)
         {
-#if FEATURE_CAS_POLICY
-            if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
-            {
-                new FileIOPermission(access, new string[] { fullPath }, checkForDuplicates, needFullPath).Demand();
-            }
-            else
-#endif
-            {
-                EmulateFileIOPermissionChecks(fullPath);
-            }
+            EmulateFileIOPermissionChecks(fullPath);
         }
 
         /// <summary>
@@ -1018,67 +820,19 @@ namespace System.Security.Permissions {
         /// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify
         /// 
         /// </summary>
-        [System.Security.SecuritySafeCritical]
         internal static void QuickDemand(FileIOPermissionAccess access, string[] fullPathList, bool checkForDuplicates = false, bool needFullPath = true)
         {
-#if FEATURE_CAS_POLICY
-            if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
+            foreach (string fullPath in fullPathList)
             {
-                new FileIOPermission(access, fullPathList, checkForDuplicates, needFullPath).Demand();
-            }
-            else
-#endif
-            {
-                foreach (string fullPath in fullPathList)
-                {
-                    EmulateFileIOPermissionChecks(fullPath);
-                }
+                EmulateFileIOPermissionChecks(fullPath);
             }
         }
 
-        [System.Security.SecuritySafeCritical]
         internal static void QuickDemand(PermissionState state)
         {
             // Should be a no-op without CAS
-#if FEATURE_CAS_POLICY
-            if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
-            {
-                new FileIOPermission(state).Demand();
-            }
-#endif
         }
 
-#if FEATURE_MACL
-        [System.Security.SecuritySafeCritical]
-        internal static void QuickDemand(FileIOPermissionAccess access, AccessControlActions control, string fullPath, bool checkForDuplicates = false, bool needFullPath = true)
-        {
-            if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
-            {
-                new FileIOPermission(access, control, new string[] { fullPath }, checkForDuplicates, needFullPath).Demand();
-            }
-            else
-            {
-                EmulateFileIOPermissionChecks(fullPath);
-            }
-        }
-
-        [System.Security.SecuritySafeCritical]
-        internal static void QuickDemand(FileIOPermissionAccess access, AccessControlActions control, string[] fullPathList, bool checkForDuplicates = true, bool needFullPath = true)
-        {
-            if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
-            {
-                new FileIOPermission(access, control, fullPathList, checkForDuplicates, needFullPath).Demand();
-            }
-            else
-            {
-                foreach (string fullPath in fullPathList)
-                {
-                    EmulateFileIOPermissionChecks(fullPath);
-                }
-            }
-        }
-#endif
-
         /// <summary>
         /// Perform the additional path checks that would normally happen when creating a FileIOPermission object.
         /// </summary>
@@ -1142,7 +896,6 @@ namespace System.Security.Permissions {
             m_pathDiscovery = pathDiscovery;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public FileIOAccess( String value )
         {
             if (value == null)
@@ -1197,7 +950,6 @@ namespace System.Security.Permissions {
             m_pathDiscovery = operand.m_pathDiscovery;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public void AddExpressions(ArrayList values, bool checkForDuplicates)
         {
             m_allFiles = false;
@@ -1248,7 +1000,6 @@ namespace System.Security.Permissions {
             return new FileIOAccess( this );
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public FileIOAccess Union( FileIOAccess operand )
         {
             if (operand == null)
@@ -1256,7 +1007,7 @@ namespace System.Security.Permissions {
                 return this.IsEmpty() ? null : this.Copy();
             }
             
-            Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+            Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
 
             if (this.m_allFiles || operand.m_allFiles)
             {
@@ -1266,7 +1017,6 @@ namespace System.Security.Permissions {
             return new FileIOAccess( this.m_set.Union( operand.m_set ), false, this.m_allLocalFiles || operand.m_allLocalFiles, this.m_pathDiscovery );
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public FileIOAccess Intersect( FileIOAccess operand )
         {
             if (operand == null)
@@ -1274,7 +1024,7 @@ namespace System.Security.Permissions {
                 return null;
             }
             
-            Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+            Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
 
             if (this.m_allFiles)
             {
@@ -1336,7 +1086,6 @@ namespace System.Security.Permissions {
             return new FileIOAccess( intersectionSet, false, this.m_allLocalFiles && operand.m_allLocalFiles, this.m_pathDiscovery );
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public bool IsSubsetOf( FileIOAccess operand )
         {
             if (operand == null)
@@ -1349,7 +1098,7 @@ namespace System.Security.Permissions {
                 return true;
             }
             
-            Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+            Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
 
             if (!((m_pathDiscovery && this.m_set.IsSubsetOfPathDiscovery( operand.m_set )) || this.m_set.IsSubsetOf( operand.m_set )))
             {
@@ -1393,7 +1142,6 @@ namespace System.Security.Permissions {
             }
         }
         
-        [SecuritySafeCritical]
         public override String ToString()
         {
             // SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
@@ -1422,7 +1170,6 @@ namespace System.Security.Permissions {
             }
         }
 
-        [SecuritySafeCritical]
         public String[] ToStringArray()
         {
             // SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
@@ -1430,18 +1177,16 @@ namespace System.Security.Permissions {
             return m_set.UnsafeToStringArray();
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal static extern bool IsLocalDrive(String path);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool Equals(Object obj)
         {
             FileIOAccess operand = obj as FileIOAccess;
             if(operand == null)
                 return (IsEmpty() && obj == null);
-            Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+            Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
             if(m_pathDiscovery)
             {
                 if(this.m_allFiles && operand.m_allFiles)
index 5c209af..f93f26d 100644 (file)
@@ -5,9 +5,6 @@
 namespace System.Security.Permissions
 {
     using System;
-#if FEATURE_CAS_POLICY
-    using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
     using System.Globalization;
 
     [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
@@ -92,19 +89,6 @@ namespace System.Security.Permissions
             return this.Copy();
         }
 
-#if FEATURE_CAS_POLICY
-        public override SecurityElement ToXml()
-        {
-            SecurityElement securityElement = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.GacIdentityPermission" );
-            return securityElement;
-        }
-
-        public override void FromXml(SecurityElement securityElement)
-        {
-            CodeAccessPermission.ValidateElement(securityElement, this);
-        }
-#endif // FEATURE_CAS_POLICY
-
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
         {
index 85be61a..c4facbb 100644 (file)
@@ -41,11 +41,9 @@ namespace System.Security.Permissions
     [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )] 
     [System.Runtime.InteropServices.ComVisible(true)]
     [Serializable]
-#if FEATURE_CORECLR
     // This needs to be in the asmmeta to enable SecAnnotate to successfully resolve and run the security rules. It gets marked
     // as internal by BCLRewriter so we are simply marking it as FriendAccessAllowed so it stays in the asmmeta.
     [System.Runtime.CompilerServices.FriendAccessAllowedAttribute]
-#endif // FEATURE_CORECLR
 #pragma warning disable 618
     sealed public class HostProtectionAttribute : CodeAccessSecurityAttribute
 #pragma warning restore 618
@@ -247,38 +245,6 @@ namespace System.Security.Permissions
             return new HostProtectionPermission(m_resources);
         }
 
-#if FEATURE_CAS_POLICY
-        //------------------------------------------------------
-        //
-        // XML
-        //
-        //------------------------------------------------------
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, this.GetType().FullName );
-            if(IsUnrestricted())
-                esd.AddAttribute( "Unrestricted", "true" );
-            else
-                esd.AddAttribute( "Resources", XMLUtil.BitFieldEnumToString( typeof( HostProtectionResource ), Resources ) );
-            return esd;
-        }
-
-        public override void FromXml(SecurityElement esd)
-        {
-            CodeAccessPermission.ValidateElement( esd, this );
-            if (XMLUtil.IsUnrestricted( esd ))
-                Resources = HostProtectionResource.All;
-            else
-            {
-                String resources = esd.Attribute( "Resources" );
-                if (resources == null)
-                    Resources = HostProtectionResource.None;
-                else
-                    Resources = (HostProtectionResource)Enum.Parse( typeof( HostProtectionResource ), resources );
-            }
-        }
-#endif // FEATURE_CAS_POLICY
-
         //------------------------------------------------------
         //
         // OBJECT OVERRIDES
index 1e11b4a..42bc648 100644 (file)
@@ -158,19 +158,6 @@ namespace System.Security.Permissions {
         {
             return BuiltInPermissionIndex.IsolatedStorageFilePermissionIndex;
         }
-
-        //------------------------------------------------------
-        //
-        // IsolatedStoragePermission OVERRIDES
-        //
-        //------------------------------------------------------
-#if FEATURE_CAS_POLICY
-        [System.Runtime.InteropServices.ComVisible(false)]
-        public override SecurityElement ToXml()
-        {
-            return base.ToXml( "System.Security.Permissions.IsolatedStorageFilePermission" );
-        }
-#endif // FEATURE_CAS_POLICY
     }
 }
 
index 308adbd..9f09a37 100644 (file)
@@ -32,9 +32,6 @@ namespace System.Security.Permissions {
 
     
     [Serializable]
-#if !FEATURE_CORECLR
-    [SecurityPermissionAttribute( SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true )]
-#endif
     [System.Runtime.InteropServices.ComVisible(true)]
     abstract public class IsolatedStoragePermission
            : CodeAccessPermission, IUnrestrictedPermission
@@ -182,93 +179,5 @@ namespace System.Security.Permissions {
         //------------------------------------------------------
         internal static long min(long x,long y) {return x>y?y:x;}
         internal static long max(long x,long y) {return x<y?y:x;}
-
-#if FEATURE_CAS_POLICY
-        //------------------------------------------------------
-        //
-        // PUBLIC ENCODING METHODS
-        //
-        //------------------------------------------------------
-        
-        private const String _strUserQuota   = "UserQuota";
-        private const String _strMachineQuota   = "MachineQuota";
-        private const String _strExpiry  = "Expiry";
-        private const String _strPermDat = "Permanent";
-
-        public override SecurityElement ToXml()
-        {
-            return ToXml ( this.GetType().FullName );
-        }
-    
-        internal SecurityElement ToXml(String permName)
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, permName );
-            if (!IsUnrestricted())
-            {
-                esd.AddAttribute( "Allowed", Enum.GetName( typeof( IsolatedStorageContainment ), m_allowed ) );
-                if (m_userQuota>0)
-                {
-                    esd.AddAttribute(_strUserQuota, (m_userQuota).ToString(CultureInfo.InvariantCulture)) ;
-                }
-                if (m_machineQuota>0)
-                {
-                    esd.AddAttribute(_strMachineQuota, (m_machineQuota).ToString(CultureInfo.InvariantCulture)) ;
-                }
-                if (m_expirationDays>0)
-                {
-                    esd.AddAttribute( _strExpiry, (m_expirationDays).ToString(CultureInfo.InvariantCulture)) ;
-                }
-                if (m_permanentData)
-                {
-                    esd.AddAttribute(_strPermDat, (m_permanentData).ToString()) ;
-                }
-            }
-            else
-            {
-                esd.AddAttribute( "Unrestricted", "true" );
-            }
-            return esd;
-        }
-    
-
-        public override void FromXml(SecurityElement esd)
-        {
-            CodeAccessPermission.ValidateElement( esd, this );
-
-            m_allowed = IsolatedStorageContainment.None;    // default if no match
-
-            if (XMLUtil.IsUnrestricted(esd))
-            {
-                m_allowed = IsolatedStorageContainment.UnrestrictedIsolatedStorage;
-            }
-            else
-            {
-                String allowed = esd.Attribute( "Allowed" );
-
-                if (allowed != null)
-                    m_allowed = (IsolatedStorageContainment)Enum.Parse( typeof( IsolatedStorageContainment ), allowed );
-            }
-                    
-            if (m_allowed == IsolatedStorageContainment.UnrestrictedIsolatedStorage)
-            {
-                m_userQuota = Int64.MaxValue;
-                m_machineQuota = Int64.MaxValue;
-                m_expirationDays = Int64.MaxValue ;
-                m_permanentData = true;
-            }
-            else 
-            {
-                String param;
-                param = esd.Attribute (_strUserQuota) ;
-                m_userQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ;
-                param = esd.Attribute (_strMachineQuota) ;
-                m_machineQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ;
-                param = esd.Attribute (_strExpiry) ;
-                m_expirationDays = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ;
-                param = esd.Attribute (_strPermDat) ;
-                m_permanentData = param != null ? (Boolean.Parse(param)) : false ;
-            }
-        }
-#endif // FEATURE_CAS_POLICY
     }
 }
index f14fb0d..b6ac8ec 100644 (file)
@@ -8,9 +8,6 @@ namespace System.Security.Permissions
     using System.Security.Util;
     using System.IO;
     using System.Security.Policy;
-#if FEATURE_MACL
-    using System.Security.AccessControl;
-#endif
     using System.Text;
     using System.Threading;
     using System.Runtime.InteropServices;
@@ -23,11 +20,9 @@ namespace System.Security.Permissions
     using System.Diagnostics.Contracts;
     
     [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CAS_POLICY
+    [System.Runtime.InteropServices.ComVisible(true)]
     // The csharp compiler requires these types to be public, but they are not used elsewhere.
     [Obsolete("SecurityAction is no longer accessible to application code.")]
-#endif
     public enum SecurityAction
     {
         // Demand permission of all caller
@@ -62,14 +57,11 @@ namespace System.Security.Permissions
         RequestRefuse = 10,
     }
 
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] 
-[System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CAS_POLICY
+    [Serializable]
+    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] 
+    [System.Runtime.InteropServices.ComVisible(true)]
     // The csharp compiler requires these types to be public, but they are not used elsewhere.
     [Obsolete("SecurityAttribute is no longer accessible to application code.")]
-#endif
     public abstract class SecurityAttribute : System.Attribute
     {
         /// <internalonly/>
@@ -96,7 +88,6 @@ namespace System.Security.Permissions
 
         abstract public IPermission CreatePermission();
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static unsafe IntPtr FindSecurityAttributeTypeHandle(String typeName)
         {
             PermissionSet.s_fullTrust.Assert();
@@ -108,13 +99,11 @@ namespace System.Security.Permissions
         }
     }
 
-[Serializable]
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] 
-[System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CAS_POLICY
+    [Serializable]
+    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] 
+    [System.Runtime.InteropServices.ComVisible(true)]
     // The csharp compiler requires these types to be public, but they are not used elsewhere.
     [Obsolete("CodeAccessSecurityAttribute is no longer accessible to application code.")]
-#endif
     public abstract class CodeAccessSecurityAttribute : SecurityAttribute
     {
         protected CodeAccessSecurityAttribute( SecurityAction action )
@@ -307,12 +296,6 @@ namespace System.Security.Permissions
                     perm.SetPathList( FileIOPermissionAccess.Append, m_append );
                 if (m_pathDiscovery != null)
                     perm.SetPathList( FileIOPermissionAccess.PathDiscovery, m_pathDiscovery );
-#if FEATURE_MACL
-                if (m_viewAccess != null)
-                    perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.View, new String[] { m_viewAccess }, false );
-                if (m_changeAccess != null)
-                    perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.Change, new String[] { m_changeAccess }, false );
-#endif
 
                 perm.AllFiles = m_allFiles;
                 perm.AllLocalFiles = m_allLocalFiles;
@@ -384,59 +367,6 @@ namespace System.Security.Permissions
         }
     }
 
-#if !FEATURE_CORECLR
-    // PrincipalPermissionAttribute currently derives from
-    // CodeAccessSecurityAttribute, even though it's not related to code access
-    // security. This is because compilers are currently looking for
-    // CodeAccessSecurityAttribute as a direct parent class rather than
-    // SecurityAttribute as the root class.
-    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false )] 
-[System.Runtime.InteropServices.ComVisible(true)]
-    [Serializable]
-    sealed public class PrincipalPermissionAttribute : CodeAccessSecurityAttribute
-    {
-        private String m_name = null;
-        private String m_role = null;
-        private bool m_authenticated = true;
-    
-        public PrincipalPermissionAttribute( SecurityAction action )
-            : base( action )
-        {
-        }
-        
-        public String Name
-        {
-            get { return m_name; }
-            set { m_name = value; }
-        }
-        
-        public String Role
-        {
-            get { return m_role; }
-            set { m_role = value; }
-        }
-        
-        public bool Authenticated
-        {
-            get { return m_authenticated; }
-            set { m_authenticated = value; }
-        }
-        
-        
-        public override IPermission CreatePermission()
-        {
-            if (m_unrestricted)
-            {
-                return new PrincipalPermission( PermissionState.Unrestricted );
-            }
-            else
-            {
-                return new PrincipalPermission( m_name, m_role, m_authenticated );
-            }
-        }
-    }
-#endif // !FEATURE_CORECLR
-
     [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] 
 [System.Runtime.InteropServices.ComVisible(true)]
     [Serializable]
@@ -570,24 +500,16 @@ namespace System.Security.Permissions
                     perm.SetPathList( RegistryPermissionAccess.Write, m_write );
                 if (m_create != null)
                     perm.SetPathList( RegistryPermissionAccess.Create, m_create );
-#if FEATURE_MACL
-                if (m_viewAcl != null)
-                    perm.SetPathList( AccessControlActions.View, m_viewAcl );
-                if (m_changeAcl != null)
-                    perm.SetPathList( AccessControlActions.Change, m_changeAcl );
-#endif
                 return perm;
             }
         }
     }
 
     [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] 
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     [Serializable]
-#if !FEATURE_CAS_POLICY
     // The csharp compiler requires these types to be public, but they are not used elsewhere.
     [Obsolete("SecurityPermissionAttribute is no longer accessible to application code.")]
-#endif
     sealed public class SecurityPermissionAttribute : CodeAccessSecurityAttribute
     {
         private SecurityPermissionFlag m_flag = SecurityPermissionFlag.NoFlags;
@@ -662,7 +584,7 @@ namespace System.Security.Permissions
             set { m_flag = value ? m_flag | SecurityPermissionFlag.RemotingConfiguration : m_flag & ~SecurityPermissionFlag.RemotingConfiguration; }
         }
 
-[System.Runtime.InteropServices.ComVisible(true)]
+        [System.Runtime.InteropServices.ComVisible(true)]
         public bool Infrastructure {
             get { return (m_flag & SecurityPermissionFlag.Infrastructure) != 0; }
             set { m_flag = value ? m_flag | SecurityPermissionFlag.Infrastructure : m_flag & ~SecurityPermissionFlag.Infrastructure; }
@@ -893,170 +815,6 @@ namespace System.Security.Permissions
             }
         }
     }
-    
-#if FEATURE_X509 && FEATURE_CAS_POLICY
-    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] 
-[System.Runtime.InteropServices.ComVisible(true)]
-    [Serializable]
-    sealed public class PublisherIdentityPermissionAttribute : CodeAccessSecurityAttribute
-    {
-        private String m_x509cert = null;
-        private String m_certFile = null;
-        private String m_signedFile = null;
-    
-        public PublisherIdentityPermissionAttribute( SecurityAction action )
-            : base( action )
-        {
-            m_x509cert = null;
-            m_certFile = null;
-            m_signedFile = null;
-        }
-
-        public String X509Certificate {
-            get { return m_x509cert; }
-            set { m_x509cert = value; }
-        }
-        
-        public String CertFile {
-            get { return m_certFile; }
-            set { m_certFile = value; }
-        }
-        
-        public String SignedFile {
-            get { return m_signedFile; }
-            set { m_signedFile = value; }
-        }
-
-        public override IPermission CreatePermission()
-        {
-            if (m_unrestricted)
-            {
-                return new PublisherIdentityPermission( PermissionState.Unrestricted );
-            }
-            else
-            {
-                if (m_x509cert != null)
-                {
-                    return new PublisherIdentityPermission( new X509Certificate( System.Security.Util.Hex.DecodeHexString( m_x509cert ) ) );
-                }
-                else if (m_certFile != null)
-                {
-                    return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile( m_certFile ) );
-                }
-                else if (m_signedFile != null)
-                {
-                    return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile( m_signedFile ) );
-                }
-                else
-                {
-                    return new PublisherIdentityPermission( PermissionState.None );
-                }
-            }
-        }
-    }
-#endif // #if FEATURE_X509 && FEATURE_CAS_POLICY
-
-#if !FEATURE_CORECLR                              
-[Serializable]
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor
-     | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly,
-    AllowMultiple=true, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
-    public abstract class IsolatedStoragePermissionAttribute : CodeAccessSecurityAttribute
-    {
-        /// <internalonly/>
-        internal long m_userQuota;
-#if false
-        /// <internalonly/>
-        internal long m_machineQuota;
-        /// <internalonly/>
-        internal long m_expirationDays;
-        /// <internalonly/>
-        internal bool m_permanentData;
-#endif
-        /// <internalonly/>
-        internal IsolatedStorageContainment m_allowed;
-        protected IsolatedStoragePermissionAttribute(SecurityAction action) : base(action)
-        {
-        }
-
-        // properties
-        public long UserQuota {
-            set{
-                m_userQuota = value;
-            }
-            get{
-                return m_userQuota;
-            }
-        }
-#if false
-        internal long MachineQuota {
-            set{
-                m_machineQuota = value;
-            }
-            get{
-                return m_machineQuota;
-            }
-        }
-        internal long ExpirationDays {
-            set{
-                m_expirationDays = value;
-            }
-            get{
-                return m_expirationDays;
-            }
-        }
-        internal bool PermanentData {
-            set{
-                m_permanentData = value;
-            }
-            get{
-                return m_permanentData;
-            }
-        }
-#endif
-        public IsolatedStorageContainment UsageAllowed {
-            set{
-                m_allowed = value;
-            }
-            get{
-                return m_allowed;
-            }
-        }
-
-    }
-
-    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor
-     | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly,
-    AllowMultiple=true, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
-    [Serializable]
-    sealed public class IsolatedStorageFilePermissionAttribute : IsolatedStoragePermissionAttribute
-    {
-        public IsolatedStorageFilePermissionAttribute(SecurityAction action) : base(action)
-        {
-
-        }
-        public override IPermission CreatePermission()
-        {
-            IsolatedStorageFilePermission p;
-            if (m_unrestricted) {
-                p = new IsolatedStorageFilePermission
-                        (PermissionState.Unrestricted);
-            } else {
-                p = new IsolatedStorageFilePermission(PermissionState.None);
-                p.UserQuota      = m_userQuota;
-                p.UsageAllowed   = m_allowed;
-#if false
-                p.PermanentData  = m_permanentData;
-                p.MachineQuota   = m_machineQuota;
-                p.ExpirationDays = m_expirationDays;
-#endif
-            }
-            return p;
-        }
-    }
-#endif // FEATURE_CORECLR
 
     [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] 
 [System.Runtime.InteropServices.ComVisible(true)]
@@ -1109,66 +867,12 @@ namespace System.Security.Permissions
             return null;
         }
 
-#if FEATURE_CAS_POLICY
-        private PermissionSet BruteForceParseStream(Stream stream)
-        {
-            Encoding[] encodings = new Encoding[] { Encoding.UTF8, 
-                                                    Encoding.ASCII, 
-                                                    Encoding.Unicode };
-
-            StreamReader reader = null;
-            Exception exception = null;
-
-            for (int i = 0; reader == null && i < encodings.Length; ++i)
-            {
-                try
-                {
-                    stream.Position = 0;
-                    reader = new StreamReader( stream, encodings[i] );
-
-                    return ParsePermissionSet( new Parser(reader) );
-                }
-                catch (Exception e1)
-                {
-                    if (exception == null)
-                        exception = e1;
-                }
-            }
-
-            throw exception;
-        }
-
-        private PermissionSet ParsePermissionSet(Parser parser)
-        {
-            SecurityElement e = parser.GetTopElement();
-            PermissionSet permSet = new PermissionSet( PermissionState.None );
-            permSet.FromXml( e );
-
-            return permSet;
-        }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CAS_POLICY
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#endif
         public PermissionSet CreatePermissionSet()
         {
             if (m_unrestricted)
                 return new PermissionSet( PermissionState.Unrestricted );
             else if (m_name != null)
-#if FEATURE_CAS_POLICY
-                return PolicyLevel.GetBuiltInSet( m_name );
-#else
                 return NamedPermissionSet.GetBuiltInSet( m_name );
-#endif // FEATURE_CAS_POLICY
-#if FEATURE_CAS_POLICY
-            else if (m_xml != null)
-                return ParsePermissionSet( new Parser(m_xml.ToCharArray()) );
-            else if (m_hex != null)
-                return BruteForceParseStream( new MemoryStream(Util.Hex.DecodeHexString(m_hex)) );
-            else if (m_file != null)
-                return BruteForceParseStream( new FileStream( m_file, FileMode.Open, FileAccess.Read) );
-#endif // FEATURE_CAS_POLICY
             else
                 return new PermissionSet( PermissionState.None );
         }
index 2bc3c08..1c9dd76 100644 (file)
@@ -259,45 +259,6 @@ namespace System.Security.Permissions
                 throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type));
             Contract.EndContractBlock();
         }
-        
-#if FEATURE_CAS_POLICY
-        //------------------------------------------------------
-        //
-        // PUBLIC ENCODING METHODS
-        //
-        //------------------------------------------------------
-        
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ReflectionPermission" );
-            if (!IsUnrestricted())
-            {
-                esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( ReflectionPermissionFlag ), m_flags ) );
-                }
-            else
-            {
-                esd.AddAttribute( "Unrestricted", "true" );
-            }
-            return esd;
-        }
-    
-        public override void FromXml(SecurityElement esd)
-        {
-            CodeAccessPermission.ValidateElement( esd, this );
-            if (XMLUtil.IsUnrestricted( esd ))
-            {
-                m_flags = ReflectionPermission.AllFlagsAndMore;
-                return;
-            }
-           
-            Reset () ;
-            SetUnrestricted (false) ;
-    
-            String flags = esd.Attribute( "Flags" );
-            if (flags != null)
-                m_flags = (ReflectionPermissionFlag)Enum.Parse( typeof( ReflectionPermissionFlag ), flags );
-        }
-#endif // FEATURE_CAS_POLICY
 
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
index bf801d6..c0c51e9 100644 (file)
@@ -59,14 +59,6 @@ namespace System.Security.Permissions
             SetPathList( access, pathList );
         }
 
-#if FEATURE_MACL
-        public RegistryPermission( RegistryPermissionAccess access, AccessControlActions control, String pathList )
-        {
-            m_unrestricted = false;
-            AddPathList( access, control, pathList );
-        }
-#endif
-
         public void SetPathList( RegistryPermissionAccess access, String pathList )
         {
             VerifyAccess( access );
@@ -85,27 +77,11 @@ namespace System.Security.Permissions
             AddPathList( access, pathList );
         }
 
-#if FEATURE_MACL
-        internal void SetPathList( AccessControlActions control, String pathList )
-        {
-            m_unrestricted = false;
-
-            if ((control & AccessControlActions.View) != 0)
-                m_viewAcl = null;
-
-            if ((control & AccessControlActions.Change) != 0)
-                m_changeAcl = null;
-
-            AddPathList( RegistryPermissionAccess.NoAccess, control, pathList );
-        }
-#endif
-
         public void AddPathList( RegistryPermissionAccess access, String pathList )
         {
             AddPathList( access, AccessControlActions.None, pathList );
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AddPathList( RegistryPermissionAccess access, AccessControlActions control, String pathList )
         {
             VerifyAccess( access );
@@ -130,25 +106,8 @@ namespace System.Security.Permissions
                     m_create = new StringExpressionSet();
                 m_create.AddExpressions( pathList );
             }
-
-#if FEATURE_MACL
-            if ((control & AccessControlActions.View) != 0)
-            {
-                if (m_viewAcl == null)
-                    m_viewAcl = new StringExpressionSet();
-                m_viewAcl.AddExpressions( pathList );
-            }
-
-            if ((control & AccessControlActions.Change) != 0)
-            {
-                if (m_changeAcl == null)
-                    m_changeAcl = new StringExpressionSet();
-                m_changeAcl.AddExpressions( pathList );
-            }
-#endif
         }
     
-        [SecuritySafeCritical]
         public String GetPathList( RegistryPermissionAccess access )
         {
             // SafeCritical: these are registry paths, which means we're not leaking file system information here
@@ -233,7 +192,6 @@ namespace System.Security.Permissions
         //
         //------------------------------------------------------
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override bool IsSubsetOf(IPermission target)
         {
             if (target == null)
@@ -257,7 +215,6 @@ namespace System.Security.Permissions
                         (this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl )));
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override IPermission Intersect(IPermission target)
         {
             if (target == null)
@@ -309,7 +266,6 @@ namespace System.Security.Permissions
             return intersectPermission;
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override IPermission Union(IPermission other)
         {
             if (other == null)
@@ -391,93 +347,6 @@ namespace System.Security.Permissions
             }
             return copy;   
         }
-        
-#if FEATURE_CAS_POLICY
-        [SecuritySafeCritical]
-        public override SecurityElement ToXml()
-        {
-            // SafeCritical: our string expression sets don't contain paths, so there's no information that
-            // needs to be guarded in them.
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.RegistryPermission" );
-            if (!IsUnrestricted())
-            {
-                if (this.m_read != null && !this.m_read.IsEmpty())
-                {
-                    esd.AddAttribute( "Read", SecurityElement.Escape( m_read.UnsafeToString() ) );
-                }
-                if (this.m_write != null && !this.m_write.IsEmpty())
-                {
-                    esd.AddAttribute( "Write", SecurityElement.Escape( m_write.UnsafeToString() ) );
-                }
-                if (this.m_create != null && !this.m_create.IsEmpty())
-                {
-                    esd.AddAttribute( "Create", SecurityElement.Escape( m_create.UnsafeToString() ) );
-                }
-                if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty())
-                {
-                    esd.AddAttribute( "ViewAccessControl", SecurityElement.Escape( m_viewAcl.UnsafeToString() ) );
-                }
-                if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty())
-                {
-                    esd.AddAttribute( "ChangeAccessControl", SecurityElement.Escape( m_changeAcl.UnsafeToString() ) );
-                }
-            }
-            else
-            {
-                esd.AddAttribute( "Unrestricted", "true" );
-            }
-            return esd;
-        }
-
-        public override void FromXml(SecurityElement esd)
-        {
-            CodeAccessPermission.ValidateElement( esd, this );
-            String et;
-            
-            if (XMLUtil.IsUnrestricted( esd ))
-            {
-                m_unrestricted = true;
-                return;
-            }
-
-            m_unrestricted = false;
-            m_read = null;
-            m_write = null;
-            m_create = null;
-            m_viewAcl = null;
-            m_changeAcl = null;
-
-            et = esd.Attribute( "Read" );
-            if (et != null)
-            {
-                m_read = new StringExpressionSet( et );
-            }
-            
-            et = esd.Attribute( "Write" );
-            if (et != null)
-            {
-                m_write = new StringExpressionSet( et );
-            }
-    
-            et = esd.Attribute( "Create" );
-            if (et != null)
-            {
-                m_create = new StringExpressionSet( et );
-            }
-            
-            et = esd.Attribute( "ViewAccessControl" );
-            if (et != null)
-            {
-                m_viewAcl = new StringExpressionSet( et );
-            }
-
-            et = esd.Attribute( "ChangeAccessControl" );
-            if (et != null)
-            {
-                m_changeAcl = new StringExpressionSet( et );
-            }
-        }
-#endif // FEATURE_CAS_POLICY
 
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
index b359cc5..cf30029 100644 (file)
@@ -16,13 +16,11 @@ namespace System.Security.Permissions
     using System.Globalization;
     using System.Diagnostics.Contracts;
 
-[Serializable]
+    [Serializable]
     [Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CAS_POLICY
+    [System.Runtime.InteropServices.ComVisible(true)]
     // The csharp compiler requires these types to be public, but they are not used elsewhere.
     [Obsolete("SecurityPermissionFlag is no longer accessible to application code.")]
-#endif
     public enum SecurityPermissionFlag
     {
         NoFlags = 0x00,
@@ -254,99 +252,9 @@ namespace System.Security.Permissions
             Contract.EndContractBlock();
         }
 
-#if FEATURE_CAS_POLICY
-        //------------------------------------------------------
-        //
-        // PUBLIC ENCODING METHODS
-        //
-        //------------------------------------------------------
-        
-        private const String _strHeaderAssertion  = "Assertion";
-        private const String _strHeaderUnmanagedCode = "UnmanagedCode";
-        private const String _strHeaderExecution = "Execution";
-        private const String _strHeaderSkipVerification = "SkipVerification";
-        private const String _strHeaderControlThread = "ControlThread";
-        private const String _strHeaderControlEvidence = "ControlEvidence";
-        private const String _strHeaderControlPolicy = "ControlPolicy";
-        private const String _strHeaderSerializationFormatter = "SerializationFormatter";
-        private const String _strHeaderControlDomainPolicy = "ControlDomainPolicy";
-        private const String _strHeaderControlPrincipal = "ControlPrincipal";
-        private const String _strHeaderControlAppDomain = "ControlAppDomain";
-    
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SecurityPermission" );
-            if (!IsUnrestricted())
-            {
-                esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( SecurityPermissionFlag ), m_flags ) );
-            }
-            else
-            {
-                esd.AddAttribute( "Unrestricted", "true" );
-            }
-            return esd;
-        }
-    
-        public override void FromXml(SecurityElement esd)
-        {
-            CodeAccessPermission.ValidateElement( esd, this );
-            if (XMLUtil.IsUnrestricted( esd ))
-            {
-                m_flags = SecurityPermissionFlag.AllFlags;
-                return;
-            }
-           
-            Reset () ;
-            SetUnrestricted (false) ;
-    
-            String flags = esd.Attribute( "Flags" );
-    
-            if (flags != null)
-                m_flags = (SecurityPermissionFlag)Enum.Parse( typeof( SecurityPermissionFlag ), flags );
-        }
-#endif // FEATURE_CAS_POLICY
-
         //
         // Object Overrides
         //
-        
-    #if ZERO   // Do not remove this code, usefull for debugging
-        public override String ToString()
-        {
-            StringBuilder sb = new StringBuilder();
-            sb.Append("SecurityPermission(");
-            if (IsUnrestricted())
-            {
-                sb.Append("Unrestricted");
-            }
-            else
-            {
-                if (GetFlag(SecurityPermissionFlag.Assertion))
-                    sb.Append("Assertion; ");
-                if (GetFlag(SecurityPermissionFlag.UnmanagedCode))
-                    sb.Append("UnmangedCode; ");
-                if (GetFlag(SecurityPermissionFlag.SkipVerification))
-                    sb.Append("SkipVerification; ");
-                if (GetFlag(SecurityPermissionFlag.Execution))
-                    sb.Append("Execution; ");
-                if (GetFlag(SecurityPermissionFlag.ControlThread))
-                    sb.Append("ControlThread; ");
-                if (GetFlag(SecurityPermissionFlag.ControlEvidence))
-                    sb.Append("ControlEvidence; ");
-                if (GetFlag(SecurityPermissionFlag.ControlPolicy))
-                    sb.Append("ControlPolicy; ");
-                if (GetFlag(SecurityPermissionFlag.SerializationFormatter))
-                    sb.Append("SerializationFormatter; ");
-                if (GetFlag(SecurityPermissionFlag.ControlDomainPolicy))
-                    sb.Append("ControlDomainPolicy; ");
-                if (GetFlag(SecurityPermissionFlag.ControlPrincipal))
-                    sb.Append("ControlPrincipal; ");
-            }
-            
-            sb.Append(")");
-            return sb.ToString();
-        }
-    #endif
 
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
index 6050b58..ff38d51 100644 (file)
@@ -5,9 +5,6 @@
 namespace System.Security.Permissions
 {
     using System;
-#if FEATURE_CAS_POLICY
-    using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
     using SiteString = System.Security.Util.SiteString;
     using System.Text;
     using System.Collections;
@@ -31,55 +28,6 @@ namespace System.Security.Permissions
         [OptionalField(VersionAdded = 2)]        
         private SiteString[] m_sites;
 
-#if FEATURE_REMOTING
-        // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission
-        [OptionalField(VersionAdded = 2)]
-        private String m_serializedPermission; 
-
-        //  This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes
-        private SiteString m_site;
-
-        [OnDeserialized]
-        private void OnDeserialized(StreamingContext ctx)
-        {
-            // v2.0 and beyond XML case
-            if (m_serializedPermission != null)
-            {
-                FromXml(SecurityElement.FromString(m_serializedPermission));
-                m_serializedPermission = null;
-            }
-            else if (m_site != null) //v1.x case where we read the m_site value
-            {
-                m_unrestricted = false;
-                m_sites = new SiteString[1];
-                m_sites[0] = m_site;
-                m_site = null;
-            }
-        }
-
-        [OnSerializing]
-        private void OnSerializing(StreamingContext ctx)
-        {
-
-            if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
-            {
-                m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case
-                if (m_sites != null && m_sites.Length == 1) // for the v1.x case
-                    m_site = m_sites[0];
-                
-            }
-        }   
-        [OnSerialized]
-        private void OnSerialized(StreamingContext ctx)
-        {
-            if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
-            {
-                m_serializedPermission = null;
-                m_site = null;
-            }
-        }
-#endif // FEATURE_REMOTING
-
         //------------------------------------------------------
         //
         // PUBLIC CONSTRUCTORS
@@ -150,8 +98,6 @@ namespace System.Security.Permissions
         // IPERMISSION IMPLEMENTATION
         //
         //------------------------------------------------------
-
-
         public override IPermission Copy()
         {
             SiteIdentityPermission perm = new SiteIdentityPermission( PermissionState.None );
@@ -291,60 +237,6 @@ namespace System.Security.Permissions
             return result;
         }
 
-#if FEATURE_CAS_POLICY
-        public override void FromXml(SecurityElement esd)
-        {
-            m_unrestricted = false;
-            m_sites = null;
-            CodeAccessPermission.ValidateElement( esd, this );
-            String unr = esd.Attribute( "Unrestricted" );
-            if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0)
-            {
-                m_unrestricted = true;
-                return;
-            }
-            String elem = esd.Attribute( "Site" );
-            List<SiteString> al = new List<SiteString>();
-            if(elem != null)
-                al.Add(new SiteString( elem ));
-            ArrayList alChildren = esd.Children;
-            if(alChildren != null)
-            {
-                foreach(SecurityElement child in alChildren)
-                {
-                    elem = child.Attribute( "Site" );
-                    if(elem != null)
-                        al.Add(new SiteString( elem ));
-                }
-            }
-            if(al.Count != 0)
-                m_sites = al.ToArray();
-        }
-
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SiteIdentityPermission" );
-            if (m_unrestricted)
-                esd.AddAttribute( "Unrestricted", "true" );
-            else if (m_sites != null)
-            {
-                if (m_sites.Length == 1)
-                    esd.AddAttribute( "Site", m_sites[0].ToString() );
-                else
-                {
-                    int n;
-                    for(n = 0; n < m_sites.Length; n++)
-                    {
-                        SecurityElement child = new SecurityElement("Site");
-                        child.AddAttribute( "Site", m_sites[n].ToString() );
-                        esd.AddChild(child);
-                    }
-                }
-            }
-            return esd;
-        }
-#endif // FEATURE_CAS_POLICY
-
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
         {
index 0bc689b..f09d84d 100644 (file)
@@ -5,9 +5,6 @@
 namespace System.Security.Permissions
 {
     using System;
-#if FEATURE_CAS_POLICY
-    using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
     using System.Security.Util;
     using System.IO;
     using String = System.String;
@@ -389,89 +386,6 @@ namespace System.Security.Permissions
             return result;
         }
 
-#if FEATURE_CAS_POLICY
-        public override void FromXml(SecurityElement e)
-        {
-            m_unrestricted = false;
-            m_strongNames = null;
-            CodeAccessPermission.ValidateElement( e, this );
-            String unr = e.Attribute( "Unrestricted" );
-            if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0)
-            {
-                m_unrestricted = true;
-                return;
-            }
-            String elBlob = e.Attribute("PublicKeyBlob");
-            String elName = e.Attribute("Name");
-            String elVersion = e.Attribute("AssemblyVersion");
-            StrongName2 sn;
-            List<StrongName2> al = new List<StrongName2>();
-            if(elBlob != null || elName != null || elVersion != null)
-            {
-                sn = new StrongName2(
-                                    (elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)), 
-                                    elName, 
-                                    (elVersion == null ? null : new Version(elVersion)));
-                al.Add(sn);
-            }
-            ArrayList alChildren = e.Children;
-            if(alChildren != null)
-            {
-                foreach(SecurityElement child in alChildren)
-                {
-                    elBlob = child.Attribute("PublicKeyBlob");
-                    elName = child.Attribute("Name");
-                    elVersion = child.Attribute("AssemblyVersion");
-                    if(elBlob != null || elName != null || elVersion != null)
-                    {
-                        sn = new StrongName2(
-                                            (elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)), 
-                                            elName, 
-                                            (elVersion == null ? null : new Version(elVersion)));
-                        al.Add(sn);
-                    }
-                }
-            }
-            if(al.Count != 0)
-                m_strongNames = al.ToArray();
-        }
-
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.StrongNameIdentityPermission" );
-            if (m_unrestricted)
-                esd.AddAttribute( "Unrestricted", "true" );
-            else if (m_strongNames != null)
-            {
-                if (m_strongNames.Length == 1)
-                {
-                    if (m_strongNames[0].m_publicKeyBlob != null)
-                        esd.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[0].m_publicKeyBlob.PublicKey));
-                    if (m_strongNames[0].m_name != null)
-                        esd.AddAttribute("Name", m_strongNames[0].m_name);
-                    if ((Object)m_strongNames[0].m_version != null)
-                        esd.AddAttribute("AssemblyVersion", m_strongNames[0].m_version.ToString());
-                }
-                else
-                {
-                    int n;
-                    for(n = 0; n < m_strongNames.Length; n++)
-                    {
-                        SecurityElement child = new SecurityElement("StrongName");
-                        if (m_strongNames[n].m_publicKeyBlob != null)
-                            child.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[n].m_publicKeyBlob.PublicKey));
-                        if (m_strongNames[n].m_name != null)
-                            child.AddAttribute("Name", m_strongNames[n].m_name);
-                        if ((Object)m_strongNames[n].m_version != null)
-                            child.AddAttribute("AssemblyVersion", m_strongNames[n].m_version.ToString());
-                        esd.AddChild(child);
-                    }
-                }
-            }
-            return esd;
-        }
-#endif // FEATURE_CAS_POLICY
-
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
         {
index bb122b7..4abe801 100644 (file)
@@ -309,50 +309,6 @@ namespace System.Security.Permissions
         {
             return new UIPermission(this.m_windowFlag, this.m_clipboardFlag);
         }
-    
-#if FEATURE_CAS_POLICY
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UIPermission" );
-            if (!IsUnrestricted())
-            {
-                if (m_windowFlag != UIPermissionWindow.NoWindows)
-                {
-                    esd.AddAttribute( "Window", Enum.GetName( typeof( UIPermissionWindow ), m_windowFlag ) );
-                }
-                if (m_clipboardFlag != UIPermissionClipboard.NoClipboard)
-                {
-                    esd.AddAttribute( "Clipboard", Enum.GetName( typeof( UIPermissionClipboard ), m_clipboardFlag ) );
-                }
-            }
-            else
-            {
-                esd.AddAttribute( "Unrestricted", "true" );
-            }
-            return esd;
-        }
-            
-        public override void FromXml(SecurityElement esd)
-        {
-            CodeAccessPermission.ValidateElement( esd, this );
-            if (XMLUtil.IsUnrestricted( esd ))
-            {
-                SetUnrestricted( true );
-                return;
-            }
-            
-            m_windowFlag = UIPermissionWindow.NoWindows;
-            m_clipboardFlag = UIPermissionClipboard.NoClipboard;
-
-            String window = esd.Attribute( "Window" );
-            if (window != null)
-                m_windowFlag = (UIPermissionWindow)Enum.Parse( typeof( UIPermissionWindow ), window );
-
-            String clipboard = esd.Attribute( "Clipboard" );
-            if (clipboard != null)
-                m_clipboardFlag = (UIPermissionClipboard)Enum.Parse( typeof( UIPermissionClipboard ), clipboard );
-        }
-#endif // FEATURE_CAS_POLICY
 
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
index 99f86ed..0883bf8 100644 (file)
@@ -5,9 +5,6 @@
 namespace System.Security.Permissions
 {
     using System;
-#if FEATURE_CAS_POLICY
-    using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
     using System.Security.Util;
     using System.IO;
     using System.Text;
@@ -31,58 +28,8 @@ namespace System.Security.Permissions
 
         [OptionalField(VersionAdded = 2)]
         private bool m_unrestricted;
-        [OptionalField(VersionAdded = 2)]        
-        private URLString[] m_urls;
-
-#if FEATURE_REMOTING
-        // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission
         [OptionalField(VersionAdded = 2)]
-        private String m_serializedPermission; 
-
-        //  This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes
-        private URLString m_url;
-
-        [OnDeserialized]
-        private void OnDeserialized(StreamingContext ctx)
-        {
-            // v2.0 and beyond XML case
-            if (m_serializedPermission != null)
-            {
-                FromXml(SecurityElement.FromString(m_serializedPermission));
-                m_serializedPermission = null;
-            }
-            else if (m_url != null) //v1.x case where we read the m_site value
-            {
-                m_unrestricted = false;
-                m_urls = new URLString[1];
-                m_urls[0] = m_url;
-                m_url = null;
-            }
-
-        }
-
-        [OnSerializing]
-        private void OnSerializing(StreamingContext ctx)
-        {
-
-            if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
-            {
-                m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case
-                if (m_urls != null && m_urls.Length == 1) // for the v1.x case
-                    m_url = m_urls[0];
-                
-            }
-        }   
-        [OnSerialized]
-        private void OnSerialized(StreamingContext ctx)
-        {
-            if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
-            {
-                m_serializedPermission = null;
-                m_url = null;
-            }
-        }
-#endif // FEATURE_REMOTING
+        private URLString[] m_urls;
 
         //------------------------------------------------------
         //
@@ -323,60 +270,6 @@ namespace System.Security.Permissions
             return result;
         }
 
-#if FEATURE_CAS_POLICY
-        public override void FromXml(SecurityElement esd)
-        {
-            m_unrestricted = false;
-            m_urls = null;
-            CodeAccessPermission.ValidateElement( esd, this );
-            String unr = esd.Attribute( "Unrestricted" );
-            if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0)
-            {
-                m_unrestricted = true;
-                return;
-            }
-            String elem = esd.Attribute( "Url" );
-            List<URLString> al = new List<URLString>();
-            if(elem != null)
-                al.Add(new URLString( elem, true ));
-            ArrayList alChildren = esd.Children;
-            if(alChildren != null)
-            {
-                foreach(SecurityElement child in alChildren)
-                {
-                    elem = child.Attribute( "Url" );
-                    if(elem != null)
-                        al.Add(new URLString( elem, true ));
-                }
-            }
-            if(al.Count != 0)
-                m_urls = al.ToArray();
-        }
-
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UrlIdentityPermission" );
-            if (m_unrestricted)
-                esd.AddAttribute( "Unrestricted", "true" );
-            else if (m_urls != null)
-            {
-                if (m_urls.Length == 1)
-                    esd.AddAttribute( "Url", m_urls[0].ToString() );
-                else
-                {
-                    int n;
-                    for(n = 0; n < m_urls.Length; n++)
-                    {
-                        SecurityElement child = new SecurityElement("Url");
-                        child.AddAttribute( "Url", m_urls[n].ToString() );
-                        esd.AddChild(child);
-                    }
-                }
-            }
-            return esd;
-        }
-#endif // FEATURE_CAS_POLICY
-
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
         {
index 803bd34..9023c7e 100644 (file)
@@ -8,9 +8,6 @@
 namespace System.Security.Permissions
 {
     using System;
-#if FEATURE_CAS_POLICY
-    using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
     using System.Globalization;
     using System.Runtime.Serialization;
     using System.Collections;
@@ -42,57 +39,6 @@ namespace System.Security.Permissions
         [OptionalField(VersionAdded = 2)]
         private uint m_zones;
 
-#if FEATURE_REMOTING
-        // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission
-        [OptionalField(VersionAdded = 2)]
-        private String m_serializedPermission; 
-
-        //  This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes
-        private SecurityZone m_zone = SecurityZone.NoZone;
-
-        [OnDeserialized]
-        private void OnDeserialized(StreamingContext ctx)
-        {
-            if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
-            {
-                // v2.0 and beyond XML case
-                if (m_serializedPermission != null)
-                {
-                    FromXml(SecurityElement.FromString(m_serializedPermission));
-                    m_serializedPermission = null;
-                }
-                else //v1.x case where we read the m_zone value
-                {
-                    SecurityZone = m_zone;
-                    m_zone = SecurityZone.NoZone;
-                }
-            }
-
-
-        }
-
-        [OnSerializing]
-        private void OnSerializing(StreamingContext ctx)
-        {
-
-            if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
-            {
-                m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case
-                m_zone = SecurityZone;
-                
-            }
-        }   
-        [OnSerialized]
-        private void OnSerialized(StreamingContext ctx)
-        {
-            if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
-            {
-                m_serializedPermission = null;
-                m_zone = SecurityZone.NoZone;
-            }
-        }
-#endif // FEATURE_REMOTING
-
         //------------------------------------------------------
         //
         // PUBLIC CONSTRUCTORS
@@ -247,53 +193,6 @@ namespace System.Security.Permissions
             return new ZoneIdentityPermission(this.m_zones | that.m_zones);
         }
 
-#if FEATURE_CAS_POLICY
-        public override SecurityElement ToXml()
-        {
-            SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ZoneIdentityPermission" );
-            if (SecurityZone != SecurityZone.NoZone)
-            {
-                esd.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), this.SecurityZone ) );
-            }
-            else
-            {
-                int nEnum = 0;
-                uint nFlag;
-                for(nFlag = 1; nFlag < AllZones; nFlag <<= 1)
-                {
-                    if((m_zones & nFlag) != 0)
-                    {
-                        SecurityElement child = new SecurityElement("Zone");
-                        child.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), (SecurityZone)nEnum ) );
-                        esd.AddChild(child);
-                    }
-                    nEnum++;
-                }
-            }
-            return esd;
-        }
-
-        public override void FromXml(SecurityElement esd)
-        {
-            m_zones = 0;
-            CodeAccessPermission.ValidateElement( esd, this );
-            String eZone = esd.Attribute( "Zone" );
-            if (eZone != null)
-                SecurityZone = (SecurityZone)Enum.Parse( typeof( SecurityZone ), eZone );
-            if(esd.Children != null)
-            {
-                foreach(SecurityElement child in esd.Children)
-                {
-                    eZone = child.Attribute( "Zone" );
-                    int enm = (int)Enum.Parse( typeof( SecurityZone ), eZone );
-                    if(enm == (int)SecurityZone.NoZone)
-                        continue;
-                    m_zones |= ((uint)1 << enm);
-                }
-            }
-        }
-#endif // FEATURE_CAS_POLICY
-
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex()
         {
index feb5911..d4f1c27 100644 (file)
@@ -11,6 +11,7 @@ namespace System.Security.Permissions {
 #endif
     using System.Security.Util;
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
 [Serializable]
@@ -525,61 +526,6 @@ namespace System.Security.Permissions {
             return cp;
         }
 
-#if FEATURE_CAS_POLICY
-        public override SecurityElement ToXml () {
-            SecurityElement securityElement = CodeAccessPermission.CreatePermissionElement(this, "System.Security.Permissions.KeyContainerPermission");
-            if (!IsUnrestricted()) {
-                securityElement.AddAttribute("Flags", m_flags.ToString());
-                if (AccessEntries.Count > 0) {
-                    SecurityElement al = new SecurityElement("AccessList");
-                    foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
-                        SecurityElement entryElem = new SecurityElement("AccessEntry");
-                        entryElem.AddAttribute("KeyStore", accessEntry.KeyStore);
-                        entryElem.AddAttribute("ProviderName", accessEntry.ProviderName);
-                        entryElem.AddAttribute("ProviderType", accessEntry.ProviderType.ToString(null, null));
-                        entryElem.AddAttribute("KeyContainerName", accessEntry.KeyContainerName);
-                        entryElem.AddAttribute("KeySpec", accessEntry.KeySpec.ToString(null, null));
-                        entryElem.AddAttribute("Flags", accessEntry.Flags.ToString());
-                        al.AddChild(entryElem);
-                    }
-                    securityElement.AddChild(al);
-                }
-            } else 
-                securityElement.AddAttribute("Unrestricted", "true");
-
-            return securityElement;
-        }
-
-        public override void FromXml (SecurityElement securityElement) {
-            CodeAccessPermission.ValidateElement(securityElement, this);
-            if (XMLUtil.IsUnrestricted(securityElement)) {
-                m_flags = KeyContainerPermissionFlags.AllFlags;
-                m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags);
-                return;
-            }
-
-            m_flags = KeyContainerPermissionFlags.NoFlags;
-            string strFlags = securityElement.Attribute("Flags");
-            if (strFlags != null) {
-                KeyContainerPermissionFlags flags = (KeyContainerPermissionFlags) Enum.Parse(typeof(KeyContainerPermissionFlags), strFlags);
-                VerifyFlags(flags);
-                m_flags = flags;
-            }
-            m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags);
-
-            if (securityElement.InternalChildren != null && securityElement.InternalChildren.Count != 0) { 
-                IEnumerator enumerator = securityElement.Children.GetEnumerator();
-                while (enumerator.MoveNext()) {
-                    SecurityElement current = (SecurityElement) enumerator.Current;
-                    if (current != null) {
-                        if (String.Equals(current.Tag, "AccessList"))
-                            AddAccessEntries(current);
-                    }
-                }
-            }
-        }
-#endif // FEATURE_CAS_POLICY
-
         /// <internalonly/>
         int IBuiltInPermission.GetTokenIndex () {
             return KeyContainerPermission.GetTokenIndex();
@@ -597,7 +543,7 @@ namespace System.Security.Permissions {
                     if (current != null) {
                         if (String.Equals(current.Tag, "AccessEntry")) {
                             int iMax = current.m_lAttributes.Count;
-                            Contract.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
+                            Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
                             string keyStore = null;
                             string providerName = null;
                             int providerType = -1;
index 079db0e..3d4e35a 100644 (file)
@@ -118,10 +118,6 @@ namespace System.Security.Policy
             }
         }
 
-#pragma warning disable 618
-        [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
-#pragma warning restore 618
-        [SecuritySafeCritical]
         public override EvidenceBase Clone()
         {
             return base.Clone();
index f142ebe..7fef1de 100644 (file)
@@ -7,6 +7,7 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.IO;
 using System.Runtime.InteropServices;
@@ -22,9 +23,6 @@ namespace System.Security.Policy
     /// </summary>
     [ComVisible(true)]
     [Serializable]
-#pragma warning disable 618
-    [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
     public abstract class EvidenceBase
     {
         protected EvidenceBase()
@@ -44,11 +42,6 @@ namespace System.Security.Policy
         ///     Since legacy evidence objects would be cloned by being serialized, the default implementation
         ///     of EvidenceBase will do the same.
         /// </remarks>
-#pragma warning disable 618
-        [SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)]
-        [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
-        [SecuritySafeCritical]
         public virtual EvidenceBase Clone()
         {
 #if FEATURE_SERIALIZATION
@@ -86,9 +79,9 @@ namespace System.Security.Policy
 
         internal LegacyEvidenceWrapper(object legacyEvidence)
         {
-            Contract.Assert(legacyEvidence != null);
-            Contract.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper");
-            Contract.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable");
+            Debug.Assert(legacyEvidence != null);
+            Debug.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper");
+            Debug.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable");
 
             m_legacyEvidence = legacyEvidence;
         }
@@ -113,10 +106,6 @@ namespace System.Security.Policy
             return m_legacyEvidence.GetHashCode();
         }
 
-#pragma warning disable 618
-        [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
-#pragma warning restore 618
-        [SecuritySafeCritical]
         public override EvidenceBase Clone()
         {
             return base.Clone();
@@ -153,7 +142,7 @@ namespace System.Security.Policy
         {
             get
             {
-                Contract.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are");
+                Debug.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are");
 
                 ILegacyEvidenceAdapter adapter = m_legacyEvidenceList[0] as ILegacyEvidenceAdapter;
                 return adapter == null ? m_legacyEvidenceList[0].GetType() : adapter.EvidenceType;
@@ -162,10 +151,10 @@ namespace System.Security.Policy
 
         public void Add(EvidenceBase evidence)
         {
-            Contract.Assert(evidence != null);
-            Contract.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType),
+            Debug.Assert(evidence != null);
+            Debug.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType),
                             "LegacyEvidenceList must be homogeonous");
-            Contract.Assert(evidence.GetType() != typeof(LegacyEvidenceList),
+            Debug.Assert(evidence.GetType() != typeof(LegacyEvidenceList),
                             "Attempt to add a legacy evidence list to another legacy evidence list");
 
             m_legacyEvidenceList.Add(evidence);
@@ -181,10 +170,6 @@ namespace System.Security.Policy
             return m_legacyEvidenceList.GetEnumerator();
         }
 
-#pragma warning disable 618
-        [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
-#pragma warning restore 618
-        [SecuritySafeCritical]
         public override EvidenceBase Clone()
         {
             return base.Clone();
index bccf392..8deb145 100644 (file)
@@ -41,7 +41,7 @@ namespace System.Security.Policy
         /// </summary>
         private EvidenceTypeDescriptor(EvidenceTypeDescriptor descriptor)
         {
-            Contract.Assert(descriptor != null);
+            Debug.Assert(descriptor != null);
 
             m_hostCanGenerate = descriptor.m_hostCanGenerate;
 
@@ -68,9 +68,9 @@ namespace System.Security.Policy
 
             set
             {
-                Contract.Assert(value != null);
+                Debug.Assert(value != null);
 #if _DEBUG
-                Contract.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set");
+                Debug.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set");
 #endif
                 m_assemblyEvidence = value;
             }
@@ -85,7 +85,7 @@ namespace System.Security.Policy
 
             set
             {
-                Contract.Assert(value, "Attempt to clear the Generated flag");
+                Debug.Assert(value, "Attempt to clear the Generated flag");
                 m_generated = value;
             }
         }
@@ -99,7 +99,7 @@ namespace System.Security.Policy
 
             set
             {
-                Contract.Assert(value, "Attempt to clear HostCanGenerate flag");
+                Debug.Assert(value, "Attempt to clear HostCanGenerate flag");
                 m_hostCanGenerate = value;
             }
         }
@@ -113,9 +113,9 @@ namespace System.Security.Policy
 
             set
             {
-                Contract.Assert(value != null);
+                Debug.Assert(value != null);
 #if _DEBUG
-                Contract.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set");
+                Debug.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set");
 #endif
                 m_hostEvidence = value;
             }
@@ -127,7 +127,7 @@ namespace System.Security.Policy
         /// </summary>
         private bool CheckEvidenceType(EvidenceBase evidence)
         {
-            Contract.Assert(evidence != null);
+            Debug.Assert(evidence != null);
 
             ILegacyEvidenceAdapter legacyAdapter = evidence as ILegacyEvidenceAdapter;
             Type storedType = legacyAdapter == null ? evidence.GetType() : legacyAdapter.EvidenceType;
@@ -150,8 +150,8 @@ namespace System.Security.Policy
         /// </summary>
         internal void SetEvidenceType(Type evidenceType)
         {
-            Contract.Assert(evidenceType != null);
-            Contract.Assert(m_evidenceType == null, "Attempt to reset evidence type");
+            Debug.Assert(evidenceType != null);
+            Debug.Assert(m_evidenceType == null, "Attempt to reset evidence type");
 
             m_evidenceType = evidenceType;
         }
index 5bd3648..8f8c07c 100644 (file)
@@ -18,7 +18,6 @@ namespace System.Security.Policy {
         /// </summary>
         bool IsVerified 
         { 
-            [System.Security.SecurityCritical]
             get; 
         }
 
index 5fb61d1..9b58ece 100644 (file)
@@ -35,14 +35,6 @@ namespace System.Security.Policy {
         // The PermissionSet associated with this policy
         internal PermissionSet m_permSet;
 
-#if FEATURE_CAS_POLICY
-        // Evidence which was not verified but which was required to generate this policy statement.
-        // This is not serialized, since once we serialize we lose the ability to verify the evidence,
-        // meaning that restoring this state is meaningless.
-        [NonSerialized]
-        private List<IDelayEvaluatedEvidence> m_dependentEvidence;
-#endif
-
         // The bitfield of inheritance properties associated with this policy
         internal PolicyStatementAttribute m_attributes;
 
@@ -144,20 +136,13 @@ namespace System.Security.Policy {
                 }
             }
         }
-        
+
         public PolicyStatement Copy()
         {
-            PolicyStatement copy = new PolicyStatement(m_permSet, Attributes, true); // The PolicyStatement .ctor will copy the permission set
-#if FEATURE_CAS_POLICY
-            if (HasDependentEvidence)
-            {
-                copy.m_dependentEvidence = new List<IDelayEvaluatedEvidence>(m_dependentEvidence);
-            }
-#endif
-
-            return copy;
+            // The PolicyStatement .ctor will copy the permission set
+            return new PolicyStatement(m_permSet, Attributes, true);
         }
-        
+
         public String AttributeString
         {
             get
@@ -199,44 +184,6 @@ namespace System.Security.Policy {
             return (flag & (int)m_attributes) != 0;
         }
 
-#if FEATURE_CAS_POLICY
-        /// <summary>
-        ///     Gets all of the delay evaluated evidence which needs to be verified before this policy can
-        ///     be used.
-        /// </summary>
-        internal IEnumerable<IDelayEvaluatedEvidence> DependentEvidence
-        {
-            get
-            {
-                BCLDebug.Assert(HasDependentEvidence, "HasDependentEvidence");
-                return m_dependentEvidence.AsReadOnly();
-            }
-        }
-
-        /// <summary>
-        ///     Determine if this policy dependent upon the evaluation of any delay evaluated evidence
-        /// </summary>
-        internal bool HasDependentEvidence
-        {
-            get { return m_dependentEvidence != null && m_dependentEvidence.Count > 0; }
-        }
-
-        /// <summary>
-        ///     Add evidence which this policy statement is depending upon being verified to be valid.
-        /// </summary>
-        internal void AddDependentEvidence(IDelayEvaluatedEvidence dependentEvidence)
-        {
-            BCLDebug.Assert(dependentEvidence != null, "dependentEvidence != null");
-
-            if (m_dependentEvidence == null)
-            {
-                m_dependentEvidence = new List<IDelayEvaluatedEvidence>();
-            }
-
-            m_dependentEvidence.Add(dependentEvidence);
-        }
-#endif
-
         /// <summary>
         ///     Union a child policy statement into this policy statement
         /// </summary>
@@ -249,27 +196,6 @@ namespace System.Security.Policy {
                 throw new PolicyException(Environment.GetResourceString( "Policy_MultipleExclusive" ));
             }
 
-#if FEATURE_CAS_POLICY
-            // If our code group generated a grant set based upon unverified evidence, or it generated a grant
-            // set strictly less than that of a child group based upon unverified evidence, we need to keep
-            // track of any unverified evidence our child group has.
-            if (childPolicy.HasDependentEvidence)
-            {
-                bool childEvidenceNeedsVerification = m_permSet.IsSubsetOf(childPolicy.GetPermissionSetNoCopy()) &&
-                                                      !childPolicy.GetPermissionSetNoCopy().IsSubsetOf(m_permSet);
-
-                if (HasDependentEvidence || childEvidenceNeedsVerification)
-                {
-                    if (m_dependentEvidence == null)
-                    {
-                        m_dependentEvidence = new List<IDelayEvaluatedEvidence>();
-                    }
-
-                    m_dependentEvidence.AddRange(childPolicy.DependentEvidence);
-                }
-            }
-#endif
-
             // We need to merge together our grant set and attributes.  The result of this merge is
             // dependent upon if we're merging a child marked exclusive or not.  If the child is not
             // exclusive, we need to union in its grant set and or in its attributes. However, if the child
@@ -287,226 +213,6 @@ namespace System.Security.Policy {
             }
         }
 
-#if FEATURE_CAS_POLICY
-
-        public SecurityElement ToXml()
-        {
-            return ToXml( null );
-        }
-
-        public void FromXml( SecurityElement et )
-        {
-            FromXml( et, null );
-        }
-
-        public SecurityElement ToXml( PolicyLevel level )
-        {
-            return ToXml( level, false );
-        }
-
-        internal SecurityElement ToXml( PolicyLevel level, bool useInternal )
-        {
-            SecurityElement e = new SecurityElement( "PolicyStatement" );
-            e.AddAttribute( "version", "1" );
-            if (m_attributes != PolicyStatementAttribute.Nothing)
-                e.AddAttribute( "Attributes", XMLUtil.BitFieldEnumToString( typeof( PolicyStatementAttribute ), m_attributes ) );            
-            
-            lock (this)
-            {
-                if (m_permSet != null)
-                {
-                    if (m_permSet is NamedPermissionSet)
-                    {
-                        // If the named permission set exists in the parent level of this
-                        // policy struct, then just save the name of the permission set.
-                        // Otherwise, serialize it like normal.
-                
-                        NamedPermissionSet namedPermSet = (NamedPermissionSet)m_permSet;
-                        if (level != null && level.GetNamedPermissionSet( namedPermSet.Name ) != null)
-                        {
-                            e.AddAttribute( "PermissionSetName", namedPermSet.Name );
-                        }
-                        else
-                        {
-                            if (useInternal)
-                                e.AddChild( namedPermSet.InternalToXml() );
-                            else
-                                e.AddChild( namedPermSet.ToXml() );
-                        }
-                    }
-                    else
-                    {
-                        if (useInternal)
-                            e.AddChild( m_permSet.InternalToXml() );
-                        else
-                            e.AddChild( m_permSet.ToXml() );
-                    }
-                }
-            }
-            
-            return e;
-        }
-        
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public void FromXml( SecurityElement et, PolicyLevel level )
-        {
-            FromXml( et, level, false );
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal void FromXml( SecurityElement et, PolicyLevel level, bool allowInternalOnly )
-        {
-            if (et == null)
-                throw new ArgumentNullException( nameof(et) );
-
-            if (!et.Tag.Equals( "PolicyStatement" ))
-                throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ),  nameof(PolicyStatement), this.GetType().FullName ) );
-            Contract.EndContractBlock();
-        
-            m_attributes = (PolicyStatementAttribute) 0;
-
-            String strAttributes = et.Attribute( "Attributes" );
-
-            if (strAttributes != null)
-                m_attributes = (PolicyStatementAttribute)Enum.Parse( typeof( PolicyStatementAttribute ), strAttributes );
-
-            lock (this)
-            {
-                m_permSet = null;
-
-                if (level != null)
-                {
-                    String permSetName = et.Attribute( "PermissionSetName" );
-    
-                    if (permSetName != null)
-                    {
-                        m_permSet = level.GetNamedPermissionSetInternal( permSetName );
-
-                        if (m_permSet == null)
-                            m_permSet = new PermissionSet( PermissionState.None );
-                    }
-                }
-
-
-                if (m_permSet == null)
-                {
-                    // There is no provided level, it is not a named permission set, or
-                    // the named permission set doesn't exist in the provided level,
-                    // so just create the class through reflection and decode normally.
-        
-                    SecurityElement e = et.SearchForChildByTag( "PermissionSet" );
-
-                    if (e != null)
-                    {
-                        String className = e.Attribute( "class" );
-
-                        if (className != null && (className.Equals( "NamedPermissionSet" ) ||
-                                                  className.Equals( "System.Security.NamedPermissionSet" )))
-                            m_permSet = new NamedPermissionSet( "DefaultName", PermissionState.None );
-                        else
-                            m_permSet = new PermissionSet( PermissionState.None );
-                
-                        try
-                        {
-                            m_permSet.FromXml( e, allowInternalOnly, true );
-                        }
-                        catch
-                        {
-                            // ignore any exceptions from the decode process.
-                            // Note: we go ahead and use the permission set anyway.  This should be safe since
-                            // the decode process should never give permission beyond what a proper decode would have
-                            // given.
-                        }
-                    }
-                    else
-                    {
-                        throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXML" ) );
-                    }
-                }
-
-                if (m_permSet == null) 
-                    m_permSet = new PermissionSet( PermissionState.None );
-            }    
-        }
-
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal void FromXml( SecurityDocument doc, int position, PolicyLevel level, bool allowInternalOnly )
-        {
-            if (doc == null)
-                throw new ArgumentNullException( nameof(doc) );
-            Contract.EndContractBlock();
-
-            if (!doc.GetTagForElement( position ).Equals( "PolicyStatement" ))
-                throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ),  nameof(PolicyStatement), this.GetType().FullName ) );
-        
-            m_attributes = (PolicyStatementAttribute) 0;
-
-            String strAttributes = doc.GetAttributeForElement( position, "Attributes" );
-
-            if (strAttributes != null)
-                m_attributes = (PolicyStatementAttribute)Enum.Parse( typeof( PolicyStatementAttribute ), strAttributes );
-
-            lock (this)
-            {
-                m_permSet = null;
-
-                if (level != null)
-                {
-                    String permSetName = doc.GetAttributeForElement( position, "PermissionSetName" );
-    
-                    if (permSetName != null)
-                    {
-                        m_permSet = level.GetNamedPermissionSetInternal( permSetName );
-
-                        if (m_permSet == null)
-                            m_permSet = new PermissionSet( PermissionState.None );
-                    }
-                }
-
-
-                if (m_permSet == null)
-                {
-                    // There is no provided level, it is not a named permission set, or
-                    // the named permission set doesn't exist in the provided level,
-                    // so just create the class through reflection and decode normally.
-        
-                    ArrayList childPositions = doc.GetChildrenPositionForElement( position );
-                    int positionPermissionSet = -1;
-
-                    for (int i = 0; i < childPositions.Count; ++i)
-                    {
-                        if (doc.GetTagForElement( (int)childPositions[i] ).Equals( "PermissionSet" ))
-                        {
-                            positionPermissionSet = (int)childPositions[i];
-                        }
-                    }
-
-                    if (positionPermissionSet != -1)
-                    {
-                        String className = doc.GetAttributeForElement( positionPermissionSet, "class" );
-
-                        if (className != null && (className.Equals( "NamedPermissionSet" ) ||
-                                                  className.Equals( "System.Security.NamedPermissionSet" )))
-                            m_permSet = new NamedPermissionSet( "DefaultName", PermissionState.None );
-                        else
-                            m_permSet = new PermissionSet( PermissionState.None );
-                
-                        m_permSet.FromXml( doc, positionPermissionSet, allowInternalOnly );
-                    }
-                    else
-                    {
-                        throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXML" ) );
-                    }
-                }
-
-                if (m_permSet == null) 
-                    m_permSet = new PermissionSet( PermissionState.None );
-            }    
-        }
-#endif // FEATURE_CAS_POLICY
-
-
         [System.Runtime.InteropServices.ComVisible(false)]
         public override bool Equals( Object obj )
         {
index 9c954d2..14a95e1 100644 (file)
@@ -10,6 +10,7 @@
 //
 
 using System;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Globalization;
 using System.Security.Permissions;
@@ -34,7 +35,7 @@ namespace System.Security.Policy
 
         private Site(SiteString name)
         {
-            Contract.Assert(name != null);
+            Debug.Assert(name != null);
             m_name = name;
         }
 
@@ -94,30 +95,6 @@ namespace System.Security.Policy
             return Clone();
         }
 
-#if FEATURE_CAS_POLICY
-        internal SecurityElement ToXml()
-        {
-            SecurityElement elem = new SecurityElement( "System.Security.Policy.Site" );
-            // If you hit this assert then most likely you are trying to change the name of this class. 
-            // This is ok as long as you change the hard coded string above and change the assert below.
-            Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Site" ), "Class name changed!" );
-
-            elem.AddAttribute( "version", "1" );
-            
-            if(m_name != null)
-                elem.AddChild( new SecurityElement( "Name", m_name.ToString() ) );
-                
-            return elem;
-        }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CAS_POLICY
-        public override String ToString()
-        {
-            return ToXml().ToString();
-        }
-#endif // FEATURE_CAS_POLICY
-
         // INormalizeForIsolatedStorage is not implemented for startup perf
         // equivalent to INormalizeForIsolatedStorage.Normalize()
         internal Object Normalize()
index 0cdf85f..999b478 100644 (file)
@@ -89,14 +89,9 @@ namespace System.Security.Policy {
 
         bool IDelayEvaluatedEvidence.IsVerified
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
-#if FEATURE_CAS_POLICY
-                return m_assembly != null ? m_assembly.IsStrongNameVerified : true;
-#else // !FEATURE_CAS_POLICY
                 return true;
-#endif // FEATURE_CAS_POLICY
             }
         }
 
@@ -133,52 +128,6 @@ namespace System.Security.Policy {
             return Clone();
         }
 
-#if FEATURE_CAS_POLICY
-        internal SecurityElement ToXml()
-        {
-            SecurityElement root = new SecurityElement( "StrongName" );
-            root.AddAttribute( "version", "1" );
-
-            if (m_publicKeyBlob != null)
-                root.AddAttribute( "Key", System.Security.Util.Hex.EncodeHexString( m_publicKeyBlob.PublicKey ) );
-
-            if (m_name != null)
-                root.AddAttribute( "Name", m_name );
-
-            if (m_version != null)
-                root.AddAttribute( "Version", m_version.ToString() );
-
-            return root;
-        }
-
-        internal void FromXml (SecurityElement element)
-        {
-            if (element == null)
-                throw new ArgumentNullException(nameof(element));
-            if (String.Compare(element.Tag, "StrongName", StringComparison.Ordinal) != 0)
-                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
-            Contract.EndContractBlock();
-
-            m_publicKeyBlob = null;
-            m_version = null;
-
-            string key = element.Attribute("Key");
-            if (key != null)
-                m_publicKeyBlob = new StrongNamePublicKeyBlob(System.Security.Util.Hex.DecodeHexString(key));
-
-            m_name = element.Attribute("Name");
-
-            string version = element.Attribute("Version");
-            if (version != null)
-                m_version = new Version(version);
-        }
-
-        public override String ToString()
-        {
-            return ToXml().ToString();
-        }
-#endif // FEATURE_CAS_POLICY
-
         public override bool Equals( Object o )
         {
             StrongName that = (o as StrongName);
index dba8ca8..3541124 100644 (file)
@@ -14,6 +14,7 @@ namespace System.Security.Policy {
     using System.Security.Util;
     using UrlIdentityPermission = System.Security.Permissions.UrlIdentityPermission;
     using System.Runtime.Serialization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -42,7 +43,7 @@ namespace System.Security.Policy {
 
         private Url(Url url)
         {
-            Contract.Assert(url != null);
+            Debug.Assert(url != null);
             m_url = url.m_url;
         }
 
@@ -87,28 +88,6 @@ namespace System.Security.Policy {
             return Clone();
         }
 
-#if FEATURE_CAS_POLICY
-        internal SecurityElement ToXml()
-        {
-            SecurityElement root = new SecurityElement( "System.Security.Policy.Url" );
-            // If you hit this assert then most likely you are trying to change the name of this class. 
-            // This is ok as long as you change the hard coded string above and change the assert below.
-            Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Url" ), "Class name changed!" );
-
-            root.AddAttribute( "version", "1" );
-
-            if (m_url != null)
-                root.AddChild( new SecurityElement( "Url", m_url.ToString() ) );
-
-            return root;
-        }
-
-        public override String ToString()
-        {
-            return ToXml().ToString();
-        }
-#endif // FEATURE_CAS_POLICY
-
         // INormalizeForIsolatedStorage is not implemented for startup perf
         // equivalent to INormalizeForIsolatedStorage.Normalize()
         internal Object Normalize()
index 267c059..a9f5d84 100644 (file)
@@ -9,23 +9,21 @@
 //  Zone is an IIdentity representing Internet/Intranet/MyComputer etc.
 //
 
-namespace System.Security.Policy {
+namespace System.Security.Policy
+{
     using System.Security.Util;
     using ZoneIdentityPermission = System.Security.Permissions.ZoneIdentityPermission;
     using System.Runtime.CompilerServices;
     using System.Runtime.InteropServices;
     using System.Runtime.Versioning;
     using System.Runtime.Serialization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
     [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class Zone : EvidenceBase, IIdentityPermissionFactory
     {
-#if FEATURE_CAS_POLICY
-        [OptionalField(VersionAdded = 2)]
-        private String m_url;
-#endif // FEATURE_CAS_POLICY
         private SecurityZone m_zone;
 
         private static readonly String[] s_names =
@@ -42,36 +40,10 @@ namespace System.Security.Policy {
 
         private Zone(Zone zone)
         {
-            Contract.Assert(zone != null);
-
-#if FEATURE_CAS_POLICY
-            m_url = zone.m_url;
-#endif // FEATURE_CAS_POLICY
+            Debug.Assert(zone != null);
             m_zone = zone.m_zone;
         }
 
-#if FEATURE_CAS_POLICY
-        private Zone(String url)
-        {
-            m_url = url;
-            m_zone = SecurityZone.NoZone;
-        }
-
-        public static Zone CreateFromUrl( String url )
-        {
-            if (url == null)
-                throw new ArgumentNullException( nameof(url) );
-            Contract.EndContractBlock();
-
-            return new Zone( url );
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SuppressUnmanagedCodeSecurity]
-        private extern static SecurityZone _CreateFromUrl( String url );
-#endif // FEATURE_CAS_POLICY
-
         public IPermission CreateIdentityPermission( Evidence evidence )
         {
             return new ZoneIdentityPermission( SecurityZone );
@@ -79,14 +51,8 @@ namespace System.Security.Policy {
 
         public SecurityZone SecurityZone
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
-#if FEATURE_CAS_POLICY
-                if (m_url != null)
-                    m_zone = _CreateFromUrl( m_url );
-#endif // FEATURE_CAS_POLICY
-
                 return m_zone;
             }
         }
@@ -117,30 +83,6 @@ namespace System.Security.Policy {
             return Clone();
         }
 
-#if FEATURE_CAS_POLICY
-        internal SecurityElement ToXml()
-        {
-            SecurityElement elem = new SecurityElement( "System.Security.Policy.Zone" );
-            // If you hit this assert then most likely you are trying to change the name of this class. 
-            // This is ok as long as you change the hard coded string above and change the assert below.
-            Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Zone" ), "Class name changed!" );
-
-            elem.AddAttribute( "version", "1" );
-            if (SecurityZone != SecurityZone.NoZone)
-                elem.AddChild( new SecurityElement( "Zone", s_names[(int)SecurityZone] ) );
-            else
-                elem.AddChild( new SecurityElement( "Zone", s_names[s_names.Length-1] ) );
-            return elem;
-        }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CAS_POLICY
-        public override String ToString()
-        {
-            return ToXml().ToString();
-        }
-#endif // FEATURE_CAS_POLICY
-
         // INormalizeForIsolatedStorage is not implemented for startup perf
         // equivalent to INormalizeForIsolatedStorage.Normalize()
         internal Object Normalize()
index fa77ac5..9eec46f 100644 (file)
@@ -2,15 +2,10 @@
 // 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.Security.Principal
 {
-#if !FEATURE_CORECLR
-    [Serializable]
-    [System.Runtime.InteropServices.ComVisible(true)]
-#endif
-    public enum TokenImpersonationLevel {
+    public enum TokenImpersonationLevel
+    {
         None            = 0,
         Anonymous       = 1,
         Identification  = 2,
index ea9cd4b..9a84164 100644 (file)
@@ -11,7 +11,6 @@ namespace Microsoft.Win32.SafeHandles {
 
     // Introduce this handle to replace internal SafeTokenHandle,
     // which is mainly used to hold Windows thread or process access token
-    [SecurityCritical]
     public sealed class SafeAccessTokenHandle : SafeHandle
     {
         private SafeAccessTokenHandle()
@@ -27,24 +26,20 @@ namespace Microsoft.Win32.SafeHandles {
 
         public static SafeAccessTokenHandle InvalidHandle
         {
-            [SecurityCritical]
             get { return new SafeAccessTokenHandle(IntPtr.Zero); }
         }
 
         public override bool IsInvalid
         {
-            [SecurityCritical]
             get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
         }
 
-        [SecurityCritical]
         protected override bool ReleaseHandle()
         {
             return Win32Native.CloseHandle(handle);
         }
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeLsaLogonProcessHandle : SafeHandleZeroOrMinusOneIsInvalid {
         private SafeLsaLogonProcessHandle() : base (true) {}
 
@@ -57,7 +52,6 @@ namespace Microsoft.Win32.SafeHandles {
             get { return new SafeLsaLogonProcessHandle(IntPtr.Zero); }
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             // LsaDeregisterLogonProcess returns an NTSTATUS
@@ -65,7 +59,6 @@ namespace Microsoft.Win32.SafeHandles {
         }
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeLsaMemoryHandle : SafeBuffer {
         private SafeLsaMemoryHandle() : base(true) {}
 
@@ -78,14 +71,12 @@ namespace Microsoft.Win32.SafeHandles {
             get { return new SafeLsaMemoryHandle( IntPtr.Zero ); }
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return Win32Native.LsaFreeMemory(handle) == 0;
         }
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeLsaPolicyHandle : SafeHandleZeroOrMinusOneIsInvalid {
         private SafeLsaPolicyHandle() : base(true) {}
 
@@ -98,14 +89,12 @@ namespace Microsoft.Win32.SafeHandles {
             get { return new SafeLsaPolicyHandle( IntPtr.Zero ); }
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return Win32Native.LsaClose(handle) == 0;
         }
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeLsaReturnBufferHandle : SafeBuffer {
         private SafeLsaReturnBufferHandle() : base (true) {}
 
@@ -118,7 +107,6 @@ namespace Microsoft.Win32.SafeHandles {
             get { return new SafeLsaReturnBufferHandle(IntPtr.Zero); }
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             // LsaFreeReturnBuffer returns an NTSTATUS
@@ -126,7 +114,6 @@ namespace Microsoft.Win32.SafeHandles {
         }
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid {
         private SafeProcessHandle() : base (true) {}
 
@@ -139,14 +126,12 @@ namespace Microsoft.Win32.SafeHandles {
             get { return new SafeProcessHandle(IntPtr.Zero); }
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return Win32Native.CloseHandle(handle);
         }
     }
 
-    [System.Security.SecurityCritical]  // auto-generated
     internal sealed class SafeThreadHandle : SafeHandleZeroOrMinusOneIsInvalid {
         private SafeThreadHandle() : base (true) {}
 
@@ -155,7 +140,6 @@ namespace Microsoft.Win32.SafeHandles {
             SetHandle(handle);
         }
 
-        [System.Security.SecurityCritical]
         override protected bool ReleaseHandle()
         {
             return Win32Native.CloseHandle(handle);
index 5d06a78..674c041 100644 (file)
@@ -27,6 +27,7 @@ namespace System.Security
 #endif // FEATURE_CORRUPTING_EXCEPTIONS
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // This enum must be kept in sync with the SecurityContextSource enum in the VM
@@ -51,13 +52,11 @@ namespace System.Security
         internal ExecutionContext currEC; // current ExecutionContext on Thread
         internal CompressedStackSwitcher cssw;
 
-        [System.Security.SecuritySafeCritical] // overrides public transparent member
         public void Dispose()
         {
             Undo();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
 #if FEATURE_CORRUPTING_EXCEPTIONS
         [HandleProcessCorruptedStateExceptions] 
@@ -75,7 +74,6 @@ namespace System.Security
             return true;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
 #if FEATURE_CORRUPTING_EXCEPTIONS
         [HandleProcessCorruptedStateExceptions] 
@@ -89,8 +87,8 @@ namespace System.Security
 
             if (currEC != null)
             {
-                Contract.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread");
-                Contract.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch");
+                Debug.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread");
+                Debug.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch");
             
                 // restore the saved security context 
                 currEC.SecurityContext = prevSC.DangerousGetRawSecurityContext();
@@ -98,7 +96,7 @@ namespace System.Security
             else
             {
                 // caller must have already restored the ExecutionContext
-                Contract.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC));
+                Debug.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC));
             }
 
             currSC = null; // this will prevent the switcher object being used again        
@@ -167,7 +165,6 @@ namespace System.Security
             
         static internal SecurityContext FullTrustSecurityContext
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 if (_fullTrustSC == null)
@@ -203,19 +200,16 @@ namespace System.Security
         {
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static AsyncFlowControl SuppressFlow()
         {
             return SuppressFlow(SecurityContextDisableFlow.All);
         }
         
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static AsyncFlowControl SuppressFlowWindowsIdentity()
         {
             return SuppressFlow(SecurityContextDisableFlow.WI);
         }
 
-        [SecurityCritical]
         internal static AsyncFlowControl SuppressFlow(SecurityContextDisableFlow flags)
         {
             if (IsFlowSuppressed(flags))
@@ -231,7 +225,6 @@ namespace System.Security
             return afc;
         }
 
-        [SecuritySafeCritical]
         public static void RestoreFlow()
         {
             SecurityContext sc = Thread.CurrentThread.GetMutableExecutionContext().SecurityContext;
@@ -247,7 +240,6 @@ namespace System.Security
             return SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.All);
         }
 
-        [SecuritySafeCritical]
         internal static bool IsFlowSuppressed(SecurityContextDisableFlow flags)
         {           
             return Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsFlowSuppressed(flags);
@@ -257,7 +249,6 @@ namespace System.Security
         // continue past the call to SecurityContext.Run.  If you change the signature to this method, or
         // provide an alternate way to do a SecurityContext.Run make sure to update
         // SecurityStackWalk::IsSpecialRunFrame in the VM to search for the new method.
-        [System.Security.SecurityCritical]  // auto-generated_required
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static void Run(SecurityContext securityContext, ContextCallback callback, Object state)
@@ -294,7 +285,7 @@ namespace System.Security
                     // and automatically goes away when the callback returns.
                     WindowsIdentity.SafeRevertToSelf(ref stackMark);
                     // Ensure we have reverted to the state we entered in.
-                    Contract.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null);
+                    Debug.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null);
                 }
             }
             else
@@ -303,7 +294,6 @@ namespace System.Security
             }
 
         }
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void RunInternal(SecurityContext securityContext, ContextCallback callBack, Object state)
         {
             if (cleanupCode == null)
@@ -331,7 +321,6 @@ namespace System.Security
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal void runTryCode(Object userData)
         {
             SecurityContextRunData rData = (SecurityContextRunData) userData;
@@ -340,7 +329,6 @@ namespace System.Security
             
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [PrePrepareMethod]
         static internal void runFinallyCode(Object userData, bool exceptionThrown)
         {
@@ -355,7 +343,6 @@ namespace System.Security
 
         // Internal API that gets called from public SetSecurityContext and from SetExecutionContext
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-        [System.Security.SecurityCritical]  // auto-generated
         [DynamicSecurityMethodAttribute()]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         internal static SecurityContextSwitcher SetSecurityContext(SecurityContext sc, SecurityContext.Reader prevSecurityContext, bool modifyCurrentExecutionContext)
@@ -364,7 +351,6 @@ namespace System.Security
             return SetSecurityContext(sc, prevSecurityContext, modifyCurrentExecutionContext, ref stackMark);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
 #if FEATURE_CORRUPTING_EXCEPTIONS
         [HandleProcessCorruptedStateExceptions] 
 #endif // FEATURE_CORRUPTING_EXCEPTIONS
@@ -404,7 +390,6 @@ namespace System.Security
         }
 
         /// <internalonly/>
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public SecurityContext CreateCopy()
         {
             if (!isNewCapture)
@@ -423,10 +408,9 @@ namespace System.Security
         }
 
         /// <internalonly/>
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal SecurityContext CreateMutableCopy()
         {
-            Contract.Assert(!this.isNewCapture);
+            Debug.Assert(!this.isNewCapture);
 
             SecurityContext sc = new SecurityContext();
             sc._disableFlow = this._disableFlow;
@@ -437,7 +421,6 @@ namespace System.Security
             return sc;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static SecurityContext Capture( )
         {
@@ -453,7 +436,6 @@ namespace System.Security
          }
 
         // create a clone from a non-existing SecurityContext
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         static internal SecurityContext Capture(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark)
         {
@@ -468,7 +450,6 @@ namespace System.Security
             return CaptureCore(currThreadEC, ref stackMark);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static private SecurityContext CaptureCore(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark)
         {
             SecurityContext sc = new SecurityContext();
@@ -479,7 +460,6 @@ namespace System.Security
             return sc;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal SecurityContext CreateFullTrustSecurityContext()
         {
             SecurityContext sc = new SecurityContext();
@@ -499,7 +479,6 @@ namespace System.Security
             return (IsDefaultThreadSecurityInfo());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal extern static bool IsDefaultThreadSecurityInfo();
     }
index 667bf7f..f57665b 100644 (file)
@@ -14,6 +14,7 @@ namespace System.Security
     using System.Globalization;
     using System.IO;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     internal enum SecurityElementType
@@ -93,19 +94,6 @@ namespace System.Security
             return ((SecurityElement)this).Attribute( attributeName );
         }
 
-//////////////
-
-#if FEATURE_CAS_POLICY
-        public static SecurityElement FromString( String xml )
-        {
-            if (xml == null)
-                throw new ArgumentNullException( nameof(xml) );
-            Contract.EndContractBlock();
-
-            return new Parser( xml ).GetTopElement();
-        }
-#endif // FEATURE_CAS_POLICY
-    
         public SecurityElement( String tag )
         {
             if (tag == null)
@@ -171,7 +159,7 @@ namespace System.Security
                     Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 );
                                         
                     int iMax = m_lAttributes.Count;
-                    Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+                    Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
                           
                     for (int i = 0; i < iMax; i += 2)
                     {
@@ -296,7 +284,7 @@ namespace System.Security
             else
             {
                 int iMax = m_lAttributes.Count;
-                Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+                Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
                           
                 for (int i = 0; i < iMax; i += 2)
                 {
@@ -400,7 +388,7 @@ namespace System.Security
             else 
             {                
                 int iMax = m_lAttributes.Count;
-                Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+                Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
 
                 if (iMax != other.m_lAttributes.Count)
                     return false;
@@ -495,7 +483,7 @@ namespace System.Security
         private static String GetEscapeSequence( char c )
         {
             int iMax = s_escapeStringPairs.Length;
-            Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+            Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
                           
             for (int i = 0; i < iMax; i += 2)
             {
@@ -506,7 +494,7 @@ namespace System.Security
                     return strEscValue;
             }
 
-            Contract.Assert( false, "Unable to find escape sequence for this character" );
+            Debug.Assert( false, "Unable to find escape sequence for this character" );
             return c.ToString();
         }
 
@@ -557,7 +545,7 @@ namespace System.Security
             int maxCompareLength = str.Length - index;
 
             int iMax = s_escapeStringPairs.Length;
-            Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+            Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
                           
             for (int i = 0; i < iMax; i += 2)
             {
@@ -616,7 +604,7 @@ namespace System.Security
             while (true);
 
             // C# reports a warning if I leave this in, but I still kinda want to just in case.
-            // Contract.Assert( false, "If you got here, the execution engine or compiler is really confused" );
+            // Debug.Assert( false, "If you got here, the execution engine or compiler is really confused" );
             // return str;
         }
 
@@ -636,23 +624,11 @@ namespace System.Security
             return sb.ToString();
         }
 
-#if !FEATURE_CORECLR
-        private static void ToStringHelperStreamWriter(Object obj, String str)
-        {
-            ((StreamWriter)obj).Write(str);
-        }
-
-        internal void ToWriter( StreamWriter writer )
-        {
-            ToString( "", writer, new ToStringHelperFunc( ToStringHelperStreamWriter ) );
-        }
-#endif
-
         private void ToString( String indent, Object obj, ToStringHelperFunc func )
         {
             // First add the indent
             
-            // func( obj, indent );                       
+            // func( obj, indent );
             
             // Add in the opening bracket and the tag.
             
@@ -681,7 +657,7 @@ namespace System.Security
                 func( obj, " " );
 
                 int iMax = m_lAttributes.Count;
-                Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+                Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
                           
                 for (int i = 0; i < iMax; i += 2)
                 {
@@ -785,7 +761,7 @@ namespace System.Security
             // the one we are asked for
 
             int iMax = m_lAttributes.Count;
-            Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+            Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
                           
             for (int i = 0; i < iMax; i += 2)
             {
@@ -831,38 +807,6 @@ namespace System.Security
             return null;
         }
 
-#if FEATURE_CAS_POLICY
-        internal IPermission ToPermission(bool ignoreTypeLoadFailures)
-        {
-            IPermission ip = XMLUtil.CreatePermission( this, PermissionState.None, ignoreTypeLoadFailures );
-            if (ip == null)
-                return null;
-            ip.FromXml(this);
-
-            // Get the permission token here to ensure that the token
-            // type is updated appropriately now that we've loaded the type.
-            PermissionToken token = PermissionToken.GetToken( ip );
-            Contract.Assert((token.m_type & PermissionTokenType.DontKnow) == 0, "Token type not properly assigned");
-
-            return ip;            
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal Object ToSecurityObject()
-        {
-            switch (m_strTag)
-            {
-                case "PermissionSet":
-                    PermissionSet pset = new PermissionSet(PermissionState.None);
-                    pset.FromXml(this);
-                    return pset;
-
-                default:
-                    return ToPermission(false);
-            }
-        }
-#endif // FEATURE_CAS_POLICY
-
         internal String SearchForTextOfLocalName(String strLocalName) 
         {
             // Search on each child in order and each
index 4de9d65..c76674c 100644 (file)
@@ -34,129 +34,19 @@ namespace System.Security
     [Serializable]
     public class SecurityException : SystemException
     {
-#if FEATURE_CAS_POLICY        
-        private String m_debugString; // NOTE: If you change the name of this field, you'll have to update SOS as well!
-        private SecurityAction m_action;
-        [NonSerialized] private Type m_typeOfPermissionThatFailed;
-        private String m_permissionThatFailed;
-        private String m_demanded;
-        private String m_granted;
-        private String m_refused;
-        private String m_denied;
-        private String m_permitOnly;
-        private AssemblyName m_assemblyName;
-        private byte[] m_serializedMethodInfo;
-        private String m_strMethodInfo;
-        private SecurityZone m_zone;
-        private String m_url;
-
-        private const String ActionName = "Action";
-        private const String FirstPermissionThatFailedName = "FirstPermissionThatFailed";
-        private const String DemandedName = "Demanded";
-        private const String GrantedSetName = "GrantedSet";
-        private const String RefusedSetName = "RefusedSet";
-        private const String DeniedName = "Denied";
-        private const String PermitOnlyName = "PermitOnly";
-        private const String Assembly_Name = "Assembly";
-        private const String MethodName_Serialized = "Method";
-        private const String MethodName_String = "Method_String";
-        private const String ZoneName = "Zone";
-        private const String UrlName = "Url";
-#endif // #if FEATURE_CAS_POLICY
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static string GetResString(string sResourceName)
         {
             PermissionSet.s_fullTrust.Assert();
             return Environment.GetResourceString(sResourceName);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
 #pragma warning disable 618
         internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
 #pragma warning restore 618
         {
-#if FEATURE_CAS_POLICY            
-            // See if we need to throw a HostProtectionException instead
-            HostProtectionPermission hostProtectionPerm = permThatFailed as HostProtectionPermission;
-            if(hostProtectionPerm != null)
-                return new HostProtectionException(GetResString("HostProtection_HostProtection"), HostProtectionPermission.protectedResources, hostProtectionPerm.Resources);
-
-            // Produce relevant strings
-            String message = "";
-            MethodInfo method = null;
-            try
-            {
-                if(granted == null && refused == null && demand == null)
-                {
-                    message = GetResString("Security_NoAPTCA");
-                }
-                else
-                {
-                    if(demand != null && demand is IPermission)
-                        message = String.Format(CultureInfo.InvariantCulture,  GetResString("Security_Generic"), demand.GetType().AssemblyQualifiedName );
-                    else if (permThatFailed != null)
-                        message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), permThatFailed.GetType().AssemblyQualifiedName);
-                    else
-                        message = GetResString("Security_GenericNoType");
-                }
-
-                method = SecurityRuntime.GetMethodInfo(rmh);
-            }
-            catch(Exception e)
-            {
-                // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort).  (We shouldn't do a Contract.Assert in this case or it will lock up the thread.)
-                if(e is System.Threading.ThreadAbortException)
-                throw;
-            }
-
-/*            catch(System.Threading.ThreadAbortException)
-            {
-                // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort).  (We shouldn't do a BCLDebug.Assert in this case or it will lock up the thread.)
-                throw;
-            }
-            catch
-            {
-            }
-*/
-            // make the exception object
-            return new SecurityException(message, asmName, granted, refused, method, action, demand, permThatFailed, asmEvidence);
-#else
             return new SecurityException(GetResString("Arg_SecurityException"));
-#endif
-
         }
 
-#if FEATURE_CAS_POLICY            
-        private static byte[] ObjectToByteArray(Object obj)
-        {
-            if(obj == null)
-                return null;
-            MemoryStream stream = new MemoryStream();
-            BinaryFormatter formatter = new BinaryFormatter();
-            try {
-                formatter.Serialize(stream, obj);
-                byte[] array = stream.ToArray();
-                return array;
-            } catch (NotSupportedException) {
-                // Serialization of certain methods is not supported (namely
-                // global methods, since they have no representation outside of
-                // a module scope).
-                return null;
-            }
-        }
-
-        private static Object ByteArrayToObject(byte[] array)
-        {
-            if(array == null || array.Length == 0)
-                return null;
-            MemoryStream stream = new MemoryStream(array);
-            BinaryFormatter formatter = new BinaryFormatter();
-            Object obj = formatter.Deserialize(stream);
-            return obj;
-        }
-#endif // FEATURE_CAS_POLICY
-
         public SecurityException()
             : base(GetResString("Arg_SecurityException"))
         {
@@ -170,427 +60,12 @@ namespace System.Security
             SetErrorCode(System.__HResults.COR_E_SECURITY);
         }
 
-#if FEATURE_CAS_POLICY            
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public SecurityException(String message, Type type ) 
-            : base(message)
-        {
-            PermissionSet.s_fullTrust.Assert();
-            SetErrorCode(System.__HResults.COR_E_SECURITY);
-            m_typeOfPermissionThatFailed = type;
-        }
-
-        // *** Don't use this constructor internally ***
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public SecurityException(String message, Type type, String state ) 
-            : base(message)
-        {
-            PermissionSet.s_fullTrust.Assert();
-            SetErrorCode(System.__HResults.COR_E_SECURITY);
-            m_typeOfPermissionThatFailed = type;
-            m_demanded = state;
-        }
-#endif //FEATURE_CAS_POLICY            
-
         public SecurityException(String message, Exception inner)
             : base(message, inner)
         {
             SetErrorCode(System.__HResults.COR_E_SECURITY);
         }
 
-#if FEATURE_CAS_POLICY            
-        // *** Don't use this constructor internally ***
-        [System.Security.SecurityCritical]  // auto-generated
-        internal SecurityException( PermissionSet grantedSetObj, PermissionSet refusedSetObj )
-            : base(GetResString("Arg_SecurityException"))
-        {
-            PermissionSet.s_fullTrust.Assert();
-            SetErrorCode(System.__HResults.COR_E_SECURITY);
-            if (grantedSetObj != null)
-                m_granted = grantedSetObj.ToXml().ToString();
-            if (refusedSetObj != null)
-                m_refused = refusedSetObj.ToXml().ToString();
-        }
-    
-        // *** Don't use this constructor internally ***
-        [System.Security.SecurityCritical]  // auto-generated
-        internal SecurityException( String message, PermissionSet grantedSetObj, PermissionSet refusedSetObj )
-            : base(message)
-        {
-            PermissionSet.s_fullTrust.Assert();
-            SetErrorCode(System.__HResults.COR_E_SECURITY);
-            if (grantedSetObj != null)
-                m_granted = grantedSetObj.ToXml().ToString();
-            if (refusedSetObj != null)
-                m_refused = refusedSetObj.ToXml().ToString();
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        protected SecurityException(SerializationInfo info, StreamingContext context) : base (info, context)
-        {
-            if (info==null)
-                throw new ArgumentNullException(nameof(info));
-            Contract.EndContractBlock();
-
-            try
-            {
-                m_action = (SecurityAction)info.GetValue(ActionName, typeof(SecurityAction));
-                m_permissionThatFailed = (String)info.GetValueNoThrow(FirstPermissionThatFailedName, typeof(String));
-                m_demanded = (String)info.GetValueNoThrow(DemandedName, typeof(String));
-                m_granted = (String)info.GetValueNoThrow(GrantedSetName, typeof(String));
-                m_refused = (String)info.GetValueNoThrow(RefusedSetName, typeof(String));
-                m_denied = (String)info.GetValueNoThrow(DeniedName, typeof(String));
-                m_permitOnly = (String)info.GetValueNoThrow(PermitOnlyName, typeof(String));
-                m_assemblyName = (AssemblyName)info.GetValueNoThrow(Assembly_Name, typeof(AssemblyName));
-                m_serializedMethodInfo = (byte[])info.GetValueNoThrow(MethodName_Serialized, typeof(byte[]));
-                m_strMethodInfo = (String)info.GetValueNoThrow(MethodName_String, typeof(String));
-                m_zone = (SecurityZone)info.GetValue(ZoneName, typeof(SecurityZone));
-                m_url = (String)info.GetValueNoThrow(UrlName, typeof(String));
-            }
-            catch 
-            {
-                m_action = 0;
-                m_permissionThatFailed = "";
-                m_demanded = "";
-                m_granted = "";
-                m_refused = "";
-                m_denied = "";
-                m_permitOnly = "";
-                m_assemblyName = null;
-                m_serializedMethodInfo = null;
-                m_strMethodInfo = null;
-                m_zone = SecurityZone.NoZone;
-                m_url = "";
-            }
-        }
-
-        // ------------------------------------------
-        // | For failures due to insufficient grant |
-        // ------------------------------------------
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence)
-            : base(message)
-        {
-            PermissionSet.s_fullTrust.Assert();
-            SetErrorCode(System.__HResults.COR_E_SECURITY);
-            Action = action;
-            if(permThatFailed != null)
-                m_typeOfPermissionThatFailed = permThatFailed.GetType();
-            FirstPermissionThatFailed = permThatFailed;
-            Demanded = demanded;
-            m_granted = (grant == null ? "" : grant.ToXml().ToString());
-            m_refused = (refused == null ? "" : refused.ToXml().ToString());
-            m_denied = "";
-            m_permitOnly = "";
-            m_assemblyName = assemblyName;
-            Method = method;
-            m_url = "";
-            m_zone = SecurityZone.NoZone;
-            if(evidence != null)
-            {
-                Url url = evidence.GetHostEvidence<Url>();
-                if(url != null)
-                    m_url = url.GetURLString().ToString();
-                Zone zone = evidence.GetHostEvidence<Zone>();
-                if(zone != null)
-                    m_zone = zone.SecurityZone;
-            }
-            m_debugString = this.ToString(true, false);
-        }
-
-        // ------------------------------------------
-        // | For failures due to deny or PermitOnly |
-        // ------------------------------------------
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed)
-            : base(message)
-        {
-            PermissionSet.s_fullTrust.Assert();
-            SetErrorCode(System.__HResults.COR_E_SECURITY);
-            Action = SecurityAction.Demand;
-            if(permThatFailed != null)
-                m_typeOfPermissionThatFailed = permThatFailed.GetType();
-            FirstPermissionThatFailed = permThatFailed;
-            Demanded = demanded;
-            m_granted = "";
-            m_refused = "";
-            DenySetInstance = deny;
-            PermitOnlySetInstance = permitOnly;
-            m_assemblyName = null;
-            Method = method;
-            m_zone = SecurityZone.NoZone;
-            m_url = "";
-            m_debugString = this.ToString(true, false);
-        }
-
-
-
-
-
-
-
-
-
-
-
-        [System.Runtime.InteropServices.ComVisible(false)]
-        public SecurityAction Action
-        {
-            get
-            {
-                return m_action;
-            }
-
-            set
-            {
-                m_action = value;
-            }
-        }
-
-        public Type PermissionType
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            get
-            {
-                if(m_typeOfPermissionThatFailed == null)
-                {
-                    Object ob = XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed);
-                    if(ob == null)
-                        ob = XMLUtil.XmlStringToSecurityObject(m_demanded);
-                    if(ob != null)
-                        m_typeOfPermissionThatFailed = ob.GetType();
-                }
-                return m_typeOfPermissionThatFailed;
-            }
-
-            set
-            {
-                m_typeOfPermissionThatFailed = value;
-            }
-        }
-
-        public IPermission FirstPermissionThatFailed
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return (IPermission)XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed);
-            }
-
-            set
-            {
-                m_permissionThatFailed = XMLUtil.SecurityObjectToXmlString(value);
-            }
-        }
-
-        public String PermissionState
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return m_demanded;
-            }
-
-            set
-            {
-                m_demanded = value;
-            }
-        }
-
-        [System.Runtime.InteropServices.ComVisible(false)]
-        public Object Demanded
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return XMLUtil.XmlStringToSecurityObject(m_demanded);
-            }
-
-            set
-            {
-                m_demanded = XMLUtil.SecurityObjectToXmlString(value);
-            }
-        }
-
-        public String GrantedSet
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return m_granted;
-            }
-
-            set
-            {
-                m_granted = value;
-            }
-        }
-
-        public String RefusedSet
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return m_refused;
-            }
-
-            set
-            {
-                m_refused = value;
-            }
-        }
-
-        [System.Runtime.InteropServices.ComVisible(false)]
-        public Object DenySetInstance
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return XMLUtil.XmlStringToSecurityObject(m_denied);
-            }
-
-            set
-            {
-                m_denied = XMLUtil.SecurityObjectToXmlString(value);
-            }
-        }
-
-        [System.Runtime.InteropServices.ComVisible(false)]
-        public Object PermitOnlySetInstance
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return XMLUtil.XmlStringToSecurityObject(m_permitOnly);
-            }
-
-            set
-            {
-                m_permitOnly = XMLUtil.SecurityObjectToXmlString(value);
-            }
-        }
-
-        [System.Runtime.InteropServices.ComVisible(false)]
-        public AssemblyName FailedAssemblyInfo
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return m_assemblyName;
-            }
-
-            set
-            {
-                m_assemblyName = value;
-            }
-            }
-
-        private MethodInfo getMethod()
-        {
-            return (MethodInfo)ByteArrayToObject(m_serializedMethodInfo);
-        }
-
-        [System.Runtime.InteropServices.ComVisible(false)]
-        public MethodInfo Method
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return getMethod();
-            }
-
-            set
-            {
-                RuntimeMethodInfo m = value as RuntimeMethodInfo;
-                m_serializedMethodInfo = ObjectToByteArray(m);
-                if (m != null)
-                {
-                    m_strMethodInfo = m.ToString();
-                }
-            }
-        }
-
-        public SecurityZone Zone
-        {
-            get
-            {
-                return m_zone;
-            }
-
-            set
-            {
-                m_zone = value;
-            }
-        }
-
-        public String Url
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
-            get
-            {
-                return m_url;
-            }
-
-            set
-            {
-                m_url = value;
-            }
-        }
-
-        private void ToStringHelper(StringBuilder sb, String resourceString, Object attr)
-        {
-            if (attr == null)
-                return;
-            String attrString = attr as String;
-            if (attrString == null)
-                attrString = attr.ToString();
-            if (attrString.Length == 0)
-                return;
-            sb.Append(Environment.NewLine);
-            sb.Append(GetResString(resourceString));
-            sb.Append(Environment.NewLine);
-            sb.Append(attrString);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        private String ToString(bool includeSensitiveInfo, bool includeBaseInfo)
-        {
-            PermissionSet.s_fullTrust.Assert();
-            StringBuilder sb = new StringBuilder();
-
-            if(includeBaseInfo)
-            sb.Append(base.ToString());
-            if(Action > 0)
-                ToStringHelper(sb, "Security_Action", Action);
-            ToStringHelper(sb, "Security_TypeFirstPermThatFailed", PermissionType);
-            if(includeSensitiveInfo)
-            {
-                ToStringHelper(sb, "Security_FirstPermThatFailed", m_permissionThatFailed);
-                ToStringHelper(sb, "Security_Demanded", m_demanded);
-                ToStringHelper(sb, "Security_GrantedSet", m_granted);
-                ToStringHelper(sb, "Security_RefusedSet", m_refused);
-                ToStringHelper(sb, "Security_Denied", m_denied);
-                ToStringHelper(sb, "Security_PermitOnly", m_permitOnly);
-                ToStringHelper(sb, "Security_Assembly", m_assemblyName);
-                ToStringHelper(sb, "Security_Method", m_strMethodInfo);
-            }
-            if(m_zone != SecurityZone.NoZone)
-                ToStringHelper(sb, "Security_Zone", m_zone);
-            if(includeSensitiveInfo)
-                ToStringHelper(sb, "Security_Url", m_url);
-            return sb.ToString();
-        }
-#else // FEATURE_CAS_POLICY
         internal SecurityException(PermissionSet grantedSetObj, PermissionSet refusedSetObj)
             : this(){}
 #pragma warning disable 618
@@ -601,7 +76,6 @@ namespace System.Security
         internal SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed)
                     : this(){}
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context)
         {
             if (info == null)
@@ -614,9 +88,6 @@ namespace System.Security
             return base.ToString();
         }
 
-#endif // FEATURE_CAS_POLICY
-
-        [System.Security.SecurityCritical]  // auto-generated
         private bool CanAccessSensitiveInfo()
         {
             bool retVal = false;
@@ -632,14 +103,7 @@ namespace System.Security
             }
             return retVal;
         }
-#if FEATURE_CAS_POLICY            
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public override String ToString() 
-        {
-            return ToString(CanAccessSensitiveInfo(), true);
-        }
-#endif //FEATURE_CAS_POLICY            
-        [System.Security.SecurityCritical]  // auto-generated_required
+
         public override void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null)
@@ -647,24 +111,8 @@ namespace System.Security
             Contract.EndContractBlock();
 
             base.GetObjectData(info, context);
-#if FEATURE_CAS_POLICY            
-
-            info.AddValue(ActionName, m_action, typeof(SecurityAction));
-            info.AddValue(FirstPermissionThatFailedName, m_permissionThatFailed, typeof(String));
-            info.AddValue(DemandedName, m_demanded, typeof(String));
-            info.AddValue(GrantedSetName, m_granted, typeof(String));
-            info.AddValue(RefusedSetName, m_refused, typeof(String));
-            info.AddValue(DeniedName, m_denied, typeof(String));
-            info.AddValue(PermitOnlyName, m_permitOnly, typeof(String));
-            info.AddValue(Assembly_Name, m_assemblyName, typeof(AssemblyName));
-            info.AddValue(MethodName_Serialized, m_serializedMethodInfo, typeof(byte[]));
-            info.AddValue(MethodName_String, m_strMethodInfo, typeof(String));
-            info.AddValue(ZoneName, m_zone, typeof(SecurityZone));
-            info.AddValue(UrlName, m_url, typeof(String));
-#endif // FEATURE_CAS_POLICY            
         }
 
-#if !FEATURE_CAS_POLICY
         // Stubs for surface area compatibility only
         public SecurityException(String message, Type type)
             : base(message)
@@ -691,6 +139,5 @@ namespace System.Security
         public object PermitOnlySetInstance { get; set; }
         public string RefusedSet { get; set; }
         public string Url { get; set; }
-#endif // !FEATURE_CAS_POLICY
     }
 }
index 74be29e..933fe0b 100644 (file)
@@ -143,16 +143,13 @@ namespace System.Security
         }
 #pragma warning restore 618
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal static extern bool IsSameType(String strLeft, String strRight);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool _SetThreadSecurity(bool bThreadSecurity);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal static extern void GetGrantedPermissions(ObjectHandleOnStack retGranted, ObjectHandleOnStack retDenied, StackCrawlMarkHandle stackMark);
index 9d776af..d037fe9 100644 (file)
@@ -4,7 +4,8 @@
 
 // 
 
-namespace System.Security {
+namespace System.Security
+{
     using System;
     using System.Globalization;
     using System.Threading;
@@ -26,7 +27,6 @@ namespace System.Security {
         //
         // Internal only, do not doc.
         // 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern 
         FrameSecurityDescriptor GetSecurityObjectForFrame(ref StackCrawlMark stackMark,
@@ -37,7 +37,6 @@ namespace System.Security {
         internal const bool StackHalt      = false;
 
         // this method is a big perf hit, so don't call unnecessarily
-        [System.Security.SecurityCritical]  // auto-generated
         internal static MethodInfo GetMethodInfo(RuntimeMethodHandleInternal rmh)
         {
             if (rmh.IsNullHandle())
@@ -60,7 +59,6 @@ namespace System.Security {
 #endif
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static bool FrameDescSetHelper(FrameSecurityDescriptor secDesc,
                                                PermissionSet demandSet,
                                                out PermissionSet alteredDemandSet,
@@ -69,7 +67,6 @@ namespace System.Security {
             return secDesc.CheckSetDemand(demandSet, out alteredDemandSet, rmh);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static bool FrameDescHelper(FrameSecurityDescriptor secDesc,
                                                IPermission demandIn, 
                                                PermissionToken permToken,
@@ -79,7 +76,6 @@ namespace System.Security {
         }
 
 #if FEATURE_COMPRESSEDSTACK
-        [System.Security.SecurityCritical]
         private static bool CheckDynamicMethodSetHelper(System.Reflection.Emit.DynamicResolver dynamicResolver,
                                                      PermissionSet demandSet,
                                                      out PermissionSet alteredDemandSet,
@@ -99,7 +95,6 @@ namespace System.Security {
             return result;
         }
 
-        [System.Security.SecurityCritical]
         private static bool CheckDynamicMethodHelper(System.Reflection.Emit.DynamicResolver dynamicResolver,
                                              IPermission demandIn, 
                                              PermissionToken permToken,
@@ -122,176 +117,41 @@ namespace System.Security {
         //
         // API for PermissionSets
         //
-        
-        [System.Security.SecurityCritical]  // auto-generated
+
         internal static void Assert(PermissionSet permSet, ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            // Note: if the "AssertPermission" is not a permission that implements IUnrestrictedPermission
-            // you need to change the fourth parameter to a zero.
-            FrameSecurityDescriptor secObj = CodeAccessSecurityEngine.CheckNReturnSO(
-                                                CodeAccessSecurityEngine.AssertPermissionToken,
-                                                CodeAccessSecurityEngine.AssertPermission,
-                                                ref stackMark,
-                                                1 );
-            
-            Contract.Assert(secObj != null,"Failure in SecurityRuntime.Assert() - secObj != null");
-            if (secObj == null)
-            {
-                // Security: REQ_SQ flag is missing. Bad compiler ?
-                System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-            else
-            {
-                if (secObj.HasImperativeAsserts())
-                    throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
-                secObj.SetAssert(permSet);
-            }
-#endif // FEATURE_CAS_POLICY
         }
-    
-        [System.Security.SecurityCritical]  // auto-generated
+
         internal static void AssertAllPossible(ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            FrameSecurityDescriptor secObj =
-                SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
-    
-            Contract.Assert(secObj != null, "Failure in SecurityRuntime.AssertAllPossible() - secObj != null");
-            if (secObj == null)
-            {
-                // Security: REQ_SQ flag is missing. Bad compiler ?
-                System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-            else
-            {
-                if (secObj.GetAssertAllPossible())
-                    throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
-                secObj.SetAssertAllPossible();
-            }
-#endif // FEATURE_CAS_POLICY
         }
-    
-        [System.Security.SecurityCritical]  // auto-generated
+
         internal static void Deny(PermissionSet permSet, ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            // Deny is only valid in legacy mode
-            if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
-            {
-                throw new NotSupportedException(Environment.GetResourceString("NotSupported_CasDeny"));
-            }
-
-            FrameSecurityDescriptor secObj =
-                SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
-    
-            Contract.Assert(secObj != null, "Failure in SecurityRuntime.Deny() - secObj != null");
-            if (secObj == null)
-            {
-                // Security: REQ_SQ flag is missing. Bad compiler ?
-                System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-            else
-            {
-                if (secObj.HasImperativeDenials())
-                    throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
-                secObj.SetDeny(permSet);
-            }
-#endif // FEATURE_CAS_POLICY
         }
-    
-        [System.Security.SecurityCritical]  // auto-generated
+
         internal static void PermitOnly(PermissionSet permSet, ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            FrameSecurityDescriptor secObj =
-                SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
-    
-            Contract.Assert(secObj != null, "Failure in SecurityRuntime.PermitOnly() - secObj != null");
-            if (secObj == null)
-            {
-                // Security: REQ_SQ flag is missing. Bad compiler ?
-                System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-            else
-            {
-                if (secObj.HasImperativeRestrictions())
-                    throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
-                secObj.SetPermitOnly(permSet);
-            }
-#endif // FEATURE_CAS_POLICY
         }
-    
+
         //
         // Revert API
         //
-        
-        [System.Security.SecurityCritical]  // auto-generated
+
         internal static void RevertAssert(ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
-            if (secObj != null)
-            {
-                secObj.RevertAssert();
-            }
-            else
-            {
-                throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-#endif // FEATURE_CAS_POLICY
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void RevertDeny(ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
-            if (secObj != null)
-            {
-                secObj.RevertDeny();
-            }
-            else
-            {
-                throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-#endif // FEATURE_CAS_POLICY
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void RevertPermitOnly(ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
-            if (secObj != null)
-            {
-                secObj.RevertPermitOnly();
-            }
-            else
-            {
-                throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-#endif // FEATURE_CAS_POLICY
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void RevertAll(ref StackCrawlMark stackMark)
         {
-#if FEATURE_CAS_POLICY
-            FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
-            if (secObj != null)
-            {
-                secObj.RevertAll();
-            }
-            else
-            {
-                throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
-            }
-#endif // FEATURE_CAS_POLICY
         }
     }
 }
index bd23acd..3c7f8bf 100644 (file)
@@ -7,25 +7,17 @@ using System.Security.Permissions;
 
 namespace System.Security
 {
-    [System.Security.SecurityCritical]  // auto-generated_required
-#pragma warning disable 618
-    [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
     public abstract class SecurityState
     {
         protected SecurityState(){}
         
-        [System.Security.SecurityCritical]  // auto-generated
         public bool IsStateAvailable()
         {
             AppDomainManager domainManager = AppDomainManager.CurrentAppDomainManager;
-#if FEATURE_CORECLR
+
             // CheckSecuritySettings only when appdomainManager is present. So if there is no 
             // appDomain Manager return true as by default coreclr runs in fulltrust. 
             return domainManager != null ? domainManager.CheckSecuritySettings(this) : true;
-#else
-            return domainManager != null ? domainManager.CheckSecuritySettings(this) : false;
-#endif
         }
         // override this function and throw the appropriate 
         public abstract void EnsureState();
index 988a39a..afc9b8c 100644 (file)
@@ -37,7 +37,6 @@ namespace System.Security.Util {
         private static volatile string m_machineConfig;
         private static volatile string m_userConfig;
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static void GetFileLocales()
         {
             if (m_machineConfig == null)
@@ -56,7 +55,6 @@ namespace System.Security.Util {
 
         internal static string MachineDirectory
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 GetFileLocales();
@@ -66,7 +64,6 @@ namespace System.Security.Util {
 
         internal static string UserDirectory
         {
-            [System.Security.SecurityCritical]  // auto-generated
             get
             {
                 GetFileLocales();
@@ -74,57 +71,12 @@ namespace System.Security.Util {
             }
         }
 
-#if FEATURE_CAS_POLICY
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        internal static extern int SaveDataByte(string path, [In] byte[] data, int length);
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        internal static extern bool RecoverData(ConfigId id);
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        internal static extern void SetQuickCache(ConfigId id, QuickCacheEntryType quickCacheFlags);
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        private static extern bool GetCacheEntry(ConfigId id, int numKey, [In] byte[] key, int keyLength, ObjectHandleOnStack retData);
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static bool GetCacheEntry(ConfigId id, int numKey, byte[] key, out byte[] data)
-        {
-            byte[] retData = null;
-            bool ret = GetCacheEntry(id, numKey, key, key.Length, JitHelpers.GetObjectHandleOnStack(ref retData));
-
-            data = retData;
-            return ret;
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        private static extern void AddCacheEntry(ConfigId id, int numKey, [In] byte[] key, int keyLength, byte[] data, int dataLength);
-
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static void AddCacheEntry(ConfigId id, int numKey, byte[] key, byte[] data)
-        {
-            AddCacheEntry(id, numKey, key, key.Length, data, data.Length);
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
-        internal static extern void ResetCacheData(ConfigId id);
-#endif
-
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private static extern void GetMachineDirectory(StringHandleOnStack retDirectory);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private static extern void GetUserDirectory(StringHandleOnStack retDirectory);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         internal static extern bool WriteToEventLog(string message);
     }
index c12ca2f..8a12235 100644 (file)
@@ -12,6 +12,7 @@ namespace System.Security.Util {
     using System.Globalization;
     using System.Runtime.Versioning;
     using System.IO;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -26,12 +27,9 @@ namespace System.Security.Util {
         //  2. Ensuring that the partial trust code has permission to see full path data
         //  3. Not using this set for paths (eg EnvironmentStringExpressionSet)
         //
-        [SecurityCritical]
         protected ArrayList m_list;
         protected bool m_ignoreCase;
-        [SecurityCritical]
         protected String m_expressions;
-        [SecurityCritical]
         protected String[] m_expressionsArray;
 
         protected bool m_throwOnRelative;
@@ -61,7 +59,6 @@ namespace System.Security.Util {
         {
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringExpressionSet( bool ignoreCase, String str, bool throwOnRelative )
         {
             m_list = null;
@@ -78,7 +75,6 @@ namespace System.Security.Util {
             return new StringExpressionSet();
         }
         
-        [SecuritySafeCritical]
         public virtual StringExpressionSet Copy()
         {
             // SafeCritical: just copying this value around, not leaking it
@@ -118,7 +114,6 @@ namespace System.Security.Util {
             return StaticProcessSingleString(str);
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         public void AddExpressions( String str )
         {
             if (str == null)
@@ -181,16 +176,14 @@ namespace System.Security.Util {
             Reduce();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public void AddExpressions( String[] str, bool checkForDuplicates, bool needFullPath )
         {
             AddExpressions(CreateListFromExpressions(str, needFullPath), checkForDuplicates);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates)
         {
-            Contract.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" );
+            Debug.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" );
 
             m_expressionsArray = null;
             m_expressions = null;
@@ -205,7 +198,6 @@ namespace System.Security.Util {
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static ArrayList CreateListFromExpressions(String[] str, bool needFullPath)
         {
             if (str == null)
@@ -249,7 +241,6 @@ namespace System.Security.Util {
             return retArrayList;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         protected void CheckList()
         {
             if (m_list == null && m_expressions != null)
@@ -303,7 +294,6 @@ namespace System.Security.Util {
         }
 
         
-        [System.Security.SecurityCritical]  // auto-generated
         protected void CreateList()
         {
             String[] expressionsArray = Split( m_expressions );
@@ -339,7 +329,6 @@ namespace System.Security.Util {
             }
         }
         
-        [SecuritySafeCritical]
         public bool IsEmpty()
         {
             // SafeCritical: we're just showing that the expressions are empty, the sensitive portion is their
@@ -354,7 +343,6 @@ namespace System.Security.Util {
             }
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         public bool IsSubsetOf( StringExpressionSet ses )
         {
             if (this.IsEmpty())
@@ -376,7 +364,6 @@ namespace System.Security.Util {
             return true;
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         public bool IsSubsetOfPathDiscovery( StringExpressionSet ses )
         {
             if (this.IsEmpty())
@@ -399,7 +386,6 @@ namespace System.Security.Util {
         }
 
         
-        [System.Security.SecurityCritical]  // auto-generated
         public StringExpressionSet Union( StringExpressionSet ses )
         {
             // If either set is empty, the union represents a copy of the other.
@@ -434,7 +420,6 @@ namespace System.Security.Util {
         }
             
         
-        [System.Security.SecurityCritical]  // auto-generated
         public StringExpressionSet Intersect( StringExpressionSet ses )
         {
             // If either set is empty, the intersection is empty
@@ -477,7 +462,6 @@ namespace System.Security.Util {
             return intersectSet;
         }
         
-        [SecuritySafeCritical]
         protected void GenerateString()
         {
             // SafeCritical - moves critical data around, but doesn't expose it out
@@ -522,7 +506,6 @@ namespace System.Security.Util {
         // expressions contain paths that were canonicalized and expanded from the input that would cause
         // information disclosure, so we instead only expose this out to trusted code that can ensure they
         // either don't leak the information or required full path information.
-        [SecurityCritical]
         public string UnsafeToString()
         {
             CheckList();
@@ -534,7 +517,6 @@ namespace System.Security.Util {
             return m_expressions;
         }
 
-        [SecurityCritical]
         public String[] UnsafeToStringArray()
         {
             if (m_expressionsArray == null && m_list != null)
@@ -550,7 +532,6 @@ namespace System.Security.Util {
         // protected static helper functions
         //-------------------------------
         
-        [SecurityCritical]
         private bool StringSubsetStringExpression( String left, StringExpressionSet right, bool ignoreCase )
         {
             for (int index = 0; index < right.m_list.Count; ++index)
@@ -563,7 +544,6 @@ namespace System.Security.Util {
             return false;
         }
         
-        [SecurityCritical]
         private static bool StringSubsetStringExpressionPathDiscovery( String left, StringExpressionSet right, bool ignoreCase )
         {
             for (int index = 0; index < right.m_list.Count; ++index)
@@ -661,7 +641,6 @@ namespace System.Security.Util {
         // protected helper functions
         //-------------------------------
         
-        [SecuritySafeCritical]
         protected void AddSingleExpressionNoDuplicates( String expression )
         {
             // SafeCritical: We're not exposing out the string sets, just allowing modification of them
@@ -691,7 +670,6 @@ namespace System.Security.Util {
             this.m_list.Add( expression );
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         protected void Reduce()
         {
             CheckList();
@@ -726,18 +704,15 @@ namespace System.Security.Util {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal static extern void GetLongPathName( String path, StringHandleOnStack retLongPath );
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static String CanonicalizePath( String path )
         {
             return CanonicalizePath( path, true );
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static string CanonicalizePath(string path, bool needFullPath)
         {
             if (needFullPath)
index 590a909..8589fa7 100644 (file)
@@ -9,6 +9,7 @@ namespace System.Security.Util
     using System.Security.Permissions;
     using System.Runtime.Serialization;
     using System.Threading;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Diagnostics.CodeAnalysis;
 
@@ -368,31 +369,17 @@ namespace System.Security.Util
             {
                 Object thisObj = this.GetItem( i );
                 IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
 
                 Object otherObj = (other != null)?other.GetItem( i ):null;
                 IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
-                ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
 
                 if (thisObj == null && otherObj == null)
                     continue;
-        
-             
+
                 if (thisObj == null)
                 {
-#if FEATURE_CAS_POLICY
-                    if (otherElem != null)
-                    {
-                        otherPerm = PermissionSet.CreatePerm(otherElem, false);
-                    }
-#endif // FEATURE_CAS_POLICY
-
                     PermissionToken token = PermissionToken.GetToken(otherPerm);
-                    
+
                     if (token == null)
                     {
                         throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
@@ -402,13 +389,6 @@ namespace System.Security.Util
                 }
                 else if (otherObj == null)
                 {
-#if FEATURE_CAS_POLICY
-                    if (thisElem != null)
-                    {
-                        thisPerm = PermissionSet.CreatePerm(thisElem, false);
-                    }
-#endif // FEATURE_CAS_POLICY
-
                     PermissionToken token = PermissionToken.GetToken(thisPerm);
                     if (token == null)
                     {
@@ -418,7 +398,7 @@ namespace System.Security.Util
                 }
                 else
                 {
-                    Contract.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" );
+                    Debug.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" );
                 }
             }
             return unionSet;
@@ -434,10 +414,6 @@ namespace System.Security.Util
                 if (obj != null)
                 {
                     IPermission perm = obj as IPermission;
-#if FEATURE_CAS_POLICY
-                    if (perm == null)
-                        perm = PermissionSet.CreatePerm(obj, ignoreTypeLoadFailures);
-#endif // FEATURE_CAS_POLICY
                     PermissionToken token = PermissionToken.GetToken(perm);
 
                     if (perm == null || token == null)
index 3eb8f8a..83f9ce4 100644 (file)
@@ -1128,7 +1128,6 @@ namespace System.Security.Util {
         }
         
 #if !PLATFORM_UNIX
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal URLString SpecialNormalizeUrl()
         {
             // Under WinXP, file protocol urls can be mapped to
@@ -1178,7 +1177,6 @@ namespace System.Security.Util {
             }
         }
                 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void GetDeviceName( String driveLetter, StringHandleOnStack retDeviceName );
index df8f0c4..3a1aaa3 100644 (file)
@@ -25,6 +25,7 @@ namespace System.Security.Util  {
     using System.Threading;
     using System.Globalization;
     using System.Reflection;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     internal static class XMLUtil
@@ -35,12 +36,7 @@ namespace System.Security.Util  {
         //
         
         private const String BuiltInPermission = "System.Security.Permissions.";
-#if FEATURE_CAS_POLICY        
-        private const String BuiltInMembershipCondition = "System.Security.Policy.";
-        private const String BuiltInCodeGroup = "System.Security.Policy.";
-        private const String BuiltInApplicationSecurityManager = "System.Security.Policy.";
-        private static readonly char[] sepChar =  {',', ' '};
-#endif        
+
         public static SecurityElement
         NewPermissionElement (IPermission ip)
         {
@@ -66,7 +62,7 @@ namespace System.Security.Util  {
         
             if ( typename == null )
                 typename = type.FullName;
-            Contract.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName);
+            Debug.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName);
             element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) );
         }
         
@@ -110,7 +106,6 @@ namespace System.Security.Util  {
             assemblyVersion = an.Version.ToString();
             return true;
         }
-        [System.Security.SecurityCritical]  // auto-generated
         private static bool
         ParseElementForObjectCreation( SecurityElement el,
                                        String requiredNamespace,
@@ -175,29 +170,6 @@ namespace System.Security.Util  {
             return false;
         }
 
-#if FEATURE_CAS_POLICY
-        public static String SecurityObjectToXmlString(Object ob)
-        {
-            if(ob == null)
-                return "";
-            PermissionSet pset = ob as PermissionSet;
-            if(pset != null)
-                return pset.ToXml().ToString();
-            return ((IPermission)ob).ToXml().ToString();
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        public static Object XmlStringToSecurityObject(String s)
-        {
-            if(s == null)
-                return null;
-            if(s.Length < 1)
-                return null;
-            return SecurityElement.FromString(s).ToSecurityObject();
-        }
-#endif // FEATURE_CAS_POLICY
-
-        [SecuritySafeCritical]
         public static IPermission
         CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures)
         {
@@ -235,9 +207,6 @@ namespace System.Security.Util  {
             // UnsafeForHostPermission
             // HostProtectionPermission
             // StrongNameIdentityPermission
-#if !FEATURE_CORECLR                              
-            // IsolatedStorageFilePermission
-#endif
             // RegistryPermission
             // PublisherIdentityPermission
 
@@ -274,15 +243,6 @@ namespace System.Security.Util  {
                         else
                             goto USEREFLECTION;
                     }
-                  
-#if !FEATURE_CORECLR              
-                case 19:
-                    // PrincipalPermission
-                    if (String.Compare(className, classNameStart, "PrincipalPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new PrincipalPermission( permState );
-                    else
-                        goto USEREFLECTION;
-#endif // !FEATURE_CORECLR
                 case 20:
                     // ReflectionPermission
                     // FileDialogPermission
@@ -326,8 +286,6 @@ namespace System.Security.Util  {
                         else
                             goto USEREFLECTION;
                     }
-
-                            
                 case 22:
                     // SiteIdentityPermission
                     // ZoneIdentityPermission
@@ -353,42 +311,22 @@ namespace System.Security.Util  {
                         else
                             goto USEREFLECTION;
                     }
-
-
                 case 24:
                     // HostProtectionPermission
                     if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
                         return new HostProtectionPermission( permState );
                     else
                         goto USEREFLECTION;
-
-#if FEATURE_X509 && FEATURE_CAS_POLICY
-                case 27:
-                    // PublisherIdentityPermission
-                    if (String.Compare(className, classNameStart, "PublisherIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new PublisherIdentityPermission( permState );
-                    else
-                        goto USEREFLECTION;
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
-
                 case 28:
                     // StrongNameIdentityPermission
                     if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
                         return new StrongNameIdentityPermission( permState );
                     else
                         goto USEREFLECTION;
-#if !FEATURE_CORECLR                                                          
-                case 29:
-                    // IsolatedStorageFilePermission
-                    if (String.Compare(className, classNameStart, "IsolatedStorageFilePermission", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new IsolatedStorageFilePermission( permState );
-                    else
-                        goto USEREFLECTION;
-#endif                            
                 default:
                     goto USEREFLECTION;
             }
-    
+
 USEREFLECTION:
 
             Object[] objs = new Object[1];
@@ -409,204 +347,6 @@ USEREFLECTION:
             return perm;
         }
 
-#if FEATURE_CAS_POLICY
-#pragma warning disable 618 // CodeGroups are obsolete
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public static CodeGroup
-        CreateCodeGroup (SecurityElement el)
-        {
-            if (el == null || !el.Tag.Equals("CodeGroup"))
-                throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<CodeGroup>" ) ) ;
-            Contract.EndContractBlock();
-    
-            String className;
-            int classNameLength;
-            int classNameStart;
-
-            if (!ParseElementForObjectCreation( el,
-                                                BuiltInCodeGroup,
-                                                out className,
-                                                out classNameStart,
-                                                out classNameLength ))
-            {
-                goto USEREFLECTION;
-            }
-    
-            switch (classNameLength)
-            {
-                case 12:
-                    // NetCodeGroup
-                    if (String.Compare(className, classNameStart, "NetCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new NetCodeGroup();
-                    else
-                        goto USEREFLECTION;
-
-                case 13:
-                    // FileCodeGroup
-                    if (String.Compare(className, classNameStart, "FileCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new FileCodeGroup();
-                    else
-                        goto USEREFLECTION;
-                case 14:
-                    // UnionCodeGroup
-                    if (String.Compare(className, classNameStart, "UnionCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new UnionCodeGroup();
-                    else
-                        goto USEREFLECTION;
-                                
-                case 19:
-                    // FirstMatchCodeGroup
-                    if (String.Compare(className, classNameStart, "FirstMatchCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new FirstMatchCodeGroup();
-                    else
-                        goto USEREFLECTION;
-
-                default:
-                    goto USEREFLECTION;
-            }
-
-USEREFLECTION: 
-            Type groupClass = null;
-            CodeGroup group = null;
-
-            new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
-            groupClass = GetClassFromElement(el, true);
-            if (groupClass == null)
-                return null;
-            if (!(typeof(CodeGroup).IsAssignableFrom(groupClass)))
-                throw new ArgumentException( Environment.GetResourceString("Argument_NotACodeGroupType") );
-
-            group = (CodeGroup) Activator.CreateInstance(groupClass, true);
-
-            Contract.Assert( groupClass.Module.Assembly != Assembly.GetExecutingAssembly(),
-                "This path should not get called for mscorlib based classes" );
-
-            return group;
-        }
-#pragma warning restore 618
-        
-        [System.Security.SecurityCritical]  // auto-generated
-        internal static IMembershipCondition
-        CreateMembershipCondition( SecurityElement el )
-        {
-            if (el == null || !el.Tag.Equals("IMembershipCondition"))
-                throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<IMembershipCondition>" ) ) ;
-            Contract.EndContractBlock();
-    
-            String className;
-            int classNameStart;
-            int classNameLength;
-            
-            if (!ParseElementForObjectCreation( el,
-                                                BuiltInMembershipCondition,
-                                                out className,
-                                                out classNameStart,
-                                                out classNameLength ))
-            {
-                goto USEREFLECTION;
-            }
-
-            // We have a built in membership condition, figure out which it is.
-                    
-            // Here's the list of built in membership conditions as of 9/17/2002
-            // System.Security.Policy.AllMembershipCondition
-            // System.Security.Policy.URLMembershipCondition
-            // System.Security.Policy.SHA1MembershipCondition
-            // System.Security.Policy.SiteMembershipCondition
-            // System.Security.Policy.ZoneMembershipCondition                                                                                                                                                              
-            // System.Security.Policy.PublisherMembershipCondition
-            // System.Security.Policy.StrongNameMembershipCondition
-            // System.Security.Policy.ApplicationMembershipCondition
-            // System.Security.Policy.DomainApplicationMembershipCondition
-            // System.Security.Policy.ApplicationDirectoryMembershipCondition
-                    
-            switch (classNameLength)
-            {
-                case 22:
-                    // AllMembershipCondition
-                    // URLMembershipCondition
-                    if (className[classNameStart] == 'A')
-                    {
-                        if (String.Compare(className, classNameStart, "AllMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
-                            return new AllMembershipCondition();
-                        else
-                            goto USEREFLECTION;
-                    }
-                    else
-                    {
-                        if (String.Compare(className, classNameStart, "UrlMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
-                            return new UrlMembershipCondition();
-                        else
-                            goto USEREFLECTION;
-                    }
-                                
-                case 23:
-                    // HashMembershipCondition
-                    // SiteMembershipCondition
-                    // ZoneMembershipCondition                                                                                                                                                              
-                    if (className[classNameStart] == 'H')
-                    {
-                        if (String.Compare(className, classNameStart, "HashMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
-                            return new HashMembershipCondition();
-                        else
-                            goto USEREFLECTION;
-                    }
-                    else if (className[classNameStart] == 'S')
-                    {
-                        if (String.Compare(className, classNameStart, "SiteMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
-                            return new SiteMembershipCondition();
-                        else
-                            goto USEREFLECTION;
-                    }
-                    else
-                    {
-                        if (String.Compare(className, classNameStart, "ZoneMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
-                            return new ZoneMembershipCondition();
-                        else
-                            goto USEREFLECTION;
-                    }
-
-                case 28:
-                    // PublisherMembershipCondition
-                    if (String.Compare(className, classNameStart, "PublisherMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new PublisherMembershipCondition();
-                    else
-                        goto USEREFLECTION;
-
-                case 29:
-                    // StrongNameMembershipCondition
-                    if (String.Compare(className, classNameStart, "StrongNameMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new StrongNameMembershipCondition();
-                    else
-                        goto USEREFLECTION;
-
-                case 39:
-                    // ApplicationDirectoryMembershipCondition
-                    if (String.Compare(className, classNameStart, "ApplicationDirectoryMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
-                        return new ApplicationDirectoryMembershipCondition();
-                    else
-                        goto USEREFLECTION;
-
-                default:
-                    goto USEREFLECTION;
-            }
-
-USEREFLECTION:
-            Type condClass = null;
-            IMembershipCondition cond = null;
-    
-            new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
-            condClass = GetClassFromElement(el, true);
-            if (condClass == null)
-                return null;
-            if (!(typeof(IMembershipCondition).IsAssignableFrom(condClass)))
-                throw new ArgumentException( Environment.GetResourceString("Argument_NotAMembershipCondition") );
-
-            cond = (IMembershipCondition) Activator.CreateInstance(condClass, true);
-
-            return cond;
-        }
-#endif //#if FEATURE_CAS_POLICY
         internal static Type
         GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures)
         {
@@ -624,7 +364,7 @@ USEREFLECTION:
             {
                 try
                 {
-                    return Type.GetType(className, false, false);               
+                    return Type.GetType(className, false, false);
                 }
                 catch (SecurityException)
                 {
@@ -632,7 +372,7 @@ USEREFLECTION:
                 }
             }
             else
-                return Type.GetType(className, true, false);               
+                return Type.GetType(className, true, false);
         }
 
         public static bool
index f4216d2..548126f 100644 (file)
@@ -14,6 +14,7 @@ namespace System.Security {
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
     using Microsoft.Win32.SafeHandles;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     public sealed class SecureString: IDisposable {
@@ -293,7 +294,7 @@ namespace System.Security {
                 throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
             }
             Contract.EndContractBlock();
-            Contract.Assert(index <= Int32.MaxValue / sizeof(char));
+            Debug.Assert(index <= Int32.MaxValue / sizeof(char));
 
             EnsureNotDisposed();
             EnsureNotReadOnly();
@@ -315,7 +316,7 @@ namespace System.Security {
         private int BufferLength {
             [System.Security.SecurityCritical]  // auto-generated
             get {
-                Contract.Assert(m_buffer != null, "Buffer is not initialized!");   
+                Debug.Assert(m_buffer != null, "Buffer is not initialized!");   
                 return m_buffer.Length;
             }
         }
@@ -377,7 +378,7 @@ namespace System.Security {
 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private static uint GetAlignedSize( int size) {
-            Contract.Assert(size >= 0, "size must be non-negative");
+            Debug.Assert(size >= 0, "size must be non-negative");
 
             uint alignedSize = ((uint)size / BlockSize) * BlockSize;
             if( (size % BlockSize != 0) || size == 0) {  // if size is 0, set allocated size to blocksize
@@ -449,8 +450,8 @@ namespace System.Security {
         [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
         private void ProtectMemory() {            
-            Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
-            Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
+            Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
+            Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
 
             if( m_length == 0 || m_encrypted) {
                 return;
@@ -650,8 +651,8 @@ namespace System.Security {
         [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private void UnProtectMemory() {
-            Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
-            Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
+            Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
+            Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
 
             if( m_length == 0) {
                 return;
@@ -733,7 +734,7 @@ namespace System.Security {
                 source.AcquirePointer(ref sourcePtr);
                 target.AcquirePointer(ref targetPtr);
 
-                Contract.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!");
+                Debug.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!");
 
                 Buffer.Memcpy(targetPtr, sourcePtr, (int) Win32Native.SysStringLen((IntPtr)sourcePtr) * 2);
             }
index ec63a0e..cbc5c35 100644 (file)
 **
 =============================================================================*/
 
-namespace System {
-
+namespace System
+{
     using System.Threading;
     using System.Runtime.Remoting;
     using System.Security;
     using System.Security.Util;
     using System.Runtime.CompilerServices;
     using System.Runtime.ConstrainedExecution;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
-#if FEATURE_CAS_POLICY
-    using StringMaker = System.Security.Util.Tokenizer.StringMaker;
-#endif // FEATURE_CAS_POLICY
 
     internal sealed class SharedStatics
     {
@@ -40,7 +38,6 @@ namespace System {
         private volatile String _Remoting_Identity_IDGuid;
         public static String Remoting_Identity_IDGuid 
         { 
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get 
             {
                 if (_sharedStatics._Remoting_Identity_IDGuid == null)
@@ -61,63 +58,12 @@ namespace System {
                     }
                 }
 
-                Contract.Assert(_sharedStatics._Remoting_Identity_IDGuid != null,
+                Debug.Assert(_sharedStatics._Remoting_Identity_IDGuid != null,
                                 "_sharedStatics._Remoting_Identity_IDGuid != null");
                 return _sharedStatics._Remoting_Identity_IDGuid;
             } 
         }
 
-#if FEATURE_CAS_POLICY
-        private StringMaker _maker;
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        static public StringMaker GetSharedStringMaker()
-        {
-            StringMaker maker = null;
-            
-            bool tookLock = false;
-            RuntimeHelpers.PrepareConstrainedRegions();
-            try {
-                Monitor.Enter(_sharedStatics, ref tookLock);
-
-                if (_sharedStatics._maker != null)
-                {
-                    maker = _sharedStatics._maker;
-                    _sharedStatics._maker = null;
-                }
-            }
-            finally {
-                if (tookLock)
-                    Monitor.Exit(_sharedStatics);
-            }
-            
-            if (maker == null)
-            {
-                maker = new StringMaker();
-            }
-            
-            return maker;
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        static public void ReleaseSharedStringMaker(ref StringMaker maker)
-        {
-            // save this stringmaker so someone else can use it
-            bool tookLock = false;
-            RuntimeHelpers.PrepareConstrainedRegions();
-            try
-            {
-                Monitor.Enter(_sharedStatics, ref tookLock);
-
-                _sharedStatics._maker = maker;
-                maker = null;
-            }
-            finally {
-                if (tookLock)
-                    Monitor.Exit(_sharedStatics);
-            }
-        }
-#endif // FEATURE_CAS_POLICY
-
         // Note this may not need to be process-wide.
         private int _Remoting_Identity_IDSeqNum;
         internal static int Remoting_Identity_GetNextSeqNum()
@@ -140,7 +86,7 @@ namespace System {
 
         internal static ulong MemoryFailPointReservedMemory {
             get { 
-                Contract.Assert(Volatile.Read(ref _sharedStatics._memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!");
+                Debug.Assert(Volatile.Read(ref _sharedStatics._memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!");
                 return (ulong) Volatile.Read(ref _sharedStatics._memFailPointReservedMemory);
             }
         }
index a2d3b13..481c088 100644 (file)
@@ -40,21 +40,18 @@ namespace System {
         internal static float NegativeZero = BitConverter.Int32BitsToSingle(unchecked((int)0x80000000));
         
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool IsInfinity(float f) {
             return (*(int*)(&f) & 0x7FFFFFFF) == 0x7F800000;
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool IsPositiveInfinity(float f) {
             return *(int*)(&f) == 0x7F800000;
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool IsNegativeInfinity(float f) {
             return *(int*)(&f) == unchecked((int)0xFF800000);
@@ -62,14 +59,12 @@ namespace System {
 
         [Pure]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool IsNaN(float f) {
             return (*(int*)(&f) & 0x7FFFFFFF) > 0x7F800000;
         }
         
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static bool IsNegative(float f) {
             return (*(uint*)(&f) & 0x80000000) == 0x80000000;
         }
@@ -163,7 +158,6 @@ namespace System {
             return IsNaN(obj) && IsNaN(m_value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe override int GetHashCode() {
             float f = m_value;
             if (f == 0) {
@@ -174,25 +168,21 @@ namespace System {
             return v;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format, IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider));
index 21785cd..f1d57d3 100644 (file)
@@ -6,6 +6,8 @@ using System.Collections.Generic;
 using System.Diagnostics;
 using System.Runtime.CompilerServices;
 
+#pragma warning disable 0809  //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
+
 namespace System
 {
     /// <summary>
@@ -26,7 +28,7 @@ namespace System
         /// <param name="array">The target array.</param>
         /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
         /// reference (Nothing in Visual Basic).</exception>
-        /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant.</exception>
+        /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
         public Span(T[] array)
         {
             if (array == null)
@@ -48,7 +50,7 @@ namespace System
         /// <param name="start">The index at which to begin the span.</param>
         /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
         /// reference (Nothing in Visual Basic).</exception>
-        /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant.</exception>
+        /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
         /// <exception cref="System.ArgumentOutOfRangeException">
         /// Thrown when the specified <paramref name="start"/> is not in the range (&lt;0 or &gt;=Length).
         /// </exception>
@@ -76,7 +78,7 @@ namespace System
         /// <param name="length">The number of items in the span.</param>
         /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
         /// reference (Nothing in Visual Basic).</exception>
-        /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant.</exception>
+        /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
         /// <exception cref="System.ArgumentOutOfRangeException">
         /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length).
         /// </exception>
@@ -101,7 +103,7 @@ namespace System
         /// out of a void*-typed block of memory.  And the length is not checked.
         /// But if this creation is correct, then all subsequent uses are correct.
         /// </summary>
-        /// <param name="ptr">An unmanaged pointer to memory.</param>
+        /// <param name="pointer">An unmanaged pointer to memory.</param>
         /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
         /// <exception cref="System.ArgumentException">
         /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
@@ -140,44 +142,14 @@ namespace System
         }
 
         /// <summary>
-        /// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
-        /// </summary>
-        public static implicit operator Span<T>(T[] array)
-        {
-            return new Span<T>(array);
-        }
-
-        /// <summary>
-        /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
-        /// </summary>
-        public static implicit operator Span<T>(ArraySegment<T> arraySegment)
-        {
-            return new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
-        }
-
-        /// <summary>
         /// Gets the number of elements contained in the <see cref="Span{T}"/>
         /// </summary>
-        public int Length
-        {
-            get { return _length; }
-        }
-
-        /// <summary>
-        /// Returns an empty <see cref="Span{T}"/>
-        /// </summary>
-        public static Span<T> Empty
-        {
-            get { return default(Span<T>); }
-        }
+        public int Length => _length;
 
         /// <summary>
         /// Returns whether the <see cref="Span{T}"/> is empty.
         /// </summary>
-        public bool IsEmpty
-        {
-            get { return _length == 0; }
-        }
+        public bool IsEmpty => _length == 0;
 
         /// <summary>
         /// Fetches the element at the specified index.
@@ -204,21 +176,98 @@ namespace System
         }
 
         /// <summary>
-        /// Copies the contents of this span into a new array.  This heap
-        /// allocates, so should generally be avoided, however is sometimes
-        /// necessary to bridge the gap with APIs written in terms of arrays.
+        /// Copies the contents of this span into destination span. If the source
+        /// and destinations overlap, this method behaves as if the original values in
+        /// a temporary location before the destination is overwritten.
         /// </summary>
-        public T[] ToArray()
+        /// <param name="destination">The span to copy items into.</param>
+        /// <exception cref="System.ArgumentException">
+        /// Thrown when the destination Span is shorter than the source Span.
+        /// </exception>
+        public void CopyTo(Span<T> destination)
         {
-            if (_length == 0)
-                return Array.Empty<T>();
+            if (!TryCopyTo(destination))
+                ThrowHelper.ThrowArgumentException_DestinationTooShort();
+        }
 
-            var destination = new T[_length];
-            SpanHelper.CopyTo<T>(ref JitHelpers.GetArrayData(destination), ref DangerousGetPinnableReference(), _length);
-            return destination;
+        /// <summary>
+        /// Copies the contents of this span into destination span. If the source
+        /// and destinations overlap, this method behaves as if the original values in
+        /// a temporary location before the destination is overwritten.
+        /// </summary>
+        /// <param name="destination">The span to copy items into.</param>
+        /// <returns>If the destination span is shorter than the source span, this method
+        /// return false and no data is written to the destination.</returns>        
+        public bool TryCopyTo(Span<T> destination)
+        {
+            if ((uint)_length > (uint)destination.Length)
+                return false;
+
+            SpanHelper.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref DangerousGetPinnableReference(), _length);
+            return true;
         }
 
         /// <summary>
+        /// Returns true if left and right point at the same memory and have the same length.  Note that
+        /// this does *not* check to see if the *contents* are equal.
+        /// </summary>
+        public static bool operator ==(Span<T> left, Span<T> right) => left.Equals(right);
+
+        /// <summary>
+        /// Returns false if left and right point at the same memory and have the same length.  Note that
+        /// this does *not* check to see if the *contents* are equal.
+        /// </summary>
+        public static bool operator !=(Span<T> left, Span<T> right) => !left.Equals(right);
+
+        /// <summary>
+        /// Checks to see if two spans point at the same memory.  Note that
+        /// this does *not* check to see if the *contents* are equal.
+        /// </summary>
+        public bool Equals(Span<T> other)
+        {
+            return (_length == other.Length) &&
+                (_length == 0 || Unsafe.AreSame(ref DangerousGetPinnableReference(), ref other.DangerousGetPinnableReference()));
+        }
+
+        /// <summary>
+        /// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
+        /// <exception cref="System.NotSupportedException">
+        /// Always thrown by this method.
+        /// </exception>
+        /// </summary>
+        [Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
+        public override bool Equals(object obj)
+        {
+            ThrowHelper.ThrowNotSupportedException_CannotCallEqualsOnSpan();
+            // Prevent compiler error CS0161: 'Span<T>.Equals(object)': not all code paths return a value
+            return default(bool); 
+        }
+
+        /// <summary>
+        /// This method is not supported as spans cannot be boxed.
+        /// <exception cref="System.NotSupportedException">
+        /// Always thrown by this method.
+        /// </exception>
+        /// </summary>
+        [Obsolete("GetHashCode() on Span will always throw an exception.")]
+        public override int GetHashCode()
+        {
+            ThrowHelper.ThrowNotSupportedException_CannotCallGetHashCodeOnSpan();
+            // Prevent compiler error CS0161: 'Span<T>.GetHashCode()': not all code paths return a value
+            return default(int); 
+        }
+
+        /// <summary>
+        /// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
+        /// </summary>
+        public static implicit operator Span<T>(T[] array) => new Span<T>(array);
+
+        /// <summary>
+        /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
+        /// </summary>
+        public static implicit operator Span<T>(ArraySegment<T> arraySegment) =>  new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+
+        /// <summary>
         /// Forms a slice out of the given span, beginning at 'start'.
         /// </summary>
         /// <param name="start">The index at which to begin this slice.</param>
@@ -238,7 +287,7 @@ namespace System
         /// Forms a slice out of the given span, beginning at 'start', of given length
         /// </summary>
         /// <param name="start">The index at which to begin this slice.</param>
-        /// <param name="end">The index at which to end this slice (exclusive).</param>
+        /// <param name="length">The desired length for the slice (exclusive).</param>
         /// <exception cref="System.ArgumentOutOfRangeException">
         /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;&eq;Length).
         /// </exception>
@@ -252,39 +301,24 @@ namespace System
         }
 
         /// <summary>
-        /// Checks to see if two spans point at the same memory.  Note that
-        /// this does *not* check to see if the *contents* are equal.
-        /// </summary>
-        public bool Equals(Span<T> other)
-        {
-            return (_length == other.Length) &&
-                (_length == 0 || Unsafe.AreSame(ref DangerousGetPinnableReference(), ref other.DangerousGetPinnableReference()));
-        }
-
-        /// <summary>
-        /// Copies the contents of this span into destination span. The destination
-        /// must be at least as big as the source, and may be bigger.
+        /// Copies the contents of this span into a new array.  This heap
+        /// allocates, so should generally be avoided, however it is sometimes
+        /// necessary to bridge the gap with APIs written in terms of arrays.
         /// </summary>
-        /// <param name="destination">The span to copy items into.</param>
-        public bool TryCopyTo(Span<T> destination)
+        public T[] ToArray()
         {
-            if ((uint)_length > (uint)destination.Length)
-                return false;
+            if (_length == 0)
+                return Array.Empty<T>();
 
-            SpanHelper.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref DangerousGetPinnableReference(), _length);
-            return true;
+            var destination = new T[_length];
+            SpanHelper.CopyTo<T>(ref JitHelpers.GetArrayData(destination), ref DangerousGetPinnableReference(), _length);
+            return destination;
         }
 
-        /// <exception cref="System.ArgumentOutOfRangeException">
-        /// Thrown when the specified <paramref name="values"/>'s Length is longer than source span's Length.
-        /// </exception>
-        public void Set(ReadOnlySpan<T> values)
-        {
-            if ((uint)values.Length > (uint)_length)
-                ThrowHelper.ThrowArgumentOutOfRangeException();
-
-            SpanHelper.CopyTo<T>(ref DangerousGetPinnableReference(), ref values.DangerousGetPinnableReference(), values.Length);
-        }
+        // <summary>
+        /// Returns an empty <see cref="Span{T}"/>
+        /// </summary>
+        public static Span<T> Empty => default(Span<T>);
     }
 
     public static class SpanExtensions
index 4d352af..da99170 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Collections;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Globalization;
 using System.Runtime.CompilerServices;
@@ -17,7 +18,6 @@ namespace System
         //Native Static Methods
         //
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static int CompareOrdinalIgnoreCaseHelper(String strA, String strB)
         {
             Contract.Requires(strA != null);
@@ -35,7 +35,7 @@ namespace System
                     int charA = *a;
                     int charB = *b;
 
-                    Contract.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
+                    Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
 
                     // uppercase both chars - notice that we need just one compare per char
                     if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
@@ -55,13 +55,11 @@ namespace System
         }
 
         // native call to COMString::CompareOrdinalEx
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int CompareOrdinalHelper(String strA, int indexA, int countA, String strB, int indexB, int countB);
 
         //This will not work in case-insensitive mode for any character greater than 0x80.  
         //We'll throw an ArgumentException.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe internal static extern int nativeCompareOrdinalIgnoreCaseWC(String strA, sbyte *strBBytes);
 
@@ -75,7 +73,6 @@ namespace System
         // Search/Query methods
         //
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private unsafe static bool EqualsHelper(String strA, String strB)
         {
@@ -137,7 +134,6 @@ namespace System
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith)
         {
@@ -155,7 +151,7 @@ namespace System
 #if BIT64
                 // Single int read aligns pointers for the following long reads
                 // No length check needed as this method is called when length >= 2
-                Contract.Assert(length >= 2);
+                Debug.Assert(length >= 2);
                 if (*(int*)a != *(int*)b) goto ReturnFalse;
                 length -= 2; a += 2; b += 2;
 
@@ -194,7 +190,6 @@ namespace System
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe static int CompareOrdinalHelper(String strA, String strB)
         {
             Contract.Requires(strA != null);
@@ -202,7 +197,7 @@ namespace System
 
             // NOTE: This may be subject to change if eliminating the check
             // in the callers makes them small enough to be inlined by the JIT
-            Contract.Assert(strA.m_firstChar == strB.m_firstChar,
+            Debug.Assert(strA.m_firstChar == strB.m_firstChar,
                 "For performance reasons, callers of this method should " +
                 "check/short-circuit beforehand if the first char is the same.");
 
@@ -310,7 +305,7 @@ namespace System
                 if (*a != *b) return *a - *b;
 
                 DiffOffset1:
-                Contract.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
+                Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
                 return *(a + 1) - *(b + 1);
             }
         }
@@ -342,7 +337,6 @@ namespace System
         // Provides a more flexible function for string comparision. See StringComparison 
         // for meaning of different comparisonType.
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static int Compare(String strA, String strB, StringComparison comparisonType) 
         {
             // Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase]
@@ -532,7 +526,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType) {
             if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) {
                 throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
@@ -638,7 +631,6 @@ namespace System
         // Compares strA and strB using an ordinal (code-point) comparison.
         //
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length)
         {
             if (strA == null || strB == null)
@@ -724,7 +716,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ComVisible(false)]
         public Boolean EndsWith(String value, StringComparison comparisonType) {
             if( (Object)value == null) {
@@ -846,7 +837,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public bool Equals(String value, StringComparison comparisonType) {
             if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
                 throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
@@ -915,7 +905,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool Equals(String a, String b, StringComparison comparisonType) {
             if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
                 throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
@@ -981,16 +970,13 @@ namespace System
 #if FEATURE_RANDOMIZED_STRING_HASHING
         // Do not remove!
         // This method is called by reflection in System.Xml
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern int InternalMarvin32HashString(string s, int strLen, long additionalEntropy);
 
-        [System.Security.SecuritySafeCritical]
         internal static bool UseRandomizedHashing() {
             return InternalUseRandomizedHashing();
         }
 
-        [System.Security.SecurityCritical]
         [System.Security.SuppressUnmanagedCodeSecurity]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         private static extern bool InternalUseRandomizedHashing();
@@ -998,7 +984,6 @@ namespace System
 
         // Gets a hash code for this string.  If strings A and B are such that A.Equals(B), then
         // they will return the same hash code.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public override int GetHashCode()
         {
@@ -1014,13 +999,12 @@ namespace System
 
         // Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile
         // hash table).
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         internal int GetLegacyNonRandomizedHashCode() {
             unsafe {
                 fixed (char* src = &m_firstChar) {
-                    Contract.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
-                    Contract.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary");
+                    Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
+                    Debug.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary");
 #if BIT64
                     int hash1 = 5381;
 #else // !BIT64 (32)
@@ -1080,7 +1064,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ComVisible(false)]
         public Boolean StartsWith(String value, StringComparison comparisonType) {
             if( (Object)value == null) {
index e1bf4be..194b4f8 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Globalization;
 using System.Runtime.CompilerServices;
@@ -17,7 +18,6 @@ namespace System
         private const int TrimTail = 1;
         private const int TrimBoth = 2;
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe private static void FillStringChecked(String dest, int destPos, String src)
         {
             Contract.Requires(dest != null);
@@ -109,7 +109,6 @@ namespace System
             return Concat(objArgs);
         }
 
-        [System.Security.SecuritySafeCritical]
         public static string Concat(params object[] args)
         {
             if (args == null)
@@ -167,8 +166,8 @@ namespace System
             {
                 string s = strings[i];
 
-                Contract.Assert(s != null);
-                Contract.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!");
+                Debug.Assert(s != null);
+                Debug.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!");
 
                 FillStringChecked(result, position, s);
                 position += s.Length;
@@ -262,7 +261,6 @@ namespace System
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String Concat(String str0, String str1) {
             Contract.Ensures(Contract.Result<String>() != null);
             Contract.Ensures(Contract.Result<String>().Length ==
@@ -291,7 +289,6 @@ namespace System
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String Concat(String str0, String str1, String str2) {
             Contract.Ensures(Contract.Result<String>() != null);
             Contract.Ensures(Contract.Result<String>().Length ==
@@ -325,7 +322,6 @@ namespace System
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String Concat(String str0, String str1, String str2, String str3) {
             Contract.Ensures(Contract.Result<String>() != null);
             Contract.Ensures(Contract.Result<String>().Length == 
@@ -366,7 +362,6 @@ namespace System
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]
         public static String Concat(params String[] values) {
             if (values == null)
                 throw new ArgumentNullException(nameof(values));
@@ -502,7 +497,6 @@ namespace System
                     .AppendFormatHelper(provider, format, args));
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String Insert(int startIndex, String value)
         {
             if (value == null)
@@ -643,7 +637,6 @@ namespace System
 
         // Joins an array of strings together as one string with a separator between each original string.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static string Join(string separator, string[] value, int startIndex, int count)
         {
             separator = separator ?? string.Empty;
@@ -745,8 +738,8 @@ namespace System
         {
             // If the separator is null, it is converted to an empty string before entering this function.
             // Even for empty strings, fixed should never return null (it should return a pointer to a null char).
-            Contract.Assert(separator != null);
-            Contract.Assert(separatorLength >= 0);
+            Debug.Assert(separator != null);
+            Debug.Assert(separatorLength >= 0);
 
             if (value == null)
             {
@@ -858,7 +851,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String PadLeft(int totalWidth, char paddingChar) {
             if (totalWidth < 0)
                 throw new ArgumentOutOfRangeException(nameof(totalWidth), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -888,7 +880,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String PadRight(int totalWidth, char paddingChar) {
             if (totalWidth < 0)
                 throw new ArgumentOutOfRangeException(nameof(totalWidth), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -912,7 +903,6 @@ namespace System
             return result;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String Remove(int startIndex, int count)
         {
             if (startIndex < 0)
@@ -969,7 +959,6 @@ namespace System
 
         // Replaces all instances of oldChar with newChar.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String Replace(char oldChar, char newChar)
         {
             Contract.Ensures(Contract.Result<String>() != null);
@@ -1040,7 +1029,6 @@ namespace System
 
         // This method contains the same functionality as StringBuilder Replace. The only difference is that
         // a new String has to be allocated since Strings are immutable
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern String ReplaceInternal(String oldValue, String newValue);
 
@@ -1110,13 +1098,11 @@ namespace System
             return SplitInternal(separator, count, options);
         }
 
-        [System.Security.SecuritySafeCritical]
         private unsafe String[] SplitInternal(char separator, int count, StringSplitOptions options)
         {
             return SplitInternal(&separator, 1, count, options);
         }
 
-        [System.Security.SecuritySafeCritical]
         private unsafe String[] SplitInternal(char[] separator, int count, StringSplitOptions options)
         {
             fixed (char* pSeparators = separator)
@@ -1126,7 +1112,6 @@ namespace System
             }
         }
 
-        [System.Security.SecurityCritical]
         private unsafe String[] SplitInternal(char* separators, int separatorsLength, int count, StringSplitOptions options)
         {
             if (count < 0)
@@ -1141,14 +1126,8 @@ namespace System
             bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);
 
             if ((count == 0) || (omitEmptyEntries && this.Length == 0)) 
-            {           
-#if FEATURE_CORECLR
+            {
                 return EmptyArray<String>.Value;
-#else
-                // Keep the old behavior of returning a new empty array
-                // to mitigate any potential compat risk.
-                return new String[0];
-#endif
             }
 
             if (count == 1)
@@ -1156,13 +1135,13 @@ namespace System
                 return new String[] { this };
             }
             
-            int[] sepList = new int[Length];            
+            int[] sepList = new int[Length];
             int numReplaces = MakeSeparatorList(separators, separatorsLength, sepList);
             
             // Handle the special case of no replaces.
             if (0 == numReplaces) {
                 return new String[] { this };
-            }            
+            }
 
             if(omitEmptyEntries) 
             {
@@ -1171,7 +1150,7 @@ namespace System
             else 
             {
                 return SplitKeepEmptyEntries(sepList, null, 1, numReplaces, count);
-            }            
+            }
         }
 
         [ComVisible(false)]
@@ -1219,13 +1198,7 @@ namespace System
             }
             
             if ((count == 0) || (omitEmptyEntries && this.Length ==0)) {
-#if FEATURE_CORECLR
                 return EmptyArray<String>.Value;
-#else
-                // Keep the old behavior of returning a new empty array
-                // to mitigate any potential compat risk.
-                return new String[0];
-#endif
             }
 
             if (count == 1 || (singleSeparator && separator.Length == 0)) {
@@ -1332,7 +1305,7 @@ namespace System
             }
 
             // we must have at least one slot left to fill in the last string.
-            Contract.Assert(arrIndex < maxItems);
+            Debug.Assert(arrIndex < maxItems);
 
             //Handle the last string at the end of the array if there is one.
             if (currIndex< Length) {                
@@ -1355,9 +1328,8 @@ namespace System
         // Args: separator  -- A string containing all of the split characters.
         //       sepList    -- an array of ints for split char indicies.
         //--------------------------------------------------------------------    
-        [System.Security.SecurityCritical]
         private unsafe int MakeSeparatorList(char* separators, int separatorsLength, int[] sepList) {
-            Contract.Assert(separatorsLength >= 0, "separatorsLength >= 0");
+            Debug.Assert(separatorsLength >= 0, "separatorsLength >= 0");
             int foundCount=0;
 
             if (separators == null || separatorsLength == 0) {
@@ -1394,9 +1366,8 @@ namespace System
         // Args: separator  -- the separator
         //       sepList    -- an array of ints for split string indicies.
         //--------------------------------------------------------------------
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe int MakeSeparatorList(string separator, int[] sepList) {
-            Contract.Assert(!string.IsNullOrEmpty(separator), "!string.IsNullOrEmpty(separator)");
+            Debug.Assert(!string.IsNullOrEmpty(separator), "!string.IsNullOrEmpty(separator)");
 
             int foundCount = 0;
             int sepListCount = sepList.Length;
@@ -1424,9 +1395,8 @@ namespace System
         //       sepList    -- an array of ints for split string indicies.
         //       lengthList -- an array of ints for split string lengths.
         //--------------------------------------------------------------------    
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private unsafe int MakeSeparatorList(String[] separators, int[] sepList, int[] lengthList) {
-            Contract.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0");
+            Debug.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0");
             
             int foundCount = 0;
             int sepListCount = sepList.Length;
@@ -1464,7 +1434,6 @@ namespace System
     
         // Returns a substring of this string.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String Substring(int startIndex, int length) {
                     
             //Bounds Checking.
@@ -1496,10 +1465,9 @@ namespace System
             return InternalSubString(startIndex, length);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         unsafe string InternalSubString(int startIndex, int length) {
-            Contract.Assert( startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!");
-            Contract.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!");            
+            Debug.Assert( startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!");
+            Debug.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!");            
             
             String result = FastAllocateString(length);
 
@@ -1607,7 +1575,6 @@ namespace System
         }
 
        
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private String TrimHelper(int trimType) {
             //end will point to the first non-trimmed character on the right
             //start will point to the first non-trimmed character on the Left
@@ -1631,7 +1598,6 @@ namespace System
         }
     
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private String TrimHelper(char[] trimChars, int trimType) {
             //end will point to the first non-trimmed character on the right
             //start will point to the first non-trimmed character on the Left
@@ -1669,7 +1635,6 @@ namespace System
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         private String CreateTrimmedString(int start, int end) {
             int len = end -start + 1;
             if (len == this.Length) {
index 30933db..2620cfd 100644 (file)
@@ -29,7 +29,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe int IndexOf(char value, int startIndex, int count) {
             if (startIndex < 0 || startIndex > Length)
                 throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
@@ -85,7 +84,6 @@ namespace System
         }
     
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern int IndexOfAny(char [] anyOf, int startIndex, int count);
     
@@ -138,7 +136,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]
         public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) {
             // Validate inputs
             if (value == null)
@@ -194,7 +191,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe int LastIndexOf(char value, int startIndex, int count) {
             if (Length == 0)
                 return -1;
@@ -258,7 +254,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern int LastIndexOfAny(char [] anyOf, int startIndex, int count);
     
@@ -299,7 +294,6 @@ namespace System
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]
         public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) {
             if (value == null)
                 throw new ArgumentNullException(nameof(value));
index f39ca98..f9162ff 100644 (file)
@@ -24,6 +24,7 @@ namespace System {
     using System.Runtime.InteropServices;    
     using System.Runtime.Versioning;
     using Microsoft.Win32;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Security;
 
@@ -67,7 +68,6 @@ namespace System {
         // than 0x80) before security is fully initialized.  Without security initialized, we can't grab resources (the nlp's)
         // from the assembly.  This provides a workaround for that problem and should NOT be used anywhere else.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal unsafe static string SmallCharToUpper(string strIn) {
             Contract.Requires(strIn != null);
             Contract.EndContractBlock();
@@ -83,7 +83,7 @@ namespace System {
 
                 for(int i = 0; i < length; i++) {
                     int c = inBuff[i];
-                    Contract.Assert(c <= 0x7F, "string has to be ASCII");
+                    Debug.Assert(c <= 0x7F, "string has to be ASCII");
 
                     // uppercase - notice that we need just one compare
                     if ((uint)(c - 'a') <= (uint)('z' - 'a')) c -= 0x20;
@@ -91,7 +91,7 @@ namespace System {
                     outBuff[i] = (char)c;
                 }
 
-                Contract.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'");
+                Debug.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'");
             }
             return strOut;
         }
@@ -102,7 +102,6 @@ namespace System {
         [System.Runtime.CompilerServices.IndexerName("Chars")]
         public extern char this[int index] {
             [MethodImpl(MethodImplOptions.InternalCall)]
-            [System.Security.SecuritySafeCritical] // public member
             get;
         }
 
@@ -111,7 +110,6 @@ namespace System {
         // sourceIndex + count - 1 to the character array buffer, beginning
         // at destinationIndex.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
         {
             if (destination == null)
@@ -136,7 +134,6 @@ namespace System {
         }
         
         // Returns the entire string as an array of characters.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe public char[] ToCharArray() {
             int length = Length;
             if (length > 0)
@@ -148,17 +145,12 @@ namespace System {
                 }
                 return chars;
             }
-            
-#if FEATURE_CORECLR
+
             return Array.Empty<char>();
-#else
-            return new char[0];
-#endif
         }
     
         // Returns a substring of this string as an array of characters.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe public char[] ToCharArray(int startIndex, int length)
         {
             // Range check everything.
@@ -177,12 +169,8 @@ namespace System {
                 }
                 return chars;
             }
-            
-#if FEATURE_CORECLR
+
             return Array.Empty<char>();
-#else
-            return new char[0];
-#endif
         }
 
         [Pure]
@@ -210,7 +198,6 @@ namespace System {
         //
         // Spec#: Add postcondition in a contract assembly.  Potential perf problem.
         public extern int Length {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
             get;
         }
@@ -218,25 +205,19 @@ namespace System {
         // Creates a new string with the characters copied in from ptr. If
         // ptr is null, a 0-length string (like String.Empty) is returned.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe public extern String(char *value);
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe public extern String(char *value, int startIndex, int length);
     
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe public extern String(sbyte *value);
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe public extern String(sbyte *value, int startIndex, int length);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe public extern String(sbyte *value, int startIndex, int length, Encoding enc);
         
-        [System.Security.SecurityCritical]  // auto-generated
         unsafe static private String CreateString(sbyte *value, int startIndex, int length, Encoding enc) {            
             if (enc == null)
                 return new String(value, startIndex, length); // default to ANSI
@@ -267,7 +248,6 @@ namespace System {
         
         // Helper for encodings so they can talk to our buffer directly
         // stringLength must be the exact size we'll expect
-        [System.Security.SecurityCritical]  // auto-generated
         unsafe static internal String CreateStringFromEncoding(
             byte* bytes, int byteLength, Encoding encoding)
         {
@@ -276,7 +256,7 @@ namespace System {
 
             // Get our string length
             int stringLength = encoding.GetCharCount(bytes, byteLength, null);
-            Contract.Assert(stringLength >= 0, "stringLength >= 0");
+            Debug.Assert(stringLength >= 0, "stringLength >= 0");
             
             // They gave us an empty string if they needed one
             // 0 bytelength might be possible if there's something in an encoder
@@ -287,7 +267,7 @@ namespace System {
             fixed(char* pTempChars = &s.m_firstChar)
             {
                 int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
-                Contract.Assert(stringLength == doubleCheck, 
+                Debug.Assert(stringLength == doubleCheck, 
                     "Expected encoding.GetChars to return same length as encoding.GetCharCount");
             }
 
@@ -297,7 +277,6 @@ namespace System {
         // This is only intended to be used by char.ToString.
         // It is necessary to put the code in this class instead of Char, since m_firstChar is a private member.
         // Making m_firstChar internal would be dangerous since it would make it much easier to break String's immutability.
-        [SecuritySafeCritical]
         internal static string CreateFromChar(char c)
         {
             string result = FastAllocateString(1);
@@ -305,7 +284,6 @@ namespace System {
             return result;
         }
                 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe internal int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer,Encoding encoding)
         {
             // encoding == Encoding.UTF8
@@ -315,10 +293,9 @@ namespace System {
             }            
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe internal int ConvertToAnsi(byte *pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar)
         {
-            Contract.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
+            Debug.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
 
             const uint CP_ACP = 0;
             int nb;
@@ -363,7 +340,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public bool IsNormalized(NormalizationForm normalizationForm)
         {
 #if !FEATURE_NORM_IDNA_ONLY
@@ -391,7 +367,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String Normalize(NormalizationForm normalizationForm)
         {
 #if !FEATURE_NORM_IDNA_ONLY        
@@ -408,7 +383,6 @@ namespace System {
             return Normalization.Normalize(this, normalizationForm);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static String FastAllocateString(int length);
 
@@ -416,7 +390,6 @@ namespace System {
         // be created from the characters in value between startIndex and
         // startIndex + length - 1.
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern String(char [] value, int startIndex, int length);
     
@@ -424,17 +397,14 @@ namespace System {
         // created from the characters in value.
         //
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern String(char [] value);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static unsafe void wstrcpy(char *dmem, char *smem, int charCount)
         {
             Buffer.Memcpy((byte*)dmem, (byte*)smem, charCount * 2); // 2 used everywhere instead of sizeof(char)
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private String CtorCharArray(char [] value)
         {
             if (value != null && value.Length != 0) {
@@ -451,7 +421,6 @@ namespace System {
                 return String.Empty;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private String CtorCharArrayStartLength(char [] value, int startIndex, int length)
         {
             if (value == null)
@@ -481,7 +450,6 @@ namespace System {
                 return String.Empty;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private String CtorCharCount(char c, int count)
         {
             if (count > 0) {
@@ -522,7 +490,6 @@ namespace System {
                 throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(count)));
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static unsafe int wcslen(char *ptr)
         {
             char *end = ptr;
@@ -553,7 +520,7 @@ namespace System {
                 end += 2;
             }
 
-            Contract.Assert(end[0] == 0 || end[1] == 0);
+            Debug.Assert(end[0] == 0 || end[1] == 0);
             if (end[0] != 0) end++;
 #else // !BIT64
             // Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
@@ -610,14 +577,13 @@ namespace System {
 #endif // !BIT64
 
             FoundZero:
-            Contract.Assert(*end == 0);
+            Debug.Assert(*end == 0);
 
             int count = (int)(end - ptr);
 
             return count;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe String CtorCharPtr(char *ptr)
         {
             if (ptr == null)
@@ -628,7 +594,7 @@ namespace System {
                 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStringPtrNotAtom"));
 #endif // FEATURE_PAL
 
-            Contract.Assert(this == null, "this == null");        // this is the string constructor, we allocate it
+            Debug.Assert(this == null, "this == null");        // this is the string constructor, we allocate it
 
             try {
                 int count = wcslen(ptr);
@@ -645,7 +611,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe String CtorCharPtrStartLength(char *ptr, int startIndex, int length)
         {
             if (length < 0) {
@@ -656,7 +621,7 @@ namespace System {
                 throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
             }
             Contract.EndContractBlock();
-            Contract.Assert(this == null, "this == null");        // this is the string constructor, we allocate it
+            Debug.Assert(this == null, "this == null");        // this is the string constructor, we allocate it
 
             char *pFrom = ptr + startIndex;
             if (pFrom < ptr) {
@@ -679,7 +644,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern String(char c, int count);
 
@@ -705,7 +669,6 @@ namespace System {
             return this;
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         unsafe public static String Copy (String str) {
             if (str==null) {
                 throw new ArgumentNullException(nameof(str));
@@ -724,7 +687,6 @@ namespace System {
              return result;
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String Intern(String str) {
             if (str==null) {
                 throw new ArgumentNullException(nameof(str));
@@ -737,7 +699,6 @@ namespace System {
         }
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static String IsInterned(String str) {
             if (str==null) {
                 throw new ArgumentNullException(nameof(str));
@@ -834,20 +795,16 @@ namespace System {
 
         // Is this a string that can be compared quickly (that is it has only characters > 0x80 
         // and not a - or '
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern bool IsFastSort();
         // Is this a string that only contains characters < 0x80.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern bool IsAscii();
 
         // Set extra byte for odd-sized strings that came from interop as BSTR.
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void SetTrailByte(byte data);
         // Try to retrieve the extra byte - returns false if not present.
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern bool TryGetTrailByte(out byte data);
 
@@ -874,7 +831,6 @@ namespace System {
         }
 
          // Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe static void InternalCopy(String src, IntPtr dest,int len)
         {
             if (len == 0)
index 38964f0..af0b595 100644 (file)
@@ -385,7 +385,6 @@ namespace System {
             return x.Equals(y);
         }               
 
-        [System.Security.SecuritySafeCritical]            
         public override int GetHashCode(string obj) {
             if( obj == null) {
                 throw new ArgumentNullException(nameof(obj));
index 34745e5..26a2276 100644 (file)
@@ -16,6 +16,7 @@ namespace  System.StubHelpers {
 #endif // FEATURE_COMINTEROP
     using System.Runtime.CompilerServices;
     using System.Runtime.ConstrainedExecution;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
@@ -23,7 +24,6 @@ namespace  System.StubHelpers {
     {
         // The length of the returned array is an approximation based on the length of the input string and the system
         // character set. It is only guaranteed to be larger or equal to cbLength, don't depend on the exact value.
-        [System.Security.SecurityCritical]
         unsafe static internal byte[] DoAnsiConversion(string str, bool fBestFit, bool fThrowOnUnmappableChar, out int cbLength)
         {
             byte[] buffer = new byte[(str.Length + 1) * Marshal.SystemMaxDBCSCharSize];
@@ -34,7 +34,6 @@ namespace  System.StubHelpers {
             return buffer;
         }
 
-        [System.Security.SecurityCritical]
         unsafe static internal byte ConvertToNative(char managedChar, bool fBestFit, bool fThrowOnUnmappableChar)
         {
             int cbAllocLength = (1 + 1) * Marshal.SystemMaxDBCSCharSize;
@@ -57,7 +56,6 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class CSTRMarshaler
     {
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer)
         {
             if (null == strManaged)
@@ -109,7 +107,6 @@ namespace  System.StubHelpers {
             return (IntPtr)pbNativeBuffer;
         }  
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe string ConvertToManaged(IntPtr cstr)
         {
             if (IntPtr.Zero == cstr)
@@ -118,7 +115,6 @@ namespace  System.StubHelpers {
                 return new String((sbyte*)cstr);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal void ClearNative(IntPtr pNative)
         {
             Win32Native.CoTaskMemFree(pNative);
@@ -129,7 +125,6 @@ namespace  System.StubHelpers {
     internal static class UTF8Marshaler
     {
         const int MAX_UTF8_CHAR_SIZE = 3;
-        [System.Security.SecurityCritical]
         static internal unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer)
         {
             if (null == strManaged)
@@ -166,7 +161,6 @@ namespace  System.StubHelpers {
             return (IntPtr)pbNativeBuffer;
         }
 
-        [System.Security.SecurityCritical]
         static internal unsafe string ConvertToManaged(IntPtr cstr)
         {
             if (IntPtr.Zero == cstr)
@@ -175,7 +169,6 @@ namespace  System.StubHelpers {
             return String.CreateStringFromEncoding((byte*)cstr, nbBytes, Encoding.UTF8);
         }
 
-        [System.Security.SecurityCritical]
         static internal void ClearNative(IntPtr pNative)
         {
             if (pNative != IntPtr.Zero)
@@ -188,7 +181,6 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class UTF8BufferMarshaler
     {
-        [System.Security.SecurityCritical]
         static internal unsafe IntPtr ConvertToNative(StringBuilder sb, IntPtr pNativeBuffer, int flags)
         {
             if (null == sb)
@@ -210,7 +202,6 @@ namespace  System.StubHelpers {
             return (IntPtr)pbNativeBuffer;
         }
 
-        [System.Security.SecurityCritical]
         static internal unsafe void ConvertToManaged(StringBuilder sb, IntPtr pNative)
         {
             if (pNative == null)
@@ -241,7 +232,6 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class BSTRMarshaler
     {
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe IntPtr ConvertToNative(string strManaged, IntPtr pNativeBuffer)
         {
             if (null == strManaged)
@@ -311,7 +301,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe string ConvertToManaged(IntPtr bstr)
         {
             if (IntPtr.Zero == bstr)
@@ -356,7 +345,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal void ClearNative(IntPtr pNative)
         {
             if (IntPtr.Zero != pNative)
@@ -372,7 +360,6 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class VBByValStrMarshaler
     {
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe IntPtr ConvertToNative(string strManaged, bool fBestFit, bool fThrowOnUnmappableChar, ref int cch)
         {
             if (null == strManaged)
@@ -414,7 +401,6 @@ namespace  System.StubHelpers {
             return new IntPtr(pNative);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe string ConvertToManaged(IntPtr pNative, int cch)
         {
             if (IntPtr.Zero == pNative)
@@ -425,7 +411,6 @@ namespace  System.StubHelpers {
             return new String((sbyte*)pNative, 0, cch);
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe void ClearNative(IntPtr pNative)
         {
             if (IntPtr.Zero != pNative)
@@ -441,7 +426,6 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class AnsiBSTRMarshaler
     {
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe IntPtr ConvertToNative(int flags, string strManaged)
         {
             if (null == strManaged)
@@ -464,7 +448,6 @@ namespace  System.StubHelpers {
             return Win32Native.SysAllocStringByteLen(bytes, (uint)nb);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe string ConvertToManaged(IntPtr bstr)
         {
             if (IntPtr.Zero == bstr)
@@ -480,7 +463,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static internal unsafe void ClearNative(IntPtr pNative)
         {
             if (IntPtr.Zero != pNative)
@@ -498,19 +480,19 @@ namespace  System.StubHelpers {
     {
         static internal IntPtr ConvertToNative(string strManaged)
         {
-            Contract.Assert(false, "NYI");
+            Debug.Assert(false, "NYI");
             return IntPtr.Zero;
         }
 
         static internal unsafe string ConvertToManaged(IntPtr bstr)
         {
-            Contract.Assert(false, "NYI");
+            Debug.Assert(false, "NYI");
             return null;
         }
 
         static internal void ClearNative(IntPtr pNative)
         {
-            Contract.Assert(false, "NYI");
+            Debug.Assert(false, "NYI");
         }
     }  // class WSTRBufferMarshaler
 
@@ -531,14 +513,12 @@ namespace  System.StubHelpers {
         // You can get this through:  (new DateTimeOffset(1601, 1, 1, 0, 0, 1, TimeSpan.Zero)).Ticks;
         private const Int64 ManagedUtcTicksAtNativeZero = 504911232000000000;
 
-        [SecurityCritical]
         internal static void ConvertToNative(ref DateTimeOffset managedDTO, out DateTimeNative dateTime) {
 
             Int64 managedUtcTicks = managedDTO.UtcTicks;
             dateTime.UniversalTime = managedUtcTicks - ManagedUtcTicksAtNativeZero;
         }
 
-        [SecurityCritical]
         internal static void ConvertToManaged(out DateTimeOffset managedLocalDTO, ref DateTimeNative nativeTicks) {
 
             Int64 managedUtcTicks = ManagedUtcTicksAtNativeZero + nativeTicks.UniversalTime;
@@ -558,7 +538,6 @@ namespace  System.StubHelpers {
     internal static class HStringMarshaler
     {
         // Slow-path, which requires making a copy of the managed string into the resulting HSTRING
-        [SecurityCritical]
         internal static unsafe IntPtr ConvertToNative(string managed)
         {
             if (!Environment.IsWinRTSupported)
@@ -578,7 +557,6 @@ namespace  System.StubHelpers {
         // Note that the managed string input to this method MUST be pinned, and stay pinned for the lifetime of
         // the returned HSTRING object.  If the string is not pinned, or becomes unpinned before the HSTRING's
         // lifetime ends, the HSTRING instance will be corrupted.
-        [SecurityCritical]
         internal static unsafe IntPtr ConvertToNativeReference(string managed,
                                                                [Out] HSTRING_HEADER *hstringHeader)
         {
@@ -598,7 +576,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         internal static string ConvertToManaged(IntPtr hstring)
         {
             if (!Environment.IsWinRTSupported)
@@ -609,10 +586,9 @@ namespace  System.StubHelpers {
             return WindowsRuntimeMarshal.HStringToString(hstring);
         }
 
-        [SecurityCritical]
         internal static void ClearNative(IntPtr hstring)
         {
-            Contract.Assert(Environment.IsWinRTSupported);
+            Debug.Assert(Environment.IsWinRTSupported);
 
             if (hstring != IntPtr.Zero)
             {
@@ -639,7 +615,6 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class ValueClassMarshaler
     {
-        [SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern void ConvertToNative(IntPtr dst, IntPtr src, IntPtr pMT, ref CleanupWorkList pCleanupWorkList);
 
@@ -672,7 +647,6 @@ namespace  System.StubHelpers {
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern object ConvertToManaged(IntPtr pUnk, IntPtr itfMT, IntPtr classMT, int flags);
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall), SuppressUnmanagedCodeSecurity]
         static internal extern void ClearNative(IntPtr pUnk);
 
@@ -690,10 +664,8 @@ namespace  System.StubHelpers {
         static internal extern string GetRawUriFromNative(IntPtr pUri);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecurityCritical]
         static unsafe internal extern IntPtr CreateNativeUriInstanceHelper(char* rawUri, int strLen);
       
-    [System.Security.SecurityCritical]
         static unsafe internal IntPtr CreateNativeUriInstance(string rawUri)
         {
             fixed(char* pManaged = rawUri)
@@ -707,7 +679,6 @@ namespace  System.StubHelpers {
     [FriendAccessAllowed]
     internal static class EventArgsMarshaler
     {
-        [SecurityCritical]
         [FriendAccessAllowed]
         static internal IntPtr CreateNativeNCCEventArgsInstance(int action, object newItems, object oldItems, int newIndex, int oldIndex)
         {
@@ -733,12 +704,10 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         [FriendAccessAllowed]
         [DllImport(JitHelpers.QCall), SuppressUnmanagedCodeSecurity]
         static extern internal IntPtr CreateNativePCEventArgsInstance([MarshalAs(UnmanagedType.HString)]string name);
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall), SuppressUnmanagedCodeSecurity]
         static extern internal IntPtr CreateNativeNCCEventArgsInstanceHelper(int action, IntPtr newItem, IntPtr oldItem, int newIndex, int oldIndex);
     }
@@ -796,19 +765,15 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class MngdHiddenLengthArrayMarshaler
     {
-        [SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, IntPtr cbElementSize, ushort vt);
         
-        [SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
 
-        [SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToNative_DateTime(ref DateTimeOffset[] managedArray, IntPtr pNativeHome)
         {
             if (managedArray != null)
@@ -821,7 +786,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToNative_Type(ref System.Type[] managedArray, IntPtr pNativeHome)
         {
             if (managedArray != null)
@@ -834,7 +798,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToNative_Exception(ref Exception[] managedArray, IntPtr pNativeHome)
         {
             if (managedArray != null)
@@ -847,7 +810,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToNative_Nullable<T>(ref Nullable<T>[] managedArray, IntPtr pNativeHome)
             where T : struct
         {
@@ -861,7 +823,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToNative_KeyValuePair<K, V>(ref KeyValuePair<K, V>[] managedArray, IntPtr pNativeHome)
         {
             if (managedArray != null)
@@ -874,15 +835,12 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int elementCount);
 
-        [SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToManaged_DateTime(ref DateTimeOffset[] managedArray, IntPtr pNativeHome)
         {
             if (managedArray != null)
@@ -895,7 +853,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToManaged_Type(ref System.Type[] managedArray, IntPtr pNativeHome)
         {
             if (managedArray != null)
@@ -908,7 +865,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToManaged_Exception(ref Exception[] managedArray, IntPtr pNativeHome)
         {
             if (managedArray != null)
@@ -921,7 +877,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToManaged_Nullable<T>(ref Nullable<T>[] managedArray, IntPtr pNativeHome)
             where T : struct
         {
@@ -935,7 +890,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         internal static unsafe void ConvertContentsToManaged_KeyValuePair<K, V>(ref KeyValuePair<K, V>[] managedArray, IntPtr pNativeHome)
         {
             if (managedArray != null)
@@ -948,14 +902,12 @@ namespace  System.StubHelpers {
             }
         }
 
-        [SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void ClearNativeContents(IntPtr pMarshalState, IntPtr pNativeHome, int cElements);
 
-        [SecurityCritical]
         internal static unsafe void ClearNativeContents_Type(IntPtr pNativeHome, int cElements)
         {
-            Contract.Assert(Environment.IsWinRTSupported);
+            Debug.Assert(Environment.IsWinRTSupported);
 
             TypeNameNative *pNativeTypeArray = *(TypeNameNative **)pNativeHome;
             if (pNativeTypeArray != null)
@@ -991,7 +943,6 @@ namespace  System.StubHelpers {
     }  // class MngdRefCustomMarshaler
 
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-    [System.Security.SecurityCritical]
     internal struct AsAnyMarshaler
     {
         private const ushort VTHACK_ANSICHAR = 253;
@@ -1037,7 +988,6 @@ namespace  System.StubHelpers {
 
         #region ConvertToNative helpers
 
-        [System.Security.SecurityCritical]
         private unsafe IntPtr ConvertArrayToNative(object pManagedHome, int dwFlags)
         {
             Type elementType = pManagedHome.GetType().GetElementType();
@@ -1109,7 +1059,6 @@ namespace  System.StubHelpers {
             return pNativeHome;
         }
 
-        [System.Security.SecurityCritical]
         private static IntPtr ConvertStringToNative(string pManagedHome, int dwFlags)
         {
             IntPtr pNativeHome;
@@ -1137,7 +1086,6 @@ namespace  System.StubHelpers {
             return pNativeHome;
         }
 
-        [System.Security.SecurityCritical]
         private unsafe IntPtr ConvertStringBuilderToNative(StringBuilder pManagedHome, int dwFlags)
         {
             IntPtr pNativeHome;
@@ -1176,7 +1124,7 @@ namespace  System.StubHelpers {
                         ptr, allocSize,
                         IsBestFit(dwFlags),
                         IsThrowOn(dwFlags));
-                    Contract.Assert(length < allocSize, "Expected a length less than the allocated size");
+                    Debug.Assert(length < allocSize, "Expected a length less than the allocated size");
                 }
                 if (IsOut(dwFlags))
                 {
@@ -1211,7 +1159,6 @@ namespace  System.StubHelpers {
             return pNativeHome;
         }
 
-        [System.Security.SecurityCritical]
         private unsafe IntPtr ConvertLayoutToNative(object pManagedHome, int dwFlags)
         {
             // Note that the following call will not throw exception if the type
@@ -1237,7 +1184,6 @@ namespace  System.StubHelpers {
 
         #endregion
 
-        [System.Security.SecurityCritical]
         internal IntPtr ConvertToNative(object pManagedHome, int dwFlags)
         {
             if (pManagedHome == null)
@@ -1283,7 +1229,6 @@ namespace  System.StubHelpers {
             return pNativeHome;
         }
 
-        [System.Security.SecurityCritical]
         internal unsafe void ConvertToManaged(object pManagedHome, IntPtr pNativeHome)
         {
             switch (backPropAction)
@@ -1321,7 +1266,6 @@ namespace  System.StubHelpers {
             }
         }
 
-        [System.Security.SecurityCritical]
         internal void ClearNative(IntPtr pNativeHome)
         {
             if (pNativeHome != IntPtr.Zero)
@@ -1341,7 +1285,6 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class NullableMarshaler
     {    
-        [SecurityCritical]
         static internal IntPtr ConvertToNative<T>(ref Nullable<T> pManaged) where T : struct
         {
             if (pManaged.HasValue)
@@ -1355,14 +1298,12 @@ namespace  System.StubHelpers {
             }
         }
         
-        [SecurityCritical]
         static internal void ConvertToManagedRetVoid<T>(IntPtr pNative, ref Nullable<T> retObj) where T : struct
         {
             retObj = ConvertToManaged<T>(pNative);
         }
 
 
-        [SecurityCritical]
         static internal Nullable<T> ConvertToManaged<T>(IntPtr pNative) where T : struct
         {
             if (pNative != IntPtr.Zero)
@@ -1406,7 +1347,6 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class SystemTypeMarshaler
     {   
-        [SecurityCritical]
         internal static unsafe void ConvertToNative(System.Type managedType, TypeNameNative *pNativeType)
         {
             if (!Environment.IsWinRTSupported)
@@ -1450,7 +1390,6 @@ namespace  System.StubHelpers {
             Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1));
         }
         
-        [SecurityCritical]
         internal static unsafe void ConvertToManaged(TypeNameNative *pNativeType, ref System.Type managedType)
         {
             if (!Environment.IsWinRTSupported)
@@ -1480,10 +1419,9 @@ namespace  System.StubHelpers {
             }
         }
         
-        [SecurityCritical]
         internal static unsafe void ClearNative(TypeNameNative *pNativeType)
         {
-            Contract.Assert(Environment.IsWinRTSupported);
+            Debug.Assert(Environment.IsWinRTSupported);
 
             if (pNativeType->typeName != IntPtr.Zero)
             {
@@ -1509,7 +1447,6 @@ namespace  System.StubHelpers {
             return ex._HResult;
         }
 
-        [SecuritySafeCritical]
         static internal unsafe Exception ConvertToManaged(int hr)
         {
             Contract.Ensures(Contract.Result<Exception>() != null || hr >= 0);
@@ -1527,7 +1464,7 @@ namespace  System.StubHelpers {
 
             // S_OK should be marshaled as null.  WinRT API's should not return S_FALSE by convention.
             // We've chosen to treat S_FALSE as success and return null.
-            Contract.Assert(e != null || hr == 0 || hr == 1, "Unexpected HRESULT - it is a success HRESULT (without the high bit set) other than S_OK & S_FALSE.");
+            Debug.Assert(e != null || hr == 0 || hr == 1, "Unexpected HRESULT - it is a success HRESULT (without the high bit set) other than S_OK & S_FALSE.");
             return e;
         }
     }  // class HResultExceptionMarshaler
@@ -1535,14 +1472,12 @@ namespace  System.StubHelpers {
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     internal static class KeyValuePairMarshaler
     {    
-        [SecurityCritical]
         internal static IntPtr ConvertToNative<K, V>([In] ref KeyValuePair<K, V> pair)
         {
             IKeyValuePair<K, V> impl = new CLRIKeyValuePairImpl<K, V>(ref pair);
             return Marshal.GetComInterfaceForObject(impl, typeof(IKeyValuePair<K, V>));
         }
         
-        [SecurityCritical]
         internal static KeyValuePair<K, V> ConvertToManaged<K, V>(IntPtr pInsp)
         {
             object obj = InterfaceMarshaler.ConvertToManagedWithoutUnboxing(pInsp);
@@ -1552,7 +1487,6 @@ namespace  System.StubHelpers {
         }
 
         // Called from COMInterfaceMarshaler
-        [SecurityCritical]
         internal static object ConvertToManagedBox<K, V>(IntPtr pInsp)
         {
             return (object)ConvertToManaged<K, V>(pInsp);
@@ -1583,48 +1517,9 @@ namespace  System.StubHelpers {
 #endif
     }  // struct NativeVariant
 
-#if !BIT64 && !FEATURE_CORECLR
-    // Structure filled by IL stubs if copy constructor(s) and destructor(s) need to be called
-    // on value types pushed on the stack. The structure is stored in s_copyCtorStubDesc by
-    // SetCopyCtorCookieChain and fetched by CopyCtorCallStubWorker. Must be stack-allocated.
-    [StructLayout(LayoutKind.Sequential)]
-    unsafe internal struct CopyCtorStubCookie
-    {
-        public void SetData(IntPtr srcInstancePtr, uint dstStackOffset, IntPtr ctorPtr, IntPtr dtorPtr)
-        {
-            m_srcInstancePtr = srcInstancePtr;
-            m_dstStackOffset = dstStackOffset;
-            m_ctorPtr = ctorPtr;
-            m_dtorPtr = dtorPtr;
-        }
-
-        public void SetNext(IntPtr pNext)
-        {
-            m_pNext = pNext;
-        }
-
-        public IntPtr m_srcInstancePtr; // pointer to the source instance
-        public uint   m_dstStackOffset; // offset from the start of stack arguments of the pushed 'this' instance
-
-        public IntPtr m_ctorPtr;        // fnptr to the managed copy constructor, result of ldftn
-        public IntPtr m_dtorPtr;        // fnptr to the managed destructor, result of ldftn
-
-        public IntPtr m_pNext;          // pointer to next cookie in the chain or IntPtr.Zero
-    }  // struct CopyCtorStubCookie
-
-    // Aggregates pointer to CopyCtorStubCookie and the target of the interop call.
-    [StructLayout(LayoutKind.Sequential)]
-    unsafe internal struct CopyCtorStubDesc
-    {
-        public IntPtr m_pCookie;
-        public IntPtr m_pTarget;
-    }  // struct CopyCtorStubDes
-#endif // !BIT64 && !FEATURE_CORECLR
-
     // Aggregates SafeHandle and the "owned" bit which indicates whether the SafeHandle
     // has been successfully AddRef'ed. This allows us to do realiable cleanup (Release)
     // if and only if it is needed.
-    [System.Security.SecurityCritical]
     internal sealed class CleanupWorkListElement
     {
         public CleanupWorkListElement(SafeHandle handle)
@@ -1640,7 +1535,6 @@ namespace  System.StubHelpers {
     }  // class CleanupWorkListElement
 
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-    [System.Security.SecurityCritical]
     internal sealed class CleanupWorkList
     {
         private List<CleanupWorkListElement> m_list = new List<CleanupWorkListElement>();
@@ -1662,7 +1556,6 @@ namespace  System.StubHelpers {
         }
     }  // class CleanupWorkList
 
-    [System.Security.SecurityCritical]  // auto-generated
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
     [SuppressUnmanagedCodeSecurityAttribute()]
     internal static class StubHelpers
@@ -1679,33 +1572,8 @@ namespace  System.StubHelpers {
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern IntPtr GetDelegateTarget(Delegate pThis, ref IntPtr pStubArg);
 
-#if !BIT64 && !FEATURE_CORECLR
-        // Written to by a managed stub helper, read by CopyCtorCallStubWorker in VM.
-        [ThreadStatic]
-        static CopyCtorStubDesc s_copyCtorStubDesc;
-
-        static internal void SetCopyCtorCookieChain(IntPtr pStubArg, IntPtr pUnmngThis, int dwStubFlags, IntPtr pCookie)
-        {
-            // we store both the cookie chain head and the target of the copy ctor stub to a thread
-            // static field to be accessed by the copy ctor (see code:CopyCtorCallStubWorker)
-            s_copyCtorStubDesc.m_pCookie = pCookie;
-            s_copyCtorStubDesc.m_pTarget = GetFinalStubTarget(pStubArg, pUnmngThis, dwStubFlags);
-        }
-
-        // Returns the final unmanaged stub target, ignores interceptors.
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        static internal extern IntPtr GetFinalStubTarget(IntPtr pStubArg, IntPtr pUnmngThis, int dwStubFlags);
-#endif // !FEATURE_CORECLR && !BIT64
-
-#if !FEATURE_CORECLR
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        static internal extern void DemandPermission(IntPtr pNMD);
-#endif // !FEATURE_CORECLR
-
-#if FEATURE_CORECLR
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern void ClearLastError();
-#endif
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern void SetLastError();
@@ -1713,7 +1581,6 @@ namespace  System.StubHelpers {
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static internal extern void ThrowInteropParamException(int resID, int paramIdx);
 
-        [System.Security.SecurityCritical]
         static internal IntPtr AddToCleanupList(ref CleanupWorkList pCleanupWorkList, SafeHandle handle)
         {
             if (pCleanupWorkList == null)
@@ -1726,7 +1593,6 @@ namespace  System.StubHelpers {
             return SafeHandleAddRef(handle, ref element.m_owned);
         }
 
-        [System.Security.SecurityCritical]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         static internal void DestroyCleanupList(ref CleanupWorkList pCleanupWorkList)
         {
@@ -1775,7 +1641,6 @@ namespace  System.StubHelpers {
         //-------------------------------------------------------
         
         // AddRefs the SH and returns the underlying unmanaged handle.
-        [System.Security.SecurityCritical]  // auto-generated
         static internal IntPtr SafeHandleAddRef(SafeHandle pHandle, ref bool success)
         {
             if (pHandle == null)
@@ -1790,7 +1655,6 @@ namespace  System.StubHelpers {
         }
 
         // Releases the SH (to be called from finally block).
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         static internal void SafeHandleRelease(SafeHandle pHandle)
         {
@@ -1848,15 +1712,12 @@ namespace  System.StubHelpers {
         static internal extern IntPtr GetDelegateInvokeMethod(Delegate pThis);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecurityCritical]
         static internal extern object GetWinRTFactoryObject(IntPtr pCPCMD);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecurityCritical]
         static internal extern IntPtr GetWinRTFactoryReturnValue(object pThis, IntPtr pCtorEntry);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecurityCritical]
         static internal extern IntPtr GetOuterInspectable(object pThis, IntPtr pCtorMD);
 
 #if MDA_SUPPORTED
index 2f653e4..fc7589f 100644 (file)
@@ -7,6 +7,7 @@ namespace System.Text
     using System;
     using System.Runtime.Serialization;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // ASCIIEncoding
@@ -70,7 +71,6 @@ namespace System.Text
             return EncodingForwarder.GetByteCount(this, chars);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetByteCount(char* chars, int count)
@@ -99,7 +99,6 @@ namespace System.Text
             return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
@@ -115,7 +114,6 @@ namespace System.Text
             return EncodingForwarder.GetCharCount(this, bytes, index, count);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetCharCount(byte* bytes, int count)
@@ -129,7 +127,6 @@ namespace System.Text
             return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
@@ -150,15 +147,14 @@ namespace System.Text
         // GetByteCount
         // Note: We start by assuming that the output will be the same as count.  Having
         // an encoder or fallback may change that assumption
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
-            Contract.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
+            Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
+            Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
+            Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
 
             char charLeftOver = (char)0;
             EncoderReplacementFallback fallback = null;
@@ -172,7 +168,7 @@ namespace System.Text
             if (encoder != null)
             {
                 charLeftOver = encoder.charLeftOver;
-                Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+                Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
                     "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
 
                 fallback = encoder.Fallback as EncoderReplacementFallback;
@@ -191,7 +187,7 @@ namespace System.Text
                 }
 
                 // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
-                Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
                     encoder.FallbackBuffer.Remaining == 0,
                     "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer");
 //                if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
@@ -228,8 +224,8 @@ namespace System.Text
             // We may have a left over character from last time, try and process it.
             if (charLeftOver > 0)
             {
-                Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
-                Contract.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
+                Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
+                Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
 
                 // Since left over char was a surrogate, it'll have to be fallen back.
                 // Get Fallback
@@ -279,24 +275,23 @@ namespace System.Text
                 byteCount++;
             }
 
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer");
 
             return byteCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS encoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
-            Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
-            Contract.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
-            Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
+            Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
+            Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
+            Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
+            Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
+            Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
 
             // Get any left over characters
             char charLeftOver = (char)0;
@@ -328,11 +323,11 @@ namespace System.Text
                     fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
                 }
 
-                Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+                Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
                     "[ASCIIEncoding.GetBytes]leftover character should be high surrogate");
 
                 // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
-                Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
                     encoder.FallbackBuffer.Remaining == 0,
                     "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer");
 //                if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
@@ -411,7 +406,7 @@ namespace System.Text
             if (charLeftOver > 0)
             {
                 // Initialize the buffer
-                Contract.Assert(encoder != null,
+                Debug.Assert(encoder != null,
                     "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over");
                 fallbackBuffer = encoder.FallbackBuffer;
                 fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
@@ -465,7 +460,7 @@ namespace System.Text
                     // didn't use this char, we'll throw or use buffer
                     if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
                     {
-                        Contract.Assert(chars > charStart || bytes == byteStart,
+                        Debug.Assert(chars > charStart || bytes == byteStart,
                             "[ASCIIEncoding.GetBytes]Expected chars to have advanced already.");
                         chars--;                                        // don't use last char
                     }
@@ -494,7 +489,7 @@ namespace System.Text
                 encoder.m_charsUsed = (int)(chars - charStart);
             }
 
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
                 (encoder != null && !encoder.m_throwOnOverflow ),
                 "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end");
 
@@ -502,12 +497,11 @@ namespace System.Text
         }
 
         // This is internal and called by something else,
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
         {
             // Just assert, we're called internally so these should be safe, checked already
-            Contract.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
-            Contract.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
+            Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
+            Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
 
             // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
             DecoderReplacementFallback fallback = null;
@@ -517,7 +511,7 @@ namespace System.Text
             else
             {
                 fallback = decoder.Fallback as DecoderReplacementFallback;
-                Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
                     decoder.FallbackBuffer.Remaining == 0,
                     "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer");
             }
@@ -568,22 +562,21 @@ namespace System.Text
             }
 
             // Fallback buffer must be empty
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer");
 
             // Converted sequence is same length as input
             return charCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS decoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
-            Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
-            Contract.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
-            Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
+            Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
+            Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
+            Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
+            Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
 
             // Do it fast way if using ? replacement fallback
             byte* byteEnd = bytes + byteCount;
@@ -600,7 +593,7 @@ namespace System.Text
             else
             {
                 fallback = decoder.Fallback as DecoderReplacementFallback;
-                Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
                     decoder.FallbackBuffer.Remaining == 0,
                     "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer");
             }
@@ -668,7 +661,7 @@ namespace System.Text
                     if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
                     {
                         // May or may not throw, but we didn't get this byte
-                        Contract.Assert(bytes > byteStart || chars == charStart,
+                        Debug.Assert(bytes > byteStart || chars == charStart,
                             "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)");
                         bytes--;                                            // unused byte
                         fallbackBuffer.InternalReset();                     // Didn't fall this back
@@ -681,7 +674,7 @@ namespace System.Text
                     // Make sure we have buffer space
                     if (chars >= charEnd)
                     {
-                        Contract.Assert(bytes > byteStart || chars == charStart,
+                        Debug.Assert(bytes > byteStart || chars == charStart,
                             "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)");
                         bytes--;                                            // unused byte
                         ThrowCharsOverflow(decoder, chars == charStart);    // throw?
@@ -698,7 +691,7 @@ namespace System.Text
                 decoder.m_bytesUsed = (int)(bytes - byteStart);
 
             // Expect Empty fallback buffer for GetChars
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[ASCIIEncoding.GetChars]Expected Empty fallback buffer");
 
             return (int)(chars - charStart);
index 4c9ca6e..0a42237 100644 (file)
@@ -6,6 +6,7 @@
 namespace System.Text
 {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Globalization;
     using System.Runtime.InteropServices;
@@ -72,7 +73,6 @@ namespace System.Text
         [NonSerialized]
         protected bool m_bUseMlangTypeForSerialization = false;
 
-        [System.Security.SecuritySafeCritical] // static constructors should be safe to call
         static BaseCodePageEncoding()
         {
         }
@@ -136,32 +136,26 @@ namespace System.Text
         }
 
         // Initialize our global stuff
-        [SecurityCritical]
         unsafe static CodePageDataFileHeader* m_pCodePageFileHeader = 
             (CodePageDataFileHeader*)GlobalizationAssembly.GetGlobalizationResourceBytePtr(
                 typeof(CharUnicodeInfo).Assembly, CODE_PAGE_DATA_FILE_NAME);
 
         // Real variables
         [NonSerialized]
-        [SecurityCritical]
         unsafe protected CodePageHeader* pCodePage = null;
 
         // Safe handle wrapper around section map view
-        [System.Security.SecurityCritical] // auto-generated
         [NonSerialized]
         protected SafeViewOfFileHandle safeMemorySectionHandle = null;
 
         // Safe handle wrapper around mapped file handle
-        [System.Security.SecurityCritical] // auto-generated
         [NonSerialized]
         protected SafeFileMappingHandle safeFileMappingHandle = null;
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal BaseCodePageEncoding(int codepage) : this(codepage, codepage)
         {
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal BaseCodePageEncoding(int codepage, int dataCodePage) :
             base(codepage == 0? Microsoft.Win32.Win32Native.GetACP(): codepage)
         {
@@ -171,7 +165,6 @@ namespace System.Text
         }
 
         // Constructor called by serialization.
-        [System.Security.SecurityCritical]  // auto-generated
         internal BaseCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
         {
             // We cannot ever call this, we've proxied ourselved to CodePageEncoding
@@ -179,12 +172,11 @@ namespace System.Text
         }
 
         // ISerializable implementation
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // Make sure to get the base stuff too This throws if info is null
             SerializeEncoding(info, context);
-            Contract.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw");
+            Debug.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw");
 
             // Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding)
             info.AddValue(m_bUseMlangTypeForSerialization ? "m_maxByteSize" : "maxCharSize",
@@ -196,7 +188,6 @@ namespace System.Text
         }
 
         // We need to load tables for our code page
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe void LoadCodePageTables()
         {
             CodePageHeader* pCodePage = FindCodePage(dataTableCodePage);
@@ -217,7 +208,6 @@ namespace System.Text
         }
 
         // Look up the code page pointer
-        [System.Security.SecurityCritical]  // auto-generated
         private static unsafe CodePageHeader* FindCodePage(int codePage)
         {
             // We'll have to loop through all of the m_pCodePageIndex[] items to find our code page, this isn't
@@ -240,7 +230,6 @@ namespace System.Text
         }
 
         // Get our code page byte count
-        [System.Security.SecurityCritical]  // auto-generated
         internal static unsafe int GetCodePageByteSize(int codePage)
         {
             // Get our code page info
@@ -250,18 +239,16 @@ namespace System.Text
             if (pCodePage == null)
                 return 0;
 
-            Contract.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2,
+            Debug.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2,
                 "[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePage->ByteCount + ") in table");
             // Return what it says for byte count
             return pCodePage->ByteCount;
         }
 
         // We have a managed code page entry, so load our tables
-        [System.Security.SecurityCritical]
         protected abstract unsafe void LoadManagedCodePage();
 
         // Allocate memory to load our code page
-        [System.Security.SecurityCritical]  // auto-generated
         protected unsafe byte* GetSharedMemory(int iSize)
         {
             // Build our name
@@ -271,7 +258,7 @@ namespace System.Text
 
             // This gets shared memory for our map.  If its can't, it gives us clean memory.
             Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle);
-            Contract.Assert(pMemorySection != null,
+            Debug.Assert(pMemorySection != null,
                 "[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened");
 
             // If that failed, we have to die.
@@ -291,7 +278,6 @@ namespace System.Text
             return pMemorySection;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         protected unsafe virtual String GetMemorySectionName()
         {
             int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
@@ -303,29 +289,26 @@ namespace System.Text
             return strName;
         }
 
-        [System.Security.SecurityCritical]
         protected abstract unsafe void ReadBestFitTable();
 
-        [System.Security.SecuritySafeCritical]  
         internal override char[] GetBestFitUnicodeToBytesData()
         {
             // Read in our best fit table if necessary
             if (arrayUnicodeBestFit == null) ReadBestFitTable();
 
-            Contract.Assert(arrayUnicodeBestFit != null,
+            Debug.Assert(arrayUnicodeBestFit != null,
                 "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
 
             // Normally we don't have any best fit data.
             return arrayUnicodeBestFit;
         }
 
-        [System.Security.SecuritySafeCritical] 
         internal override char[] GetBestFitBytesToUnicodeData()
         {
             // Read in our best fit table if necessary
             if (arrayBytesBestFit == null) ReadBestFitTable();
 
-            Contract.Assert(arrayBytesBestFit != null,
+            Debug.Assert(arrayBytesBestFit != null,
                 "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
 
             // Normally we don't have any best fit data.
@@ -336,7 +319,6 @@ namespace System.Text
         // is invalid. so we detect that by validating the memory section handle then re-initialize the memory 
         // section by calling LoadManagedCodePage() method and eventually the mapped file handle and
         // the memory section pointer will get finalized one more time.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe void CheckMemorySection()
         {
             if (safeMemorySectionHandle != null && safeMemorySectionHandle.DangerousGetHandle() == IntPtr.Zero)
index 5ab73fc..7805c65 100644 (file)
@@ -11,6 +11,7 @@ namespace System.Text
     using System;
     using System.Runtime.Serialization;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     /*=================================CodePageEncoding==================================
@@ -74,7 +75,6 @@ namespace System.Text
         }
 
         // Just get it from GetEncoding
-        [System.Security.SecurityCritical]  // auto-generated
         public Object GetRealObject(StreamingContext context)
         {
             // Get our encoding (Note: This has default fallbacks for readonly and everett cases)
@@ -93,11 +93,10 @@ namespace System.Text
         }
 
         // ISerializable implementation
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // We cannot ever call this.
-            Contract.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData");
+            Debug.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData");
             throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
         }
 
@@ -120,18 +119,16 @@ namespace System.Text
             }
 
             // Just get it from GetDecider
-            [System.Security.SecurityCritical]  // auto-generated
             public Object GetRealObject(StreamingContext context)
             {
                 return this.realEncoding.GetDecoder();
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // We cannot ever call this.
-                Contract.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData");
+                Debug.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData");
                 throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
             }
         }
index 1503ef7..28b85d5 100644 (file)
@@ -6,6 +6,7 @@
 namespace System.Text
 {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Text;
     using System.Threading;
@@ -20,13 +21,10 @@ namespace System.Text
     {
         // Pointers to our memory section parts
         [NonSerialized]
-        [SecurityCritical]
         protected unsafe char*   mapBytesToUnicode = null;      // char 65536
         [NonSerialized]
-        [SecurityCritical]
         protected unsafe ushort* mapUnicodeToBytes = null;      // byte 65536
         [NonSerialized]
-        [SecurityCritical]
         protected unsafe int*    mapCodePageCached = null;      // to remember which CP is cached
 
         [NonSerialized]
@@ -45,23 +43,20 @@ namespace System.Text
         [NonSerialized]
         protected char    charUnknown = (char)0;
 
-        [System.Security.SecurityCritical]  // auto-generated
         public DBCSCodePageEncoding(int codePage) : this(codePage, codePage)
         {
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
         {
         }
 
         // Constructor called by serialization.
         // Note:  We use the base GetObjectData however
-        [System.Security.SecurityCritical]  // auto-generated
         internal DBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
         {
             // Actually this can't ever get called, CodePageEncoding is our proxy
-            Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
+            Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
             throw new ArgumentNullException("this");
         }
 
@@ -93,11 +88,10 @@ namespace System.Text
         //               corrospond to those unicode code points.
         // We have a managed code page entry, so load our tables
         //
-        [System.Security.SecurityCritical]  // auto-generated
         protected override unsafe void LoadManagedCodePage()
         {
             // Should be loading OUR code page
-            Contract.Assert(pCodePage->CodePage == this.dataTableCodePage,
+            Debug.Assert(pCodePage->CodePage == this.dataTableCodePage,
                 "[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
 
             // Make sure we're really a 1 byte code page
@@ -120,7 +114,7 @@ namespace System.Text
                 byteCountUnknown++;
 
             // We use fallback encoder, which uses ?, which so far all of our tables do as well
-            Contract.Assert(bytesUnknown == 0x3f,
+            Debug.Assert(bytesUnknown == 0x3f,
                 "[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character");
 
             // Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars)
@@ -134,7 +128,7 @@ namespace System.Text
             // If its cached (& filled in) we don't have to do anything else
             if (*mapCodePageCached != 0)
             {
-                Contract.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) ||
+                Debug.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) ||
                     (*mapCodePageCached == this.CodePage && !this.bFlagDataTable)),
                     "[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page flag to be set to data table or regular code page.");
 
@@ -188,7 +182,7 @@ namespace System.Text
                 else if (input == LEAD_BYTE_CHAR) // 0xfffe
                 {
                     // Lead byte mark
-                    Contract.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
+                    Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
                     useBytes = bytePosition;
                     // input stays 0xFFFE
                 }
@@ -235,7 +229,6 @@ namespace System.Text
         }
 
         // Any special processing for this code page
-        [System.Security.SecurityCritical]  // auto-generated
         protected virtual unsafe void CleanUpEndBytes(char* chars)
         {
         }
@@ -256,7 +249,6 @@ namespace System.Text
         }
 
         // Read in our best fit table
-        [System.Security.SecurityCritical]  // auto-generated
         protected unsafe override void ReadBestFitTable()
         {
             // Lock so we don't confuse ourselves.
@@ -407,7 +399,7 @@ namespace System.Text
                     // If they're out of order we need to sort them.
                     if (bOutOfOrder)
                     {
-                        Contract.Assert((arrayTemp.Length / 2) < 20,
+                        Debug.Assert((arrayTemp.Length / 2) < 20,
                             "[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2);
 
                         for (int i = 0; i < arrayTemp.Length - 2; i+=2)
@@ -515,7 +507,7 @@ namespace System.Text
                                     // We can't do this assert for CP 51932 & 50220 because they aren't 
                                     // calling CleanUpBytes() for best fit.  All the string stuff here
                                     // also makes this assert slow.
-    //                                Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format(
+    //                                Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format(
     //                                    "[DBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}",
     //                                    (int)mapBytesToUnicode[input], (int)input, CodePage));
                                 }
@@ -534,15 +526,14 @@ namespace System.Text
         // GetByteCount
         // Note: We start by assuming that the output will be the same as count.  Having
         // an encoder or fallback may change that assumption
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative");
-            Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null");
+            Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative");
+            Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
+            Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
 
             CheckMemorySection();
 
@@ -568,8 +559,8 @@ namespace System.Text
             // We may have a left over character from last time, try and process it.
             if (charLeftOver > 0)
             {
-                Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
-                Contract.Assert(encoder != null,
+                Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
+                Debug.Assert(encoder != null,
                     "[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
 
                 // Since left over char was a surrogate, it'll have to be fallen back.
@@ -625,18 +616,17 @@ namespace System.Text
             return (int)byteCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS encoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null");
-            Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative");
-            Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null");
-            Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative");
+            Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null");
+            Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative");
+            Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null");
+            Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
+            Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
 
             CheckMemorySection();
 
@@ -654,7 +644,7 @@ namespace System.Text
             if (encoder != null)
             {
                 charLeftOver = encoder.charLeftOver;
-                Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+                Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
                     "[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
 
                 // Go ahead and get the fallback buffer (need leftover fallback if converting)
@@ -669,7 +659,7 @@ namespace System.Text
                 // We may have a left over character from last time, try and process it.
                 if (charLeftOver > 0)
                 {
-                    Contract.Assert(encoder != null,
+                    Debug.Assert(encoder != null,
                         "[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
 
                     // Since left over char was a surrogate, it'll have to be fallen back.
@@ -702,7 +692,7 @@ namespace System.Text
                     if (fallbackBuffer == null)
                     {
                         // Initialize the buffer
-                        Contract.Assert(encoder == null,
+                        Debug.Assert(encoder == null,
                             "[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder.");
                         fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
                         fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
@@ -724,7 +714,7 @@ namespace System.Text
                         // didn't use this char, we'll throw or use buffer
                         if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
                         {
-                            Contract.Assert(chars > charStart,
+                            Debug.Assert(chars > charStart,
                                 "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)");
                             chars--;                                        // don't use last char
                         }
@@ -743,7 +733,7 @@ namespace System.Text
                     // didn't use this char, we'll throw or use buffer
                     if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
                     {
-                        Contract.Assert(chars > charStart,
+                        Debug.Assert(chars > charStart,
                             "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)");
                         chars--;                                        // don't use last char
                     }
@@ -771,7 +761,7 @@ namespace System.Text
 
             // If we're not converting we must not have a fallback buffer
             // (We don't really have a way to clear none-encoder using fallbacks however)
-//            Contract.Assert((encoder == null || encoder.m_throwOnOverflow) &&
+//            Debug.Assert((encoder == null || encoder.m_throwOnOverflow) &&
 //                (fallbackBuffer == null || fallbackBuffer.Remaining == 0),
 //                "[DBCSEncoding.GetBytes]Expected empty fallback buffer at end if not converting");
 
@@ -779,12 +769,11 @@ namespace System.Text
         }
 
         // This is internal and called by something else,
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
         {
             // Just assert, we're called internally so these should be safe, checked already
-            Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
-            Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
+            Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
+            Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
 
             CheckMemorySection();
 
@@ -800,7 +789,7 @@ namespace System.Text
 
             // Shouldn't have anything in fallback buffer for GetCharCount
             // (don't have to check m_throwOnOverflow for count)
-            Contract.Assert(decoder == null ||
+            Debug.Assert(decoder == null ||
                 !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
                 "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start");
 
@@ -818,7 +807,7 @@ namespace System.Text
                     }
 
 
-                    Contract.Assert(fallbackBuffer == null,
+                    Debug.Assert(fallbackBuffer == null,
                         "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer");
                     fallbackBuffer = decoder.FallbackBuffer;
                     fallbackBuffer.InternalInitialize(bytes, null);
@@ -842,7 +831,7 @@ namespace System.Text
                     charCount--;
 
                     // We'll need a fallback
-                    Contract.Assert(fallbackBuffer == null,
+                    Debug.Assert(fallbackBuffer == null,
                         "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair");
                     fallbackBuffer = decoder.FallbackBuffer;
                     fallbackBuffer.InternalInitialize(byteEnd - count, null);
@@ -917,7 +906,7 @@ namespace System.Text
             }
 
             // Shouldn't have anything in fallback buffer for GetChars
-            Contract.Assert(decoder == null || !decoder.m_throwOnOverflow ||
+            Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
                 !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
                 "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end");
 
@@ -925,15 +914,14 @@ namespace System.Text
             return charCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS baseDecoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null");
-            Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative");
-            Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null");
-            Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative");
+            Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null");
+            Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative");
+            Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null");
+            Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative");
 
             CheckMemorySection();
 
@@ -951,7 +939,7 @@ namespace System.Text
             DecoderFallbackBuffer fallbackBuffer = null;
 
             // Shouldn't have anything in fallback buffer for GetChars
-            Contract.Assert(decoder == null || !decoder.m_throwOnOverflow ||
+            Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
                 !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
                 "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
 
@@ -970,7 +958,7 @@ namespace System.Text
 
                     // Well, we're flushing, so use '?' or fallback
                     // fallback leftover byte
-                    Contract.Assert(fallbackBuffer == null,
+                    Debug.Assert(fallbackBuffer == null,
                         "[DBCSCodePageEncoding.GetChars]Expected empty fallback");
                     fallbackBuffer = decoder.FallbackBuffer;
                     fallbackBuffer.InternalInitialize(bytes, charEnd);
@@ -995,7 +983,7 @@ namespace System.Text
                 char cDecoder = mapBytesToUnicode[iBytes];
                 if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0)
                 {
-                    Contract.Assert(fallbackBuffer == null,
+                    Debug.Assert(fallbackBuffer == null,
                         "[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes");
                     fallbackBuffer = decoder.FallbackBuffer;
                     fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
@@ -1073,7 +1061,7 @@ namespace System.Text
                     if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
                     {
                         // May or may not throw, but we didn't get these byte(s)
-                        Contract.Assert(bytes >= byteStart + byteBuffer.Length, 
+                        Debug.Assert(bytes >= byteStart + byteBuffer.Length, 
                             "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback");
                         bytes-=byteBuffer.Length;                           // didn't use these byte(s)
                         fallbackBuffer.InternalReset();                     // Didn't fall this back
@@ -1087,12 +1075,12 @@ namespace System.Text
                     if (chars >= charEnd)
                     {
                         // May or may not throw, but we didn't get these byte(s)
-                        Contract.Assert(bytes > byteStart, 
+                        Debug.Assert(bytes > byteStart, 
                             "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte");
                         bytes--;                                            // unused byte
                         if (iBytes >= 0x100)
                         {
-                            Contract.Assert(bytes > byteStart, 
+                            Debug.Assert(bytes > byteStart, 
                                 "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte");
                             bytes--;                                        // 2nd unused byte
                         }
@@ -1118,7 +1106,7 @@ namespace System.Text
             }
 
             // Shouldn't have anything in fallback buffer for GetChars
-            Contract.Assert(decoder == null || !decoder.m_throwOnOverflow ||
+            Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
                 !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
                 "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end");
 
index 6c1b7e2..0ebbacd 100644 (file)
@@ -7,6 +7,7 @@ namespace System.Text
     using System.Runtime.Serialization;
     using System.Text;
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     // A Decoder is used to decode a sequence of blocks of bytes into a
     // sequence of blocks of characters. Following instantiation of a decoder,
@@ -124,7 +125,6 @@ namespace System.Text
 
         // We expect this to be the workhorse for NLS Encodings, but for existing
         // ones we need a working (if slow) default implimentation)
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush)
@@ -189,7 +189,6 @@ namespace System.Text
         // the char[] to our char* output buffer.  If the result count was wrong, we
         // could easily overflow our output buffer.  Therefore we do an extra test
         // when we copy the buffer so that we don't overflow charCount either.
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe int GetChars(byte* bytes, int byteCount,
@@ -218,7 +217,7 @@ namespace System.Text
             // Do the work
             int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush);
 
-            Contract.Assert(result <= charCount, "Returned more chars than we have space for");
+            Debug.Assert(result <= charCount, "Returned more chars than we have space for");
 
             // Copy the char array
             // WARNING: We MUST make sure that we don't copy too many chars.  We can't
@@ -306,7 +305,6 @@ namespace System.Text
         // Note that if all of the input bytes are not consumed, then we'll do a /2, which means
         // that its likely that we didn't consume as many bytes as we could have.  For some
         // applications this could be slow.  (Like trying to exactly fill an output buffer from a bigger stream)
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe void Convert(byte* bytes, int byteCount,
index 5c1dcd9..6389b4b 100644 (file)
@@ -10,6 +10,7 @@ namespace System.Text
     using System;
     using System.Text;
     using System.Threading;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -101,7 +102,7 @@ namespace System.Text
         public override bool Fallback(byte[] bytesUnknown, int index)
         {
             // We expect no previous fallback in our buffer
-            Contract.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
+            Debug.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
 
             cBestFit = TryBestFit(bytesUnknown);
             if (cBestFit == '\0')
@@ -155,7 +156,6 @@ namespace System.Text
         }
 
         // Clear the buffer
-        [System.Security.SecuritySafeCritical] // overrides public transparent member
         public override unsafe void Reset()
         {
             iCount = -1;
@@ -163,7 +163,6 @@ namespace System.Text
         }
 
         // This version just counts the fallback and doesn't actually copy anything.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
         // Right now this has both bytes and bytes[], since we might have extra bytes, hence the
         // array, and we might need the index, hence the byte*
@@ -212,7 +211,7 @@ namespace System.Text
                 if (cTest == cCheck)
                 {
                     // We found it
-                    Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+                    Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
                         "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
                     return oFallback.arrayBestFit[index + 1];
                 }
@@ -233,7 +232,7 @@ namespace System.Text
                 if (oFallback.arrayBestFit[index] == cCheck)
                 {
                     // We found it
-                    Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+                    Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
                         "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
                     return oFallback.arrayBestFit[index + 1];
                 }
index 24f33b9..42483a7 100644 (file)
@@ -7,6 +7,7 @@ using System;
 using System.Security;
 using System.Threading;
 using System.Globalization;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Text
@@ -115,13 +116,10 @@ namespace System.Text
 
         // Internal items to help us figure out what we're doing as far as error messages, etc.
         // These help us with our performance and messages internally
-        [SecurityCritical]
         internal     unsafe byte*    byteStart;
-        [SecurityCritical]
         internal     unsafe char*    charEnd;
 
         // Internal Reset
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe void InternalReset()
         {
             byteStart = null;
@@ -130,7 +128,6 @@ namespace System.Text
 
         // Set the above values
         // This can't be part of the constructor because DecoderFallbacks would have to know how to impliment these.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe void InternalInitialize(byte* byteStart, char* charEnd)
         {
             this.byteStart = byteStart;
@@ -145,7 +142,6 @@ namespace System.Text
         // Right now this has both bytes and bytes[], since we might have extra bytes, hence the
         // array, and we might need the index, hence the byte*
         // Don't touch ref chars unless we succeed
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars)
         {
             // Copy bytes to array (slow, but right now that's what we get to do.
@@ -153,7 +149,7 @@ namespace System.Text
 //            for (int i = 0; i < count; i++)
 //                bytesUnknown[i] = *(bytes++);
 
-            Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
+            Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
 
             // See if there's a fallback character and we have an output buffer then copy our string.
             if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
@@ -204,7 +200,6 @@ namespace System.Text
         }
 
         // This version just counts the fallback and doesn't actually copy anything.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes)
         // Right now this has both bytes and bytes[], since we might have extra bytes, hence the
         // array, and we might need the index, hence the byte*
@@ -214,7 +209,7 @@ namespace System.Text
 //            for (int i = 0; i < count; i++)
   //              bytesUnknown[i] = *(bytes++);
 
-            Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
+            Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
 
             // See if there's a fallback character and we have an output buffer then copy our string.
             if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
index 56c95de..e44c43a 100644 (file)
@@ -42,7 +42,6 @@ namespace System.Text
         }
 
         // ISerializable implementation. called during serialization.
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             SerializeDecoder(info);
@@ -77,7 +76,6 @@ namespace System.Text
             return GetCharCount(bytes, index, count, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
         {
             // Validate Parameters
@@ -104,7 +102,6 @@ namespace System.Text
                 return GetCharCount(pBytes + index, count, flush);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
         {
             // Validate parameters
@@ -131,7 +128,6 @@ namespace System.Text
             return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
                                              char[] chars, int charIndex, bool flush)
         {
@@ -170,7 +166,6 @@ namespace System.Text
                                     pChars + charIndex, charCount, flush);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe override int GetChars(byte* bytes, int byteCount,
                                               char* chars, int charCount, bool flush)
         {
@@ -194,7 +189,6 @@ namespace System.Text
 
         // This method is used when the output buffer might not be big enough.
         // Just call the pointer version.  (This gets chars)
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
                                               char[] chars, int charIndex, int charCount, bool flush,
                                               out int bytesUsed, out int charsUsed, out bool completed)
@@ -241,7 +235,6 @@ namespace System.Text
 
         // This is the version that used pointers.  We call the base encoding worker function
         // after setting our appropriate internal variables.  This is getting chars
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe override void Convert(byte* bytes, int byteCount,
                                               char* chars, int charCount, bool flush,
                                               out int bytesUsed, out int charsUsed, out bool completed)
index 44a34c1..77c8560 100644 (file)
@@ -5,6 +5,7 @@
 namespace System.Text
 {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -156,7 +157,7 @@ namespace System.Text
             }
 
             // Now make sure its in the expected range
-            Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
+            Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
                             "Index exceeds buffer range");
 
             return strDefault[fallbackIndex];            
@@ -187,7 +188,6 @@ namespace System.Text
         }
 
         // Clear the buffer
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override unsafe void Reset()
         {
             fallbackCount = -1;
@@ -196,7 +196,6 @@ namespace System.Text
         }
 
         // This version just counts the fallback and doesn't actually copy anything.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
         // Right now this has both bytes and bytes[], since we might have extra bytes, hence the
         // array, and we might need the index, hence the byte*
index 7c90cae..44345b2 100644 (file)
@@ -50,13 +50,11 @@ namespace System.Text
     internal class EUCJPEncoding : DBCSCodePageEncoding
     {
         // This pretends to be CP 932 as far as memory tables are concerned.
-        [System.Security.SecurityCritical]  // auto-generated
         public EUCJPEncoding() : base(51932, 932)
         {
             this.m_bUseMlangTypeForSerialization = true;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         protected unsafe override String GetMemorySectionName()
         {
             int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
@@ -165,7 +163,6 @@ namespace System.Text
             return true;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         protected override unsafe void CleanUpEndBytes(char* chars)
         {
             // Need to special case CP 51932
index e965c3a..b9d4581 100644 (file)
@@ -7,6 +7,7 @@ namespace System.Text
     using System.Runtime.Serialization;
     using System.Text;
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     // An Encoder is used to encode a sequence of blocks of characters into
     // a sequence of blocks of bytes. Following instantiation of an encoder,
@@ -120,7 +121,6 @@ namespace System.Text
         // We expect this to be the workhorse for NLS encodings
         // unfortunately for existing overrides, it has to call the [] version,
         // which is really slow, so avoid this method if you might be calling external encodings.
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
@@ -182,7 +182,6 @@ namespace System.Text
         // the byte[] to our byte* output buffer.  If the result count was wrong, we
         // could easily overflow our output buffer.  Therefore we do an extra test
         // when we copy the buffer so that we don't overflow byteCount either.
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe int GetBytes(char* chars, int charCount,
@@ -211,7 +210,7 @@ namespace System.Text
             // Do the work
             int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
 
-            Contract.Assert(result <= byteCount, "Returned more bytes than we have space for");
+            Debug.Assert(result <= byteCount, "Returned more bytes than we have space for");
 
             // Copy the byte array
             // WARNING: We MUST make sure that we don't copy too many bytes.  We can't
@@ -299,7 +298,6 @@ namespace System.Text
         // Note that if all of the input chars are not consumed, then we'll do a /2, which means
         // that its likely that we didn't consume as many chars as we could have.  For some
         // applications this could be slow.  (Like trying to exactly fill an output buffer from a bigger stream)
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe void Convert(char* chars, int charCount,
index 92eff37..c5f82a2 100644 (file)
@@ -11,6 +11,7 @@ namespace System.Text
     using System.Globalization;
     using System.Text;
     using System.Threading;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -103,7 +104,7 @@ namespace System.Text
             // If we had a buffer already we're being recursive, throw, it's probably at the suspect
             // character in our array.
             // Shouldn't be able to get here for all of our code pages, table would have to be messed up.
-            Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
+            Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
 
             iCount = iSize = 1;
             cBestFit = TryBestFit(charUnknown);
@@ -130,7 +131,7 @@ namespace System.Text
             // If we had a buffer already we're being recursive, throw, it's probably at the suspect
             // character in our array.  0 is processing last character, < 0 is not falling back
             // Shouldn't be able to get here, table would have to be messed up.
-            Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
+            Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
 
             // Go ahead and get our fallback, surrogates don't have best fit
             cBestFit = '?';
@@ -183,7 +184,6 @@ namespace System.Text
         }
 
         // Clear the buffer
-        [System.Security.SecuritySafeCritical] // overrides public transparent member
         public override unsafe void Reset()
         {
             iCount = -1;
@@ -212,7 +212,7 @@ namespace System.Text
                 if (cTest == cUnknown)
                 {
                     // We found it
-                    Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+                    Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
                         "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
                     return oFallback.arrayBestFit[index + 1];
                 }
@@ -233,7 +233,7 @@ namespace System.Text
                 if (oFallback.arrayBestFit[index] == cUnknown)
                 {
                     // We found it
-                    Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+                    Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
                         "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
                     return oFallback.arrayBestFit[index + 1];
                 }
index 4b17041..db2bf93 100644 (file)
@@ -5,6 +5,7 @@
 using System;
 using System.Security;
 using System.Threading;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Text
@@ -111,9 +112,7 @@ namespace System.Text
 
         // Internal items to help us figure out what we're doing as far as error messages, etc.
         // These help us with our performance and messages internally
-        [SecurityCritical]
         internal    unsafe char*   charStart;
-        [SecurityCritical]
         internal    unsafe char*   charEnd;
         internal    EncoderNLS     encoder;
         internal    bool           setEncoder;
@@ -124,7 +123,6 @@ namespace System.Text
 
         // Internal Reset
         // For example, what if someone fails a conversion and wants to reset one of our fallback buffers?
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe void InternalReset()
         {
             charStart = null;
@@ -135,7 +133,6 @@ namespace System.Text
 
         // Set the above values
         // This can't be part of the constructor because EncoderFallbacks would have to know how to impliment these.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder)
         {
             this.charStart = charStart;
@@ -163,11 +160,10 @@ namespace System.Text
         // Note that this could also change the contents of this.encoder, which is the same
         // object that the caller is using, so the caller could mess up the encoder for us
         // if they aren't careful.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe virtual bool InternalFallback(char ch, ref char* chars)
         {
             // Shouldn't have null charStart
-            Contract.Assert(charStart != null,
+            Debug.Assert(charStart != null,
                 "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized");
 
             // Get our index, remember chars was preincremented to point at next char, so have to -1
index eef9c46..2add017 100644 (file)
@@ -45,7 +45,6 @@ namespace System.Text
         }
 
         // ISerializable implementation. called during serialization.
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             SerializeEncoder(info);
@@ -77,7 +76,6 @@ namespace System.Text
                 m_fallbackBuffer.Reset();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush)
         {
             // Validate input parameters
@@ -107,7 +105,6 @@ namespace System.Text
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe override int GetByteCount(char* chars, int count, bool flush)
         {
             // Validate input parameters
@@ -125,7 +122,6 @@ namespace System.Text
             return m_encoding.GetByteCount(chars, count, this);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
                                               byte[] bytes, int byteIndex, bool flush)
         {
@@ -163,7 +159,6 @@ namespace System.Text
                                     pBytes + byteIndex, byteCount, flush);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
         {
             // Validate parameters
@@ -183,7 +178,6 @@ namespace System.Text
 
         // This method is used when your output buffer might not be large enough for the entire result.
         // Just call the pointer version.  (This gets bytes)
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override unsafe void Convert(char[] chars, int charIndex, int charCount,
                                               byte[] bytes, int byteIndex, int byteCount, bool flush,
                                               out int charsUsed, out int bytesUsed, out bool completed)
@@ -230,7 +224,6 @@ namespace System.Text
 
         // This is the version that uses pointers.  We call the base encoding worker function
         // after setting our appropriate internal variables.  This is getting bytes
-        [System.Security.SecurityCritical]  // auto-generated
         public override unsafe void Convert(char* chars, int charCount,
                                               byte* bytes, int byteCount, bool flush,
                                               out int charsUsed, out int bytesUsed, out bool completed)
index c9e0c6c..604cddf 100644 (file)
@@ -6,6 +6,7 @@ namespace System.Text
 {
     using System;
     using System.Runtime;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -189,7 +190,7 @@ namespace System.Text
             }
 
             // Now make sure its in the expected range
-            Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
+            Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
                             "Index exceeds buffer range");
 
             return strDefault[fallbackIndex];
@@ -220,7 +221,6 @@ namespace System.Text
         }
 
         // Clear the buffer
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override unsafe void Reset()
         {
             fallbackCount = -1;
index 160370b..b2284d7 100644 (file)
@@ -15,6 +15,7 @@ namespace System.Text
     using System.Security.Permissions;
     using System.Threading;
     using System.Text;
+    using System.Diagnostics;
     using System.Diagnostics.CodeAnalysis;
     using System.Diagnostics.Contracts;
     using Win32Native = Microsoft.Win32.Win32Native;
@@ -389,9 +390,6 @@ namespace System.Text
         private static volatile Hashtable encodings;
 #endif
 
-#if !FEATURE_CORECLR
-        [System.Security.SecurityCritical]
-#endif
         public static void RegisterProvider(EncodingProvider provider) 
         {
             // Parameters validated inside EncodingProvider
@@ -399,9 +397,6 @@ namespace System.Text
         }
 
         [Pure]
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#endif
         public static Encoding GetEncoding(int codepage)
         {
             Encoding result = EncodingProvider.GetEncodingFromProvider(codepage);
@@ -478,7 +473,7 @@ namespace System.Text
                         result = GetEncodingCodePage(codepage) ?? GetEncodingRare(codepage);
                     }
 
-                    Contract.Assert(result != null, "result != null");
+                    Debug.Assert(result != null, "result != null");
 
                     encodings.Add(key, result);
                 }
@@ -516,10 +511,9 @@ namespace System.Text
             return fallbackEncoding;
         }
 #if FEATURE_CODEPAGES_FILE
-        [System.Security.SecurityCritical]  // auto-generated
         private static Encoding GetEncodingRare(int codepage)
         {
-            Contract.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001,
+            Debug.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001,
                 "[Encoding.GetEncodingRare]This code page (" + codepage + ") isn't supported by GetEncodingRare!");
             Encoding result;
             switch (codepage)
@@ -585,7 +579,6 @@ namespace System.Text
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static Encoding GetEncodingCodePage(int CodePage)
         {
             // Single Byte or Double Byte Code Page? (0 if not found)
@@ -896,7 +889,6 @@ namespace System.Text
         // which is really slow, so this method should be avoided if you're calling
         // a 3rd party encoding.
         [Pure]
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe int GetByteCount(char* chars, int count)
@@ -922,7 +914,6 @@ namespace System.Text
 
         // For NLS Encodings, workhorse takes an encoder (may be null)
         // Always validate parameters before calling internal version, which will only assert.
-        [System.Security.SecurityCritical]  // auto-generated
         internal virtual unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
         {
             Contract.Requires(chars != null);
@@ -983,7 +974,7 @@ namespace System.Text
             int byteCount = GetByteCount(s);
             byte[] bytes = new byte[byteCount];
             int bytesReceived = GetBytes(s, 0, s.Length, bytes, 0);
-            Contract.Assert(byteCount == bytesReceived);
+            Debug.Assert(byteCount == bytesReceived);
             return bytes;
         }
 
@@ -998,7 +989,6 @@ namespace System.Text
 
         // This is our internal workhorse
         // Always validate parameters before calling internal version, which will only assert.
-        [System.Security.SecurityCritical]  // auto-generated
         internal virtual unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS encoder)
         {
@@ -1022,7 +1012,6 @@ namespace System.Text
         // could easily overflow our output buffer.  Therefore we do an extra test
         // when we copy the buffer so that we don't overflow byteCount either.
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe int GetBytes(char* chars, int charCount,
@@ -1051,7 +1040,7 @@ namespace System.Text
             // Do the work
             int result = GetBytes(arrChar, 0, charCount, arrByte, 0);
 
-            Contract.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for");
+            Debug.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for");
 
             // Copy the byte array
             // WARNING: We MUST make sure that we don't copy too many bytes.  We can't
@@ -1092,7 +1081,6 @@ namespace System.Text
         // We expect this to be the workhorse for NLS Encodings, but for existing
         // ones we need a working (if slow) default implimentation)
         [Pure]
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe int GetCharCount(byte* bytes, int count)
@@ -1118,7 +1106,6 @@ namespace System.Text
 
         // This is our internal workhorse
         // Always validate parameters before calling internal version, which will only assert.
-        [System.Security.SecurityCritical]  // auto-generated
         internal virtual unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
         {
             return GetCharCount(bytes, count);
@@ -1181,7 +1168,6 @@ namespace System.Text
         // could easily overflow our output buffer.  Therefore we do an extra test
         // when we copy the buffer so that we don't overflow charCount either.
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public virtual unsafe int GetChars(byte* bytes, int byteCount,
@@ -1210,7 +1196,7 @@ namespace System.Text
             // Do the work
             int result = GetChars(arrByte, 0, byteCount, arrChar, 0);
 
-            Contract.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for");
+            Debug.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for");
 
             // Copy the char array
             // WARNING: We MUST make sure that we don't copy too many chars.  We can't
@@ -1230,7 +1216,6 @@ namespace System.Text
 
         // This is our internal workhorse
         // Always validate parameters before calling internal version, which will only assert.
-        [System.Security.SecurityCritical]  // auto-generated
         internal virtual unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS decoder)
         {
@@ -1238,7 +1223,6 @@ namespace System.Text
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public unsafe string GetString(byte* bytes, int byteCount)
@@ -1306,7 +1290,6 @@ namespace System.Text
             return new DefaultDecoder(this);
         }
 
-        [System.Security.SecuritySafeCritical]
         private static Encoding CreateDefaultEncoding()
         {
             // defaultEncoding should be null if we get here, but we can't
@@ -1482,7 +1465,6 @@ namespace System.Text
                 EncodingName, EncoderFallback.GetType()), "bytes");
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void ThrowBytesOverflow(EncoderNLS encoder, bool nothingEncoded)
         {
             if (encoder == null || encoder.m_throwOnOverflow || nothingEncoded)
@@ -1507,7 +1489,6 @@ namespace System.Text
                 EncodingName, DecoderFallback.GetType()), "chars");
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void ThrowCharsOverflow(DecoderNLS decoder, bool nothingDecoded)
         {
             if (decoder == null || decoder.m_throwOnOverflow || nothingDecoded)
@@ -1558,7 +1539,6 @@ namespace System.Text
             }
 
             // Just get it from GetEncoding
-            [System.Security.SecurityCritical]  // auto-generated
             public Object GetRealObject(StreamingContext context)
             {
                 // upon deserialization since the DefaultEncoder implement IObjectReference the 
@@ -1584,7 +1564,6 @@ namespace System.Text
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // Any info?
@@ -1608,7 +1587,6 @@ namespace System.Text
                 return m_encoding.GetByteCount(chars, index, count);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
             public unsafe override int GetByteCount(char* chars, int count, bool flush)
             {
@@ -1641,7 +1619,6 @@ namespace System.Text
                 return m_encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
             public unsafe override int GetBytes(char* chars, int charCount,
                                                  byte* bytes, int byteCount, bool flush)
@@ -1684,7 +1661,6 @@ namespace System.Text
             }
 
             // Just get it from GetEncoding
-            [System.Security.SecurityCritical]  // auto-generated
             public Object GetRealObject(StreamingContext context)
             {
                 // upon deserialization since the DefaultEncoder implement IObjectReference the 
@@ -1705,7 +1681,6 @@ namespace System.Text
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // Any info?
@@ -1733,7 +1708,6 @@ namespace System.Text
                 return m_encoding.GetCharCount(bytes, index, count);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
             public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
             {
@@ -1770,7 +1744,6 @@ namespace System.Text
                 return m_encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
             public unsafe override int GetChars(byte* bytes, int byteCount,
                                                   char* chars, int charCount, bool flush)
@@ -1782,24 +1755,17 @@ namespace System.Text
 
         internal class EncodingCharBuffer
         {
-            [SecurityCritical]
             unsafe char* chars;
-            [SecurityCritical]
             unsafe char* charStart;
-            [SecurityCritical]
             unsafe char* charEnd;
             int          charCountResult = 0;
             Encoding     enc;
             DecoderNLS   decoder;
-            [SecurityCritical]
             unsafe byte* byteStart;
-            [SecurityCritical]
             unsafe byte* byteEnd;
-            [SecurityCritical]
             unsafe byte* bytes;
             DecoderFallbackBuffer fallbackBuffer;
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS decoder, char* charStart, int charCount,
                                                     byte* byteStart, int byteCount)
             {
@@ -1821,12 +1787,11 @@ namespace System.Text
 
                 // If we're getting chars or getting char count we don't expect to have
                 // to remember fallbacks between calls (so it should be empty)
-                Contract.Assert(fallbackBuffer.Remaining == 0,
+                Debug.Assert(fallbackBuffer.Remaining == 0,
                     "[Encoding.EncodingCharBuffer.EncodingCharBuffer]Expected empty fallback buffer for getchars/charcount");
                 fallbackBuffer.InternalInitialize(bytes, charEnd);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddChar(char ch, int numBytes)
             {
                 if (chars != null)
@@ -1845,14 +1810,12 @@ namespace System.Text
                 return true;
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddChar(char ch)
             {
                 return AddChar(ch,1);
             }
 
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddChar(char ch1, char ch2, int numBytes)
             {
                 // Need room for 2 chars
@@ -1866,7 +1829,6 @@ namespace System.Text
                 return AddChar(ch1, numBytes) && AddChar(ch2, numBytes);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe void AdjustBytes(int count)
             {
                 bytes += count;
@@ -1874,7 +1836,6 @@ namespace System.Text
 
             internal unsafe bool MoreData
             {
-                [System.Security.SecurityCritical]  // auto-generated
                 get
                 {
                     return bytes < byteEnd;
@@ -1882,7 +1843,6 @@ namespace System.Text
             }
 
             // Do we have count more bytes?
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool EvenMoreData(int count)
             {
                 return (bytes <= byteEnd - count);
@@ -1890,10 +1850,9 @@ namespace System.Text
 
             // GetNextByte shouldn't be called unless the caller's already checked more data or even more data,
             // but we'll double check just to make sure.
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe byte GetNextByte()
             {
-                Contract.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date");
+                Debug.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date");
                 if (bytes >= byteEnd)
                     return 0;
                 return *(bytes++);
@@ -1901,14 +1860,12 @@ namespace System.Text
 
             internal unsafe int BytesUsed
             {
-                [System.Security.SecurityCritical]  // auto-generated
                 get
                 {
                     return (int)(bytes - byteStart);
                 }
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool Fallback(byte fallbackByte)
             {
                 // Build our buffer
@@ -1918,7 +1875,6 @@ namespace System.Text
                 return Fallback(byteBuffer);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool Fallback(byte byte1, byte byte2)
             {
                 // Build our buffer
@@ -1928,7 +1884,6 @@ namespace System.Text
                 return Fallback(byteBuffer);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4)
             {
                 // Build our buffer
@@ -1938,7 +1893,6 @@ namespace System.Text
                 return Fallback(byteBuffer);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool Fallback(byte[] byteBuffer)
             {
                 // Do the fallback and add the data.
@@ -1974,24 +1928,17 @@ namespace System.Text
 
         internal class EncodingByteBuffer
         {
-            [SecurityCritical]
             unsafe byte* bytes;
-            [SecurityCritical]
             unsafe byte* byteStart;
-            [SecurityCritical]
             unsafe byte* byteEnd;
-            [SecurityCritical]
             unsafe char* chars;
-            [SecurityCritical]
             unsafe char* charStart;
-            [SecurityCritical]
             unsafe char* charEnd;
             int          byteCountResult = 0;
             Encoding     enc;
             EncoderNLS   encoder;
             internal EncoderFallbackBuffer fallbackBuffer;
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS inEncoder,
                         byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount)
             {
@@ -2020,10 +1967,9 @@ namespace System.Text
                 fallbackBuffer.InternalInitialize(chars, charEnd, encoder, bytes != null);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddByte(byte b, int moreBytesExpected)
             {
-                Contract.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected");
+                Debug.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected");
                 if (bytes != null)
                 {
                     if (bytes >= byteEnd - moreBytesExpected)
@@ -2039,31 +1985,26 @@ namespace System.Text
                 return true;
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddByte(byte b1)
             {
                 return (AddByte(b1, 0));
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddByte(byte b1, byte b2)
             {
                 return (AddByte(b1, b2, 0));
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddByte(byte b1, byte b2, int moreBytesExpected)
             {
                 return (AddByte(b1, 1 + moreBytesExpected) && AddByte(b2, moreBytesExpected));
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddByte(byte b1, byte b2, byte b3)
             {
                 return AddByte(b1, b2, b3, (int)0);
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected)
             {
                 return (AddByte(b1, 2 + moreBytesExpected) &&
@@ -2071,7 +2012,6 @@ namespace System.Text
                         AddByte(b3, moreBytesExpected));
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool AddByte(byte b1, byte b2, byte b3, byte b4)
             {
                 return (AddByte(b1, 3) &&
@@ -2080,14 +2020,13 @@ namespace System.Text
                         AddByte(b4, 0));
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe void MovePrevious(bool bThrow)
             {
                 if (fallbackBuffer.bFallingBack)
                     fallbackBuffer.MovePrevious();                      // don't use last fallback
                 else
                 {
-                    Contract.Assert(chars > charStart || 
+                    Debug.Assert(chars > charStart || 
                         ((bThrow == true) && (bytes == byteStart)), 
                         "[EncodingByteBuffer.MovePrevious]expected previous data or throw");
                     if (chars > charStart)
@@ -2098,7 +2037,6 @@ namespace System.Text
                     enc.ThrowBytesOverflow(encoder, bytes == byteStart);    // Throw? (and reset fallback if not converting)
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe bool Fallback(char charFallback)
             {
                 // Do the fallback
@@ -2107,7 +2045,6 @@ namespace System.Text
 
             internal unsafe bool MoreData
             {
-                [System.Security.SecurityCritical]  // auto-generated
                 get
                 {
                     // See if fallbackBuffer is not empty or if there's data left in chars buffer.
@@ -2115,7 +2052,6 @@ namespace System.Text
                 }
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe char GetNextChar()
             {
                  // See if there's something in our fallback buffer
@@ -2133,7 +2069,6 @@ namespace System.Text
 
             internal unsafe int CharsUsed
             {
-                [System.Security.SecurityCritical]  // auto-generated
                 get
                 {
                     return (int)(chars - charStart);
index 5579f6d..9a8dd26 100644 (file)
@@ -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.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Security;
 
@@ -31,12 +32,11 @@ namespace System.Text
         // the parameter, it will call the same method again, which will eventually
         // lead to a StackOverflowException.
 
-        [SecuritySafeCritical]
         public unsafe static int GetByteCount(Encoding encoding, char[] chars, int index, int count)
         {
             // Validate parameters
 
-            Contract.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here
+            Debug.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here
             if (chars == null)
             {
                 throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
@@ -60,10 +60,9 @@ namespace System.Text
                 return encoding.GetByteCount(pChars + index, count, encoder: null);
         }
 
-        [SecuritySafeCritical]
         public unsafe static int GetByteCount(Encoding encoding, string s)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (s == null)
             {
                 string paramName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the string chars
@@ -84,10 +83,9 @@ namespace System.Text
                 return encoding.GetByteCount(pChars, s.Length, encoder: null);
         }
 
-        [SecurityCritical]
         public unsafe static int GetByteCount(Encoding encoding, char* chars, int count)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (chars == null)
             {
                 throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
@@ -102,10 +100,9 @@ namespace System.Text
             return encoding.GetByteCount(chars, count, encoder: null);
         }
 
-        [SecuritySafeCritical]
         public unsafe static int GetBytes(Encoding encoding, string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (s == null || bytes == null)
             {
                 string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars
@@ -139,10 +136,9 @@ namespace System.Text
             }
         }
 
-        [SecuritySafeCritical]
         public unsafe static int GetBytes(Encoding encoding, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (chars == null || bytes == null)
             {
                 throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
@@ -180,10 +176,9 @@ namespace System.Text
             }
         }
 
-        [SecurityCritical]
         public unsafe static int GetBytes(Encoding encoding, char* chars, int charCount, byte* bytes, int byteCount)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (bytes == null || chars == null)
             {
                 throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
@@ -197,10 +192,9 @@ namespace System.Text
             return encoding.GetBytes(chars, charCount, bytes, byteCount, encoder: null);
         }
 
-        [SecuritySafeCritical]
         public unsafe static int GetCharCount(Encoding encoding, byte[] bytes, int index, int count)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (bytes == null)
             {
                 throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
@@ -224,10 +218,9 @@ namespace System.Text
                 return encoding.GetCharCount(pBytes + index, count, decoder: null);
         }
 
-        [SecurityCritical]
         public unsafe static int GetCharCount(Encoding encoding, byte* bytes, int count)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (bytes == null)
             {
                 throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
@@ -241,10 +234,9 @@ namespace System.Text
             return encoding.GetCharCount(bytes, count, decoder: null);
         }
 
-        [SecuritySafeCritical]
         public unsafe static int GetChars(Encoding encoding, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (bytes == null || chars == null)
             {
                 throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
@@ -280,10 +272,9 @@ namespace System.Text
             }
         }
 
-        [SecurityCritical]
         public unsafe static int GetChars(Encoding encoding, byte* bytes, int byteCount, char* chars, int charCount)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (bytes == null || chars == null)
             {
                 throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
@@ -297,10 +288,9 @@ namespace System.Text
             return encoding.GetChars(bytes, byteCount, chars, charCount, decoder: null);
         }
 
-        [SecuritySafeCritical]
         public unsafe static string GetString(Encoding encoding, byte[] bytes, int index, int count)
         {
-            Contract.Assert(encoding != null);
+            Debug.Assert(encoding != null);
             if (bytes == null)
             {
                 throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
index d670d6d..fbddf37 100644 (file)
@@ -50,7 +50,6 @@ namespace System.Text
             return EncodingForwarder.GetByteCount(this, s);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public override unsafe int GetByteCount(char* chars, int count)
         {
             return EncodingForwarder.GetByteCount(this, chars, count);
@@ -77,7 +76,6 @@ namespace System.Text
             return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
         {
             return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
@@ -91,7 +89,6 @@ namespace System.Text
             return EncodingForwarder.GetCharCount(this, bytes, index, count);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public override unsafe int GetCharCount(byte* bytes, int count)
         {
             return EncodingForwarder.GetCharCount(this, bytes, count);
@@ -103,7 +100,6 @@ namespace System.Text
             return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
         {
             return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
index 324d034..8ed52a6 100644 (file)
@@ -85,6 +85,7 @@
 namespace System.Text
 {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Text;
     using System.Runtime.InteropServices;
@@ -107,10 +108,8 @@ namespace System.Text
         // This is the table of 4 byte conversions.
         private const int GBLast4ByteCode = 0x99FB;
         [NonSerialized]
-        [SecurityCritical]
         unsafe internal char* map4BytesToUnicode = null;       // new char[GBLast4ByteCode + 1]; // Need to map all 4 byte sequences to Unicode
         [NonSerialized]
-        [SecurityCritical]
         unsafe internal byte* mapUnicodeTo4BytesFlags = null;  // new byte[0x10000 / 8];         // Need 1 bit for each code point to say if its 4 byte or not
 
         private const int GB18030       = 54936;
@@ -120,37 +119,33 @@ namespace System.Text
         private const int GBLastSurrogateOffset = 0x12E247; // GBE3329A35
 
         // We have to load the 936 code page tables, so impersonate 936 as our base
-        [System.Security.SecurityCritical]  // auto-generated
         internal GB18030Encoding() : base(GB18030, 936)
         {
         }
 
         // Constructor called by serialization.
-        [System.Security.SecurityCritical]  // auto-generated
         internal GB18030Encoding(SerializationInfo info, StreamingContext context) :
                                           base(GB18030, 936)
         {
             // Set up our base, also throws if info was empty
             DeserializeEncoding(info, context);
-            Contract.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw");
+            Debug.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw");
 
             // Already build our code page, fallbacks & read only, so we're good to go!
         }
 
         // ISerializable implementation
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // Make sure to get the base stuff too This throws if info is null
             SerializeEncoding(info, context);
-            Contract.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw");
+            Debug.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw");
 
             // Everett doesn't need more than the basics
         }
 
         // This loads our base 936 code page and then applys the changes from the tableUnicodeToGBDiffs table.
         // See table comments for table format.
-        [System.Security.SecurityCritical]  // auto-generated
         protected override unsafe void LoadManagedCodePage()
         {
             // Use base code page loading algorithm.
@@ -199,7 +194,7 @@ namespace System.Text
                     // It was GB 18030 4 byte data, next <data> characters are 4 byte sequences.
                     while (data > 0)
                     {
-                        Contract.Assert(count4Byte <= GBLast4ByteCode,
+                        Debug.Assert(count4Byte <= GBLast4ByteCode,
                             "[GB18030Encoding.LoadManagedCodePage] Found too many 4 byte codes in data table.");
 
                         // Set the 4 byte -> Unicode value
@@ -217,11 +212,11 @@ namespace System.Text
             }
 
             // unicodeCount should've wrapped back to 0
-            Contract.Assert(unicodeCount == 0,
+            Debug.Assert(unicodeCount == 0,
                 "[GB18030Encoding.LoadManagedCodePage] Expected unicodeCount to wrap around to 0 as all chars were processed");
 
             // We should've read in GBLast4ByteCode 4 byte sequences
-            Contract.Assert(count4Byte == GBLast4ByteCode + 1,
+            Debug.Assert(count4Byte == GBLast4ByteCode + 1,
                 "[GB18030Encoding.LoadManagedCodePage] Expected 0x99FB to be last 4 byte offset, found 0x" + count4Byte.ToString("X4", CultureInfo.InvariantCulture));
 
             // Need to flag ourselves saying we've built this CP.
@@ -238,7 +233,6 @@ namespace System.Text
         // Is4Byte
         // Checks the 4 byte table and returns true if this is a 4 byte code.
         // Its a 4 byte code if the flag is set in mapUnicodeTo4BytesFlags
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe bool Is4Byte(char charTest)
         {
             // See what kind it is
@@ -247,26 +241,24 @@ namespace System.Text
         }
 
         // GetByteCount
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
         {
             // Just call GetBytes() with null bytes
             return GetBytes(chars, count, null, 0, encoder);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS encoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
             // We'll allow null bytes as a count
-//            Contract.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null");
-            Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative");
-            Contract.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null");
-            Contract.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative");
+//            Debug.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null");
+            Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative");
+            Debug.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null");
+            Debug.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback");
+            Debug.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback");
 
             // Get any left over characters
             char charLeftOver = (char)0;
@@ -289,7 +281,7 @@ namespace System.Text
                 // Have to check for charLeftOver
                 if (charLeftOver != 0)
                 {
-                    Contract.Assert(Char.IsHighSurrogate(charLeftOver),
+                    Debug.Assert(Char.IsHighSurrogate(charLeftOver),
                         "[GB18030Encoding.GetBytes] leftover character should be high surrogate, not 0x" + ((int)charLeftOver).ToString("X4", CultureInfo.InvariantCulture));
 
                     // If our next char isn't a low surrogate, then we need to do fallback.
@@ -319,7 +311,7 @@ namespace System.Text
                         offset /= 0x7e;
                         byte byte2 = (byte)((offset % 0x0a) + 0x30);
                         offset /= 0x0a;
-                        Contract.Assert(offset < 0x6f,
+                        Debug.Assert(offset < 0x6f,
                             "[GB18030Encoding.GetBytes](1) Expected offset < 0x6f, not 0x" + offset.ToString("X2", CultureInfo.InvariantCulture));
 
                         charLeftOver = (char)0;
@@ -369,7 +361,7 @@ namespace System.Text
                         iBytes /= 0x7e;
                         byte byte2 = (byte)((iBytes % 0x0a) + 0x30);
                         iBytes /= 0x0a;
-                        Contract.Assert(iBytes < 0x7e,
+                        Debug.Assert(iBytes < 0x7e,
                             "[GB18030Encoding.GetBytes]Expected iBytes < 0x7e, not 0x" + iBytes.ToString("X2", CultureInfo.InvariantCulture));
                         if (!buffer.AddByte((byte)(iBytes + 0x81), byte2, byte3, byte4))
                             break;
@@ -436,23 +428,21 @@ namespace System.Text
         }
 
         // This is internal and called by something else,
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
         {
             // Just call GetChars() with null chars to count
             return GetChars(bytes, count, null, 0, baseDecoder);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS baseDecoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
             // We'll allow null chars as a count
-            Contract.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null");
-            Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative");
-//            Contract.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null");
-            Contract.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative");
+            Debug.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null");
+            Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative");
+//            Debug.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null");
+            Debug.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative");
 
             // Fix our decoder
             GB18030Decoder decoder = (GB18030Decoder)baseDecoder;
@@ -852,7 +842,6 @@ namespace System.Text
             }
 
             // Constructor called by serialization, have to handle deserializing from Everett
-            [System.Security.SecurityCritical]  // auto-generated
             internal GB18030Decoder(SerializationInfo info, StreamingContext context)
             {
                 // Any info?
@@ -879,7 +868,6 @@ namespace System.Text
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // Any info?
index 83ca500..751b821 100644 (file)
@@ -9,6 +9,7 @@
 namespace System.Text
 {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Globalization;
     using System.Runtime.Serialization;
@@ -72,7 +73,7 @@ namespace System.Text
             defaultCodePage = codePage - 57000;
 
             // Legal windows code pages are between Devanagari and Punjabi
-            Contract.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi,
+            Debug.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi,
                 "[ISCIIEncoding] Code page (" + codePage + " isn't supported by ISCIIEncoding!");
 
             // This shouldn't really be possible
@@ -86,17 +87,16 @@ namespace System.Text
         {
             // Actually this can't ever get called, MLangCodePageEncoding is our proxy
             // (In Everett this was done by MLang)
-            Contract.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor");
+            Debug.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor");
             throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
         }
 
         // ISerializable implementation
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // Make sure to get the base stuff too This throws if info is null
             SerializeEncoding(info, context);
-            Contract.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw");
+            Debug.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw");
 
             // Just need Everett MLangCodePageEncoding maxCharSize
             info.AddValue("m_maxByteSize", 2);
@@ -155,7 +155,6 @@ namespace System.Text
         }
 
         // Our workhorse version
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
         {
             // Use null pointer to ask GetBytes for count
@@ -163,15 +162,14 @@ namespace System.Text
         }
 
         // Workhorse
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char *chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS baseEncoder)
         {
             // Allow null bytes for counting
-            Contract.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null");
-//            Contract.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null");
-            Contract.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0");
-            Contract.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0");
+            Debug.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null");
+//            Debug.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null");
+            Debug.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0");
+            Debug.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0");
 
             // Need the ISCII Encoder
             ISCIIEncoder encoder = (ISCIIEncoder) baseEncoder;
@@ -268,7 +266,7 @@ namespace System.Text
 
                 // See if our code page ("font" in ISCII spec) has to change
                 // (This if doesn't add character, just changes character set)
-                Contract.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value");
+                Debug.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value");
                 if (indicScript != currentCodePage)
                 {
                     // It changed, spit out the ATR
@@ -279,7 +277,7 @@ namespace System.Text
                     currentCodePage = indicScript;
 
                     // We only know how to map from Unicode to pages from Devanagari to Punjabi (2 to 11)
-                    Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
+                    Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
                         "[ISCIIEncoding.GetBytes]Code page (" + currentCodePage + " shouldn't appear in ISCII from Unicode table!");
                 }
 
@@ -294,7 +292,7 @@ namespace System.Text
                 if (indicTwoBytes != 0)
                 {
                     // This one needs another byte
-                    Contract.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3,
+                    Debug.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3,
                         "[ISCIIEncoding.GetBytes]Expected indicTwoBytes from 1-3, not " + (indicTwoBytes >> 12));
 
                     // Already did buffer checking, but...
@@ -341,7 +339,6 @@ namespace System.Text
        }
 
         // Workhorse
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
         {
             // Just call GetChars with null chars saying we want count
@@ -354,16 +351,15 @@ namespace System.Text
         // Devenagari F0, B8 -> \u0952
         // Devenagari F0, BF -> \u0970
         // Some characters followed by E9 become a different character instead.
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS baseDecoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
             // Allow null chars for counting
-            Contract.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null");
-            Contract.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative");
-//            Contract.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null");
-            Contract.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative");
+            Debug.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null");
+            Debug.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative");
+//            Debug.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null");
+            Debug.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative");
 
             // Need the ISCII Decoder
             ISCIIDecoder decoder = (ISCIIDecoder) baseDecoder;
@@ -395,7 +391,7 @@ namespace System.Text
 
             // Get our current code page index (some code pages are dups)
             int currentCodePageIndex = -1;
-            Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
+            Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
                 "[ISCIIEncoding.GetChars]Decoder code page must be >= Devanagari and <= Punjabi, not " + currentCodePage);
 
             if (currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi)
@@ -415,7 +411,7 @@ namespace System.Text
                     bLastSpecial = false;
 
                     // One and only one of our flags should be set
-                    Contract.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) +
+                    Debug.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) +
                                (bLastDevenagariStressAbbr ? 1 : 0) +
                                ((cLastCharForNextNukta > 0) ? 1 : 0)) == 1,
                         String.Format(CultureInfo.InvariantCulture,
@@ -476,10 +472,10 @@ namespace System.Text
                         bLastATR = false;
 
                         // we know we can't have any of these other modes
-                        Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode");
-                        Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode");
-                        Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode");
-                        Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode");
+                        Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode");
+                        Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode");
+                        Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode");
+                        Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode");
 
                         // Keep processing this byte
                     }
@@ -508,10 +504,10 @@ namespace System.Text
                         bLastVirama = false;
 
                         // We know we can't have any of these other modes
-                        Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode");
-                        Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode");
-                        Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode");
-                        Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode");
+                        Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode");
+                        Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode");
+                        Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode");
+                        Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode");
                     }
                     else if (bLastDevenagariStressAbbr)
                     {
@@ -544,15 +540,15 @@ namespace System.Text
                         // (last character was added when mode was set)
                         bLastDevenagariStressAbbr = false;
 
-                        Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode");
-                        Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode");
-                        Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode");
-                        Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode");                        
+                        Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode");
+                        Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode");
+                        Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode");
+                        Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode");                        
                     }
                     else
                     {
                         // We were checking for next char being a nukta
-                        Contract.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0,
+                        Debug.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0,
                             "[ISCIIEncoding.GetChars]No other special case found, but cLastCharFor(No)NextNukta variable(s) aren't set.");
 
                         // We'll either add combined char or last char
@@ -574,14 +570,14 @@ namespace System.Text
                         // Keep processing this byte, turn off mode.
                         cLastCharForNextNukta = cLastCharForNoNextNukta = '\0';
                         
-                        Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode");
-                        Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode");
-                        Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode");                        
+                        Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode");
+                        Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode");
+                        Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode");                        
                     }
                 }
 
                 // Now bLastSpecial should be false and all flags false.
-                Contract.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR &&
+                Debug.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR &&
                           cLastCharForNextNukta == '\0',
                           "[ISCIIEncoding.GetChars]No special state for last code point should exist at this point.");
 
@@ -600,7 +596,7 @@ namespace System.Text
                     continue;
                 }
 
-                Contract.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1");
+                Debug.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1");
                 char ch = IndicMapping[currentCodePageIndex, 0, b - MultiByteBegin];
                 char cAlt = IndicMapping[currentCodePageIndex, 1, b - MultiByteBegin];
 
@@ -646,7 +642,7 @@ namespace System.Text
                 }
 
                 // We must be the Devenagari special case for F0, B8 & F0, BF
-                Contract.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt,
+                Debug.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt,
                     String.Format(CultureInfo.InvariantCulture,
                         "[ISCIIEncoding.GetChars] Devenagari special case must {0} not {1} or in Devanagari code page {2} not {3}.",
                         DevenagariExt, b, CodeDevanagari, currentCodePage));
@@ -701,7 +697,7 @@ namespace System.Text
                     cLastCharForNoNextNukta != '\0' || bLastATR || bLastDevenagariStressAbbr)
                 {
                     // Either not flushing or had state (from convert)
-                    Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+                    Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
                         "[ISCIIEncoding.GetChars]Expected no state or not converting or not flushing");
                     decoder.currentCodePage = currentCodePage;
                     decoder.bLastVirama = bLastVirama;
index f7e0616..fca579f 100644 (file)
@@ -28,6 +28,7 @@
 namespace System.Text
 {
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Text;
     using System.Runtime.InteropServices;
@@ -53,7 +54,6 @@ namespace System.Text
 
         // We have to load the 936 code page tables, so impersonate 936 as our base
         // This pretends to be other code pages as far as memory sections are concerned.
-        [System.Security.SecurityCritical]  // auto-generated
         internal ISO2022Encoding(int codePage) : base(codePage, tableBaseCodePages[codePage % 10])
         {
             this.m_bUseMlangTypeForSerialization = true;
@@ -61,11 +61,10 @@ namespace System.Text
 
         // Constructor called by serialization.
         // Note:  We use the base GetObjectData however
-        [System.Security.SecurityCritical]  // auto-generated
         internal ISO2022Encoding(SerializationInfo info, StreamingContext context) : base(info, context)
         {
             // Actually this can't ever get called, CodePageEncoding is our proxy
-            Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
+            Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
             throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
         }
 
@@ -102,7 +101,6 @@ namespace System.Text
             ModeNOOP                = -3
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         protected unsafe override String GetMemorySectionName()
         {
             int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
@@ -123,7 +121,7 @@ namespace System.Text
                     strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}_HZ";
                     break;
                 default:
-                    Contract.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage);
+                    Debug.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage);
                     strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}";
                     break;
             }
@@ -263,28 +261,26 @@ namespace System.Text
         }
 
         // GetByteCount
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative");
-            Contract.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null");
+            Debug.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative");
+            Debug.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null");
 
             // Just call GetBytes with null byte* to get count
             return GetBytes(chars, count, null, 0, baseEncoder);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS baseEncoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null");
-            Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative");
-            Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative");
+            Debug.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null");
+            Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative");
+            Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback");
+            Debug.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback");
 
             // Fix our encoder
             ISO2022Encoder encoder = (ISO2022Encoder)baseEncoder;
@@ -316,25 +312,23 @@ namespace System.Text
         }
 
         // This is internal and called by something else,
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
         {
             // Just assert, we're called internally so these should be safe, checked already
-            Contract.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null");
-            Contract.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative");
+            Debug.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null");
+            Debug.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative");
 
             // Just call getChars with null char* to get count
             return GetChars(bytes, count, null, 0, baseDecoder);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS baseDecoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null");
-            Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative");
-            Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative");
+            Debug.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null");
+            Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative");
+            Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative");
 
             // Fix our decoder
             ISO2022Decoder decoder = (ISO2022Decoder)baseDecoder;
@@ -358,7 +352,7 @@ namespace System.Text
                     iCount = GetCharsCP52936( bytes, byteCount, chars, charCount, decoder);
                     break;
                 default:
-                    Contract.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page");
+                    Debug.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page");
                     break;
             }
 
@@ -399,7 +393,6 @@ namespace System.Text
         // undefined, so we maintain that behavior when decoding.  We will never generate characters using
         // that technique, but the decoder will process them.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe int GetBytesCP5022xJP(char* chars, int charCount,
                                                   byte* bytes, int byteCount, ISO2022Encoder encoder)
         {
@@ -422,7 +415,7 @@ namespace System.Text
                 // We may have a left over character from last time, try and process it.
                 if (charLeftOver > 0)
                 {
-                    Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate");
+                    Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate");
 
                     // It has to be a high surrogate, which we don't support, so it has to be a fallback
                     buffer.Fallback(charLeftOver);
@@ -483,7 +476,7 @@ namespace System.Text
                         else
                         {
                             // 50221 does halfwidth katakana by escape sequence
-                            Contract.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221");
+                            Debug.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221");
 
                             // Add our escape sequence
                             if (!buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'I')))
@@ -642,7 +635,6 @@ namespace System.Text
         // Also Mlang always assumed KR mode, even if the designator wasn't found yet, so we do that as
         // well.  So basically we just ignore <ESC>$)C when decoding.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe int GetBytesCP50225KR(char* chars, int charCount,
                                                     byte* bytes, int byteCount, ISO2022Encoder encoder)
         {
@@ -665,7 +657,7 @@ namespace System.Text
                 // We may have a l left over character from last time, try and process it.
                 if (charLeftOver > 0)
                 {
-                    Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate");
+                    Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate");
 
                     // It has to be a high surrogate, which we don't support, so it has to be a fallback
                     buffer.Fallback(charLeftOver);
@@ -765,7 +757,7 @@ namespace System.Text
                 if (!encoder.MustFlush || encoder.charLeftOver != (char)0)
                 {
                     // We should be not flushing or converting
-                    Contract.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow,
+                    Debug.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow,
                         "[ISO2022Encoding.GetBytesCP50225KR]Expected no left over data or not flushing or not converting");
                     encoder.shiftInOutMode = shiftOutMode;
                 }
@@ -793,7 +785,6 @@ namespace System.Text
         //
         // This encoding is designed for transmission by e-mail and news.  No bytes should have high bit set.
         // (all bytes <= 0x7f)
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe int GetBytesCP52936(char* chars, int charCount,
                                            byte* bytes, int byteCount, ISO2022Encoder encoder)
         {
@@ -813,7 +804,7 @@ namespace System.Text
                 // We may have a left over character from last time, try and process it.
                 if (charLeftOver > 0)
                 {
-                    Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate");
+                    Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate");
 
                     // It has to be a high surrogate, which we don't support, so it has to be a fallback
                     buffer.Fallback(charLeftOver);
@@ -928,7 +919,6 @@ namespace System.Text
             return buffer.Count;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount,
                                                   char* chars, int charCount, ISO2022Decoder decoder)
         {
@@ -1139,7 +1129,7 @@ namespace System.Text
                 if (!decoder.MustFlush || escapeCount != 0)
                 {
                     // Either not flushing or had state (from convert)
-                    Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+                    Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
                         "[ISO2022Encoding.GetCharsCP5022xJP]Expected no state or not converting or not flushing");
                                         
                     decoder.currentMode = currentMode;
@@ -1233,7 +1223,7 @@ namespace System.Text
 
         private byte DecrementEscapeBytes(ref byte[] bytes, ref int count)
         {
-            Contract.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0");
+            Debug.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0");
 
             // Decrement our count
             count--;
@@ -1256,7 +1246,6 @@ namespace System.Text
 
         // Note that in DBCS mode mlang passed through ' ', '\t' and '\n' as SBCS characters
         // probably to allow mailer formatting without too much extra work.
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount,
                                                    char* chars, int charCount, ISO2022Decoder decoder)
         {
@@ -1441,7 +1430,7 @@ namespace System.Text
                 if (!decoder.MustFlush || escapeCount != 0)
                 {
                     // Either not flushing or had state (from convert)
-                    Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+                    Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
                         "[ISO2022Encoding.GetCharsCP50225KR]Expected no state or not converting or not flushing");
                     
                     decoder.currentMode = currentMode;
@@ -1496,12 +1485,11 @@ namespace System.Text
         //
         // This encoding is designed for transmission by e-mail and news.  No bytes should have high bit set.
         // (all bytes <= 0x7f)
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe int GetCharsCP52936(byte* bytes, int byteCount,
                                                 char* chars, int charCount, ISO2022Decoder decoder)
         {
-            Contract.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0");
-            Contract.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null");
+            Debug.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0");
+            Debug.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null");
 
             // Get our info.
             Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
@@ -1612,7 +1600,7 @@ namespace System.Text
                 if (currentMode != ISO2022Modes.ModeASCII)
                 {
                     // Should be ModeHZ
-                    Contract.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ");
+                    Debug.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ");
                     char cm;
 
                     // Everett allowed characters < 0x20 to be passed as if they were ASCII
@@ -1737,7 +1725,7 @@ namespace System.Text
                 else
                 {
                     // Either not flushing or had state (from convert)
-                    Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+                    Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
                         "[ISO2022Encoding.GetCharsCP52936]Expected no state or not converting or not flushing");
                                         
                     decoder.currentMode = currentMode;
index a4b863d..56a6c1f 100644 (file)
@@ -5,6 +5,7 @@
 namespace System.Text
 {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Globalization;
     using System.Runtime.InteropServices;
@@ -43,12 +44,11 @@ namespace System.Text
         }
 
         // ISerializable implementation, serialize it as a CodePageEncoding
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // Make sure to get the base stuff too This throws if info is null
             SerializeEncoding(info, context);
-            Contract.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw");
+            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);
@@ -61,15 +61,14 @@ namespace System.Text
         // GetByteCount
         // Note: We start by assuming that the output will be the same as count.  Having
         // an encoder or fallback may change that assumption
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative");
-            Contract.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null");
+            Debug.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative");
+            Debug.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder");
+            Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder");
 
             char charLeftOver = (char)0;
 
@@ -79,13 +78,13 @@ namespace System.Text
             if (encoder != null)
             {
                 charLeftOver = encoder.charLeftOver;
-                Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+                Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
                     "[Latin1Encoding.GetByteCount]leftover character should be high surrogate");
 
                 fallback = encoder.Fallback as EncoderReplacementFallback;
 
                 // Verify that we have no fallbackbuffer, for Latin1 its always empty, so just assert
-                Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
                     encoder.FallbackBuffer.Remaining == 0,
                     "[Latin1CodePageEncoding.GetByteCount]Expected empty fallback buffer");
             }
@@ -122,7 +121,7 @@ namespace System.Text
             if (charLeftOver > 0)
             {
                 // Initialize the buffer
-                Contract.Assert(encoder != null,
+                Debug.Assert(encoder != null,
                     "[Latin1Encoding.GetByteCount]Expected encoder if we have charLeftOver");
                 fallbackBuffer = encoder.FallbackBuffer;
                 fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
@@ -171,24 +170,23 @@ namespace System.Text
                 byteCount++;
             }
 
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[Latin1Encoding.GetByteCount]Expected Empty fallback buffer");
 
             return byteCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS encoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null");
-            Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative");
-            Contract.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null");
-            Contract.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative");
+            Debug.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null");
+            Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative");
+            Debug.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null");
+            Debug.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback");
+            Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback");
 
             // Get any left over characters & check fast or slower fallback type
             char charLeftOver = (char)0;
@@ -197,11 +195,11 @@ namespace System.Text
             {
                 charLeftOver = encoder.charLeftOver;
                 fallback = encoder.Fallback as EncoderReplacementFallback;
-                Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+                Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
                     "[Latin1Encoding.GetBytes]leftover character should be high surrogate");
 
                 // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
-                Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
                     encoder.FallbackBuffer.Remaining == 0,
                     "[Latin1CodePageEncoding.GetBytes]Expected empty fallback buffer");
             }
@@ -284,7 +282,7 @@ namespace System.Text
             {
                 // Since left over char was a surrogate, it'll have to be fallen back.
                 // Get Fallback
-                Contract.Assert(encoder != null,
+                Debug.Assert(encoder != null,
                     "[Latin1Encoding.GetBytes]Expected encoder if we have charLeftOver");
                 fallbackBuffer = encoder.FallbackBuffer;
                 fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
@@ -338,7 +336,7 @@ namespace System.Text
                     {
                         // Didn't use this char, throw it.  Chars should've advanced by now
                         // If we had encoder fallback data it would've thrown before the loop
-                        Contract.Assert(chars > charStart, 
+                        Debug.Assert(chars > charStart, 
                             "[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)");
                         chars--;
                         fallbackBuffer.InternalReset();
@@ -356,11 +354,11 @@ namespace System.Text
                 if (bytes >= byteEnd)
                 {
                     // didn't use this char, we'll throw or use buffer
-                    Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
+                    Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
                         "[Latin1Encoding.GetBytes]Expected fallback to have throw initially if insufficient space");
                     if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
                     {
-                        Contract.Assert(chars > charStart, 
+                        Debug.Assert(chars > charStart, 
                             "[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)");
                         chars--;                                        // don't use last char
                     }
@@ -385,34 +383,32 @@ namespace System.Text
                 encoder.m_charsUsed = (int)(chars - charStart);
             }
 
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[Latin1Encoding.GetBytes]Expected Empty fallback buffer");
 
             return (int)(bytes - byteStart);
         }
 
         // This is internal and called by something else,
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
         {
             // Just assert, we're called internally so these should be safe, checked already
-            Contract.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null");
-            Contract.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative");
+            Debug.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null");
+            Debug.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative");
 
             // Just return length, SBCS stay the same length because they don't map to surrogate
             // pairs and we don't have to fallback because all latin1Encoding code points are unicode
             return count;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS decoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null");
-            Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative");
-            Contract.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null");
-            Contract.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative");
+            Debug.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null");
+            Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative");
+            Debug.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null");
+            Debug.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative");
 
             // Need byteCount chars, otherwise too small buffer
             if (charCount < byteCount)
index e65bcee..a82db91 100644 (file)
@@ -13,6 +13,7 @@ namespace System.Text
     using System;
     using System.Runtime.Serialization;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     /*=================================MLangCodePageEncoding==================================
@@ -76,7 +77,6 @@ namespace System.Text
         }
 
         // Just get it from GetEncoding
-        [System.Security.SecurityCritical]  // auto-generated
         public Object GetRealObject(StreamingContext context)
         {
             // Get our encoding (Note: This has default fallbacks for readonly and everett cases)
@@ -95,11 +95,10 @@ namespace System.Text
         }
 
         // ISerializable implementation
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // We cannot ever call this.
-            Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData");
+            Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData");
             throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));        
         }
 
@@ -122,18 +121,16 @@ namespace System.Text
             }
 
             // Just get it from GetEncoder
-            [System.Security.SecurityCritical]  // auto-generated
             public Object GetRealObject(StreamingContext context)
             {
                 return this.realEncoding.GetEncoder();
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // We cannot ever call this.
-                Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData");
+                Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData");
                 throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
             }
         }
@@ -158,18 +155,16 @@ namespace System.Text
             }
 
             // Just get it from GetDecoder
-            [System.Security.SecurityCritical]  // auto-generated
             public Object GetRealObject(StreamingContext context)
             {
                 return this.realEncoding.GetDecoder();
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // We cannot ever call this.
-                Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData");
+                Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData");
                 throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
             }
         }
index 7820bbe..b2faf0d 100644 (file)
@@ -11,6 +11,7 @@ namespace System.Text
     using System.Runtime.CompilerServices;
     using System.Runtime.InteropServices;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // This internal class wraps up our normalization behavior
@@ -43,7 +44,6 @@ namespace System.Text
         private const int ERROR_INSUFFICIENT_BUFFER = 122;
         private const int ERROR_NO_UNICODE_TRANSLATION = 1113;
 
-        [System.Security.SecurityCritical]  // auto-generated
         static private unsafe void InitializeForm(NormalizationForm form, String strDataFile)
         {
             byte* pTables = null;
@@ -73,7 +73,6 @@ namespace System.Text
             nativeNormalizationInitNormalization(form, pTables);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         static private void EnsureInitialized(NormalizationForm form)
         {
             switch ((ExtendedNormalizationForms)form)
@@ -150,7 +149,6 @@ namespace System.Text
             }
         }
 
-        [System.Security.SecurityCritical]
         internal static bool IsNormalized(String strInput, NormalizationForm normForm)
         {
             Contract.Requires(strInput != null);
@@ -187,7 +185,6 @@ namespace System.Text
             return result;
         }
 
-        [System.Security.SecurityCritical]
         internal static String Normalize(String strInput, NormalizationForm normForm)
         {
             Contract.Requires(strInput != null);
@@ -246,7 +243,7 @@ namespace System.Text
                 {
                     // Do appropriate stuff for the individual errors:
                     case ERROR_INSUFFICIENT_BUFFER:
-                        Contract.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
+                        Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
                         continue;
 
                     case ERROR_INVALID_PARAMETER:
@@ -270,20 +267,17 @@ namespace System.Text
             return new String(cBuffer, 0, iLength);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe private static extern int nativeNormalizationNormalizeString(
             NormalizationForm normForm, ref int iError,
             String lpSrcString, int cwSrcLength,
             char[] lpDstString, int cwDstLength);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe private static extern bool nativeNormalizationIsNormalizedString(
             NormalizationForm normForm, ref int iError,
             String lpString, int cwLength);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [SuppressUnmanagedCodeSecurity]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         unsafe private static extern void nativeNormalizationInitNormalization(
index b21ba78..8b07149 100644 (file)
@@ -6,6 +6,7 @@
 namespace System.Text
 {
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Text;
     using System.Threading;
@@ -20,13 +21,10 @@ namespace System.Text
     {
         // Pointers to our memory section parts
         [NonSerialized]
-        [SecurityCritical]
         unsafe char* mapBytesToUnicode = null;      // char 256
         [NonSerialized]
-        [SecurityCritical]
         unsafe byte* mapUnicodeToBytes = null;      // byte 65536
         [NonSerialized]
-        [SecurityCritical]
         unsafe int*  mapCodePageCached = null;      // to remember which CP is cached
 
         const char UNKNOWN_CHAR=(char)0xFFFD;
@@ -37,23 +35,20 @@ namespace System.Text
         [NonSerialized]
         char  charUnknown;
 
-        [System.Security.SecurityCritical]  // auto-generated
         public SBCSCodePageEncoding(int codePage) : this(codePage, codePage)
         {
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal SBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
         {
         }
 
         // Constructor called by serialization.
         // Note:  We use the base GetObjectData however
-        [System.Security.SecurityCritical]  // auto-generated
         internal SBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
         {
             // Actually this can't ever get called, CodePageEncoding is our proxy
-            Contract.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor");
+            Debug.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor");
             throw new ArgumentNullException("this");
         }
 
@@ -69,11 +64,10 @@ namespace System.Text
         //              byte < 0x20 means skip the next n positions.  (Where n is the byte #)
         //              byte == 1 means that next word is another unicode code point #
         //              byte == 0 is unknown.  (doesn't override initial WCHAR[256] table!
-        [System.Security.SecurityCritical]  // auto-generated
         protected override unsafe void LoadManagedCodePage()
         {
             // Should be loading OUR code page
-            Contract.Assert(pCodePage->CodePage == this.dataTableCodePage,
+            Debug.Assert(pCodePage->CodePage == this.dataTableCodePage,
                 "[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
 
             // Make sure we're really a 1 byte code page
@@ -96,7 +90,7 @@ namespace System.Text
             // If its cached (& filled in) we don't have to do anything else
             if (*mapCodePageCached != 0)
             {
-                Contract.Assert(*mapCodePageCached == this.dataTableCodePage,
+                Debug.Assert(*mapCodePageCached == this.dataTableCodePage,
                     "[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page to be same as data table code page.  Cached : " +
                     *mapCodePageCached + " Expected:" + this.dataTableCodePage);
 
@@ -151,7 +145,6 @@ namespace System.Text
         }
 
         // Read in our best fit table
-        [System.Security.SecurityCritical]  // auto-generated
         protected unsafe override void ReadBestFitTable()
         {
             // Lock so we don't confuse ourselves.
@@ -180,7 +173,7 @@ namespace System.Text
                     while ((byteTemp = *((ushort*)pData)) != 0)
                     {
 
-                        Contract.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture,
+                        Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture,
                             "[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{2:X2}) for best fit byte at 0x{0:X2} for code page {1}",
                             byteTemp, CodePage, (int)arrayTemp[byteTemp]));
                         pData += 2;
@@ -281,7 +274,7 @@ namespace System.Text
                                 arrayTemp[iBestFitCount++] = mapBytesToUnicode[input];
 
                                 // This won't work if it won't round trip.
-                                Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0,
+                                Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0,
                                     String.Format(CultureInfo.InvariantCulture,
                                     "[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}",
                                     (int)mapBytesToUnicode[input], (int)input, CodePage));
@@ -299,15 +292,14 @@ namespace System.Text
         // GetByteCount
         // Note: We start by assuming that the output will be the same as count.  Having
         // an encoder or fallback may change that assumption
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative");
-            Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null");
+            Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative");
+            Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
+            Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
 
             CheckMemorySection();
 
@@ -319,12 +311,12 @@ namespace System.Text
             if (encoder != null)
             {
                 charLeftOver = encoder.charLeftOver;
-                Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+                Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
                     "[SBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
                 fallback = encoder.Fallback as EncoderReplacementFallback;
 
                 // Verify that we have no fallbackbuffer, actually for SBCS this is always empty, so just assert
-                Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
                     encoder.FallbackBuffer.Remaining == 0,
                     "[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start");
             }
@@ -363,7 +355,7 @@ namespace System.Text
             {
                 // Since left over char was a surrogate, it'll have to be fallen back.
                 // Get Fallback
-                Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
+                Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
                 fallbackBuffer = encoder.FallbackBuffer;
                 fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
 
@@ -414,24 +406,23 @@ namespace System.Text
                 byteCount++;
             }
 
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end");
 
             return (int)byteCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS encoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null");
-            Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative");
-            Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null");
-            Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative");
+            Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null");
+            Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative");
+            Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null");
+            Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative");
 
             // Assert because we shouldn't be able to have a null encoder.
-            Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
+            Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
 
             CheckMemorySection();
 
@@ -443,12 +434,12 @@ namespace System.Text
             if (encoder != null)
             {
                 charLeftOver = encoder.charLeftOver;
-                Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+                Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
                     "[SBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
                 fallback = encoder.Fallback as EncoderReplacementFallback;
 
                 // Verify that we have no fallbackbuffer, for SBCS its always empty, so just assert
-                Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
                     encoder.FallbackBuffer.Remaining == 0,
                     "[SBCSCodePageEncoding.GetBytes]Expected empty fallback buffer at start");
 //                if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
@@ -545,7 +536,7 @@ namespace System.Text
             {
                 // Since left over char was a surrogate, it'll have to be fallen back.
                 // Get Fallback
-                Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
+                Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
                 fallbackBuffer = encoder.FallbackBuffer;
                 fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
 
@@ -598,7 +589,7 @@ namespace System.Text
                     if (fallbackBuffer.Remaining > byteEnd - bytes)
                     {
                         // Didn't use this char, reset it
-                        Contract.Assert(chars > charStart,
+                        Debug.Assert(chars > charStart,
                             "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)");
                         chars--;
                         fallbackBuffer.InternalReset();
@@ -615,11 +606,11 @@ namespace System.Text
                 if (bytes >= byteEnd)
                 {
                     // didn't use this char, we'll throw or use buffer
-                    Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
+                    Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
                         "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back");
                     if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
                     {
-                        Contract.Assert(chars > charStart,
+                        Debug.Assert(chars > charStart,
                             "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)");                        
                         chars--;                                        // don't use last char
                     }
@@ -645,19 +636,18 @@ namespace System.Text
             }
 
             // Expect Empty fallback buffer for SBCS
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end");
 
             return (int)(bytes - byteStart);
         }
 
         // This is internal and called by something else,
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
         {
             // Just assert, we're called internally so these should be safe, checked already
-            Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null");
-            Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative");
+            Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null");
+            Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative");
 
             CheckMemorySection();
 
@@ -676,7 +666,7 @@ namespace System.Text
             {
                 fallback = decoder.Fallback as DecoderReplacementFallback;
                 bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback;
-                Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
                     decoder.FallbackBuffer.Remaining == 0,
                     "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
             }
@@ -729,22 +719,21 @@ namespace System.Text
             }
 
             // Fallback buffer must be empty
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end");
 
             // Converted sequence is same length as input
             return charCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS decoder)
         {
             // Just need to ASSERT, this is called by something else internal that checked parameters already
-            Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null");
-            Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative");
-            Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null");
-            Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative");
+            Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null");
+            Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative");
+            Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null");
+            Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative");
 
             CheckMemorySection();
 
@@ -768,7 +757,7 @@ namespace System.Text
             {
                 fallback = decoder.Fallback as DecoderReplacementFallback;
                 bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback;
-                Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+                Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
                     decoder.FallbackBuffer.Remaining == 0,
                     "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
             }
@@ -848,7 +837,7 @@ namespace System.Text
                     }
 
                     // Use fallback buffer
-                    Contract.Assert(bytes > byteStart,
+                    Debug.Assert(bytes > byteStart,
                         "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (unknown byte)");
                     byteBuffer[0] = *(bytes - 1);
                     // Fallback adds fallback to chars, but doesn't increment chars unless the whole thing fits.
@@ -866,7 +855,7 @@ namespace System.Text
                     // Make sure we have buffer space
                     if (chars >= charEnd)
                     {
-                        Contract.Assert(bytes > byteStart,
+                        Debug.Assert(bytes > byteStart,
                             "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)");                        
                         bytes--;                                            // unused byte
                         ThrowCharsOverflow(decoder, bytes == byteStart);    // throw?
@@ -883,7 +872,7 @@ namespace System.Text
                 decoder.m_bytesUsed = (int)(bytes - byteStart);
 
             // Expect Empty fallback buffer for GetChars
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[SBCSEncoding.GetChars]Expected Empty fallback buffer at end");
 
             return (int)(chars - charStart);
index f525118..f20146f 100644 (file)
@@ -20,7 +20,9 @@ namespace System.Text {
     using System.Security;
     using System.Threading;
     using System.Globalization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
+    using System.Collections.Generic;
 
     // This class represents a mutable string.  It is convenient for situations in
     // which it is desirable to modify a string, perhaps by removing, replacing, or 
@@ -117,7 +119,6 @@ namespace System.Text {
         // Creates a new string builder from the specifed substring with the specified
         // capacity.  The maximum number of characters is set by capacity.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringBuilder(String value, int startIndex, int length, int capacity) {
             if (capacity<0) {
                 throw new ArgumentOutOfRangeException(nameof(capacity),
@@ -177,7 +178,6 @@ namespace System.Text {
             m_ChunkChars = new char[capacity];
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private StringBuilder(SerializationInfo info, StreamingContext context) {
             if (info == null)
                 throw new ArgumentNullException(nameof(info));
@@ -240,7 +240,6 @@ namespace System.Text {
             VerifyClassInvariant();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info==null) {
@@ -264,21 +263,21 @@ namespace System.Text {
             for (; ; )
             {
                 // All blocks have copy of the maxCapacity.
-                Contract.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
-                Contract.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer");
+                Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
+                Debug.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer");
 
-                Contract.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length");
-                Contract.Assert(currentBlock.m_ChunkLength >= 0, "Negative length");
-                Contract.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset");
+                Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length");
+                Debug.Assert(currentBlock.m_ChunkLength >= 0, "Negative length");
+                Debug.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset");
 
                 StringBuilder prevBlock = currentBlock.m_ChunkPrevious;
                 if (prevBlock == null)
                 {
-                    Contract.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0");
+                    Debug.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0");
                     break;
                 }
                 // There are no gaps in the blocks. 
-                Contract.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!");
+                Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!");
                 currentBlock = prevBlock;
             }
         }
@@ -326,7 +325,6 @@ namespace System.Text {
             return Capacity;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
 
@@ -370,7 +368,6 @@ namespace System.Text {
 
 
         // Converts a substring of this string builder to a String.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(int startIndex, int length) {
             Contract.Ensures(Contract.Result<String>() != null);
 
@@ -477,7 +474,7 @@ namespace System.Text {
                 {
                     m_ChunkLength = 0;
                     m_ChunkOffset = 0;
-                    Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
+                    Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
                     return;
                 }
 
@@ -499,7 +496,7 @@ namespace System.Text {
                         int newLen = originalCapacity - chunk.m_ChunkOffset;
                         char[] newArray = new char[newLen];
 
-                        Contract.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing");
+                        Debug.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing");
                         Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength);
                         
                         m_ChunkChars = newArray;
@@ -509,7 +506,7 @@ namespace System.Text {
                     m_ChunkLength = value - chunk.m_ChunkOffset;
                     VerifyClassInvariant();
                 }
-                Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
+                Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
             }
         }
 
@@ -581,7 +578,7 @@ namespace System.Text {
                 {
                     m_ChunkLength = idx;
                     ExpandByABlock(repeatCount);
-                    Contract.Assert(m_ChunkLength == 0, "Expand should create a new block");
+                    Debug.Assert(m_ChunkLength == 0, "Expand should create a new block");
                     idx = 0;
                 }
             }
@@ -591,7 +588,6 @@ namespace System.Text {
         }
 
         // Appends an array of characters at the end of this string builder. The capacity is adjusted as needed. 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringBuilder Append(char[] value, int startIndex, int charCount) {
             if (startIndex < 0) {
                 throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
@@ -628,7 +624,6 @@ namespace System.Text {
 
 
         // Appends a copy of this string at the end of this string builder.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringBuilder Append(String value) {
             Contract.Ensures(Contract.Result<StringBuilder>() != null);
 
@@ -667,7 +662,6 @@ namespace System.Text {
 
         // We put this fixed in its own helper to avoid the cost zero initing valueChars in the
         // case we don't actually use it.  
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private void AppendHelper(string value) {
             unsafe {
                 fixed (char* valueChars = value)
@@ -676,16 +670,13 @@ namespace System.Text {
         }
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecurityCritical]
         internal unsafe extern void ReplaceBufferInternal(char* newBuffer, int newLength);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecurityCritical]
         internal unsafe extern void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength);
 
         // Appends a copy of the characters in value from startIndex to startIndex +
         // count at the end of this string builder.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringBuilder Append(String value, int startIndex, int count) {
             if (startIndex < 0) {
                 throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
@@ -738,7 +729,6 @@ namespace System.Text {
         }
 
         [System.Runtime.InteropServices.ComVisible(false)]
-        [SecuritySafeCritical]
         public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) {
             if (destination == null) {
                 throw new ArgumentNullException(nameof(destination));
@@ -802,7 +792,6 @@ namespace System.Text {
         // The capacity is adjusted as needed. If value equals String.Empty, this
         // string builder is not changed. 
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringBuilder Insert(int index, String value, int count) {
             if (count < 0) {
                 throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -827,7 +816,7 @@ namespace System.Text {
             if (insertingChars > MaxCapacity - this.Length) {
                 throw new OutOfMemoryException();
             }
-            Contract.Assert(insertingChars + this.Length < Int32.MaxValue);
+            Debug.Assert(insertingChars + this.Length < Int32.MaxValue);
 
             StringBuilder chunk;
             int indexInChunk;
@@ -997,7 +986,6 @@ namespace System.Text {
         }
 
         // Appends all of the characters in value to the current instance.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringBuilder Append(char[] value) {
             Contract.Ensures(Contract.Result<StringBuilder>() != null);
 
@@ -1011,6 +999,88 @@ namespace System.Text {
             return this;
         }
 
+        // Append joined values with a separator between each value.
+        public unsafe StringBuilder AppendJoin<T>(char separator, params T[] values)
+        {
+            // Defer argument validation to the internal function
+            return AppendJoinCore(&separator, 1, values);
+        }
+
+        public unsafe StringBuilder AppendJoin<T>(string separator, params T[] values)
+        {
+            separator = separator ?? string.Empty;
+            fixed (char* pSeparator = separator)
+            {
+                // Defer argument validation to the internal function
+                return AppendJoinCore(pSeparator, separator.Length, values);
+            }
+        }
+
+        public unsafe StringBuilder AppendJoin<T>(char separator, IEnumerable<T> values)
+        {
+            // Defer argument validation to the internal function
+            return AppendJoinCore(&separator, 1, values);
+        }
+
+        public unsafe StringBuilder AppendJoin<T>(string separator, IEnumerable<T> values)
+        {
+            separator = separator ?? string.Empty;
+            fixed (char* pSeparator = separator)
+            {
+                // Defer argument validation to the internal function
+                return AppendJoinCore(pSeparator, separator.Length, values);
+            }
+        }
+
+        private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, params T[] values)
+        {
+            if (values == null)
+                throw new ArgumentNullException(nameof(values));
+            Contract.Ensures(Contract.Result<StringBuilder>() != null);
+
+            if (values.Length == 0)
+                return this;
+
+            var value = values[0];
+            if (value != null)
+                Append(value.ToString());
+
+            for (var i = 1; i < values.Length; i++)
+            {
+                Append(separator, separatorLength);
+                value = values[i];
+                if (value != null)
+                    Append(value.ToString());
+            }
+            return this;
+        }
+
+        private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, IEnumerable<T> values)
+        {
+            if (values == null)
+                throw new ArgumentNullException(nameof(values));
+            Contract.Ensures(Contract.Result<StringBuilder>() != null);
+
+            using (var en = values.GetEnumerator())
+            {
+                if (!en.MoveNext())
+                    return this;
+
+                var value = en.Current;
+                if (value != null)
+                    Append(value.ToString());
+
+                while (en.MoveNext())
+                {
+                    Append(separator, separatorLength);
+                    value = en.Current;
+                    if (value != null)
+                        Append(value.ToString());
+                }
+            }
+            return this;
+        }
+
         /*====================================Insert====================================
         **
         ==============================================================================*/
@@ -1020,7 +1090,6 @@ namespace System.Text {
         // The capacity is adjusted as needed. If value equals String.Empty, the
         // StringBuilder is not changed.
         // 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringBuilder Insert(int index, String value) {
             if ((uint)index > (uint)Length) {
                 throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
@@ -1083,7 +1152,6 @@ namespace System.Text {
         // the buffer at index. Existing characters are shifted to make room for the new text.
         // The capacity is adjusted as needed. If value equals String.Empty, the
         // StringBuilder is not changed.
-        [SecuritySafeCritical]
         public StringBuilder Insert(int index, char value) {
             Contract.Ensures(Contract.Result<StringBuilder>() != null);
 
@@ -1114,7 +1182,6 @@ namespace System.Text {
         // value inserted into the buffer at index.  Existing characters are shifted
         // to make room for the new text and capacity is adjusted as required.  If value is null, the StringBuilder
         // is unchanged.  Characters are taken from value starting at position startIndex.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) {
             Contract.Ensures(Contract.Result<StringBuilder>() != null);
 
@@ -1656,7 +1723,7 @@ namespace System.Text {
 
                     chunk = FindChunkForIndex(index);
                     indexInChunk = index - chunk.m_ChunkOffset;
-                    Contract.Assert(chunk != null || count == 0, "Chunks ended prematurely");
+                    Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely");
                 }
             }
             VerifyClassInvariant();
@@ -1710,7 +1777,6 @@ namespace System.Text {
         /// <summary>
         /// Appends 'value' of length 'count' to the stringBuilder. 
         /// </summary>
-        [SecurityCritical]
         [System.CLSCompliantAttribute(false)]
         public unsafe StringBuilder Append(char* value, int valueCount)
         {
@@ -1747,7 +1813,7 @@ namespace System.Text {
                 // Expand the builder to add another chunk. 
                 int restLength = valueCount - firstLength;
                 ExpandByABlock(restLength);
-                Contract.Assert(m_ChunkLength == 0, "Expand did not make a new block");
+                Debug.Assert(m_ChunkLength == 0, "Expand did not make a new block");
 
                 // Copy the second chunk
                 ThreadSafeCopy(value + firstLength, m_ChunkChars, 0, restLength);
@@ -1760,7 +1826,6 @@ namespace System.Text {
         /// <summary>
         /// Inserts 'value' of length 'cou
         /// </summary>
-        [SecurityCritical]
         unsafe private void Insert(int index, char* value, int valueCount)
         {
             if ((uint)index > (uint)Length)
@@ -1783,7 +1848,6 @@ namespace System.Text {
         /// replacements in bulk (and therefore very efficiently. 
         /// with the string 'value'.  
         /// </summary>
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private void ReplaceAllInChunk(int[] replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value)
         {
             if (replacementsCount <= 0)
@@ -1813,9 +1877,9 @@ namespace System.Text {
                             break;
     
                         int gapEnd = replacements[i];
-                        Contract.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer.  Should not happen");
-                        Contract.Assert(gapStart <= gapEnd, "negative gap size");
-                        Contract.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
+                        Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer.  Should not happen");
+                        Debug.Assert(gapStart <= gapEnd, "negative gap size");
+                        Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
                         if (delta != 0)     // can skip the sliding of gaps if source an target string are the same size.  
                         {
                             // Copy the gap data between the current replacement and the the next replacement
@@ -1825,7 +1889,7 @@ namespace System.Text {
                         else
                         {
                             targetIndexInChunk += gapEnd - gapStart;
-                            Contract.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
+                            Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
                         }
                     }
     
@@ -1870,7 +1934,6 @@ namespace System.Text {
         /// point at the end of the characters just copyied (thus you can splice in strings from multiple 
         /// places by calling this mulitple times.  
         /// </summary>
-        [SecurityCritical]
         unsafe private void ReplaceInPlaceAtChunk(ref StringBuilder chunk, ref int indexInChunk, char* value, int count)
         {
             if (count != 0)
@@ -1878,7 +1941,7 @@ namespace System.Text {
                 for (; ; )
                 {
                     int lengthInChunk = chunk.m_ChunkLength - indexInChunk;
-                    Contract.Assert(lengthInChunk >= 0, "index not in chunk");
+                    Debug.Assert(lengthInChunk >= 0, "index not in chunk");
 
                     int lengthToCopy = Math.Min(lengthInChunk, count);
                     ThreadSafeCopy(value, chunk.m_ChunkChars, indexInChunk, lengthToCopy);
@@ -1903,7 +1966,6 @@ namespace System.Text {
         /// The only way to do this is to copy all interesting variables out of the heap and then do the
         /// bounds check.  This is what we do here.   
         /// </summary>
-        [SecurityCritical]
         unsafe private static void ThreadSafeCopy(char* sourcePtr, char[] destination, int destinationIndex, int count)
         {
             if (count > 0)
@@ -1919,7 +1981,6 @@ namespace System.Text {
                 }
             }
         }
-        [SecurityCritical]
         private static void ThreadSafeCopy(char[] source, int sourceIndex, char[] destination, int destinationIndex, int count)
         {
             if (count > 0)
@@ -1939,7 +2000,6 @@ namespace System.Text {
         }
 
          // Copies the source StringBuilder to the destination IntPtr memory allocated with len bytes.
-        [System.Security.SecurityCritical]  // auto-generated
         internal unsafe void InternalCopy(IntPtr dest, int len) {
             if(len ==0)
                 return;
@@ -1972,13 +2032,13 @@ namespace System.Text {
         /// <returns></returns>
         private StringBuilder FindChunkForIndex(int index)
         {
-            Contract.Assert(0 <= index && index <= Length, "index not in string");
+            Debug.Assert(0 <= index && index <= Length, "index not in string");
 
             StringBuilder ret = this;
             while (ret.m_ChunkOffset > index)
                 ret = ret.m_ChunkPrevious;
 
-            Contract.Assert(ret != null, "index not in string");
+            Debug.Assert(ret != null, "index not in string");
             return ret;
         }
 
@@ -1989,13 +2049,13 @@ namespace System.Text {
         /// <returns></returns>
         private StringBuilder FindChunkForByte(int byteIndex)
         {
-            Contract.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string");
+            Debug.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string");
 
             StringBuilder ret = this;
             while (ret.m_ChunkOffset*sizeof(char) > byteIndex)
                 ret = ret.m_ChunkPrevious;
 
-            Contract.Assert(ret != null, "Byte Index not in string");
+            Debug.Assert(ret != null, "Byte Index not in string");
             return ret;
         }
 
@@ -2078,12 +2138,11 @@ namespace System.Text {
         /// If dontMoveFollowingChars is true, then the room must be made by inserting a chunk BEFORE the
         /// current chunk (this is what it does most of the time anyway)
         /// </summary>
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doneMoveFollowingChars)
         {
             VerifyClassInvariant();
-            Contract.Assert(count > 0, "Count must be strictly positive");
-            Contract.Assert(index >= 0, "Index can't be negative");
+            Debug.Assert(count > 0, "Count must be strictly positive");
+            Debug.Assert(index >= 0, "Index can't be negative");
             if (count + Length > m_MaxCapacity || count + Length < count)
                 throw new ArgumentOutOfRangeException("requiredLength", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
 
@@ -2148,8 +2207,8 @@ namespace System.Text {
         /// </summary>
         private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock)
         {
-            Contract.Assert(size > 0, "size not positive");
-            Contract.Assert(maxCapacity > 0, "maxCapacity not positive");
+            Debug.Assert(size > 0, "size not positive");
+            Debug.Assert(maxCapacity > 0, "maxCapacity not positive");
             m_ChunkChars = new char[size];
             m_MaxCapacity = maxCapacity;
             m_ChunkPrevious = previousBlock;
@@ -2162,11 +2221,10 @@ namespace System.Text {
         /// Removes 'count' characters from the logical index 'startIndex' and returns the chunk and 
         /// index in the chunk of that logical index in the out parameters.  
         /// </summary>
-        [SecuritySafeCritical]
         private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk)
         {
             VerifyClassInvariant();
-            Contract.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string");
+            Debug.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string");
 
             int endIndex = startIndex + count;
 
@@ -2195,7 +2253,7 @@ namespace System.Text {
                 }
                 chunk = chunk.m_ChunkPrevious;
             }
-            Contract.Assert(chunk != null, "fell off beginning of string!");
+            Debug.Assert(chunk != null, "fell off beginning of string!");
 
             int copyTargetIndexInChunk = indexInChunk;
             int copyCount = endChunk.m_ChunkLength - endIndexInChunk;
@@ -2225,7 +2283,7 @@ namespace System.Text {
             if (copyTargetIndexInChunk != endIndexInChunk)  // Sometimes no move is necessary
                 ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount);
 
-            Contract.Assert(chunk != null, "fell off beginning of string!");
+            Debug.Assert(chunk != null, "fell off beginning of string!");
             VerifyClassInvariant();
         }
     }
index 8ee41a3..bbfa180 100644 (file)
@@ -12,6 +12,7 @@ namespace System.Text
     using System;
     using System.Runtime.Serialization;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     /*=================================SurrogateEncoder==================================
@@ -38,7 +39,6 @@ namespace System.Text
         }
 
         // Just get it from GetEncoding
-        [System.Security.SecurityCritical]  // auto-generated
         public Object GetRealObject(StreamingContext context)
         {
             // Need to get our Encoding's Encoder
@@ -46,11 +46,10 @@ namespace System.Text
         }
 
         // ISerializable implementation
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             // We cannot ever call this.
-            Contract.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData");
+            Debug.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData");
             throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
         }
     }
index 6973bb7..a7ac1d8 100644 (file)
@@ -10,6 +10,7 @@ namespace System.Text
 {
 
     using System;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Globalization;
     // Encodes text into and out of UTF-32.  UTF-32 is a way of writing
@@ -109,7 +110,6 @@ namespace System.Text
             return EncodingForwarder.GetByteCount(this, s);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         public override unsafe int GetByteCount(char* chars, int count)
         {
@@ -137,7 +137,6 @@ namespace System.Text
             return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
         {
@@ -152,7 +151,6 @@ namespace System.Text
             return EncodingForwarder.GetCharCount(this, bytes, index, count);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         public override unsafe int GetCharCount(byte* bytes, int count)
         {
@@ -165,7 +163,6 @@ namespace System.Text
             return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
         {
@@ -182,11 +179,10 @@ namespace System.Text
         
         // End of overridden methods which use EncodingForwarder
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS encoder)
         {
-            Contract.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null");
-            Contract.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0");
+            Debug.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null");
+            Debug.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0");
 
             char* end = chars + count;
             char* charStart = chars;
@@ -248,7 +244,7 @@ namespace System.Text
 
                     // We are missing our low surrogate, decrement chars and fallback the high surrogate
                     // The high surrogate may have come from the encoder, but nothing else did.
-                    Contract.Assert(chars > charStart, 
+                    Debug.Assert(chars > charStart, 
                         "[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
                     chars--;
 
@@ -301,21 +297,20 @@ namespace System.Text
 
             // Shouldn't have anything in fallback buffer for GetByteCount
             // (don't have to check m_throwOnOverflow for count)
-            Contract.Assert(fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer.Remaining == 0,
                 "[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
 
             // Return our count
             return byteCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char *chars, int charCount,
                                                  byte* bytes, int byteCount, EncoderNLS encoder)
         {
-            Contract.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null");
-            Contract.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null");
-            Contract.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0");
-            Contract.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0");
+            Debug.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null");
+            Debug.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null");
+            Debug.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0");
+            Debug.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0");
 
             char* charStart = chars;
             char* charEnd = chars + charCount;
@@ -384,7 +379,7 @@ namespace System.Text
                             {
                                 // If we don't have enough room, then either we should've advanced a while
                                 // or we should have bytes==byteStart and throw below
-                                Contract.Assert(chars > charStart + 1 || bytes == byteStart, 
+                                Debug.Assert(chars > charStart + 1 || bytes == byteStart, 
                                     "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
                                 chars-=2;                                       // Aren't using those 2 chars
                             }
@@ -412,7 +407,7 @@ namespace System.Text
 
                     // We are missing our low surrogate, decrement chars and fallback the high surrogate
                     // The high surrogate may have come from the encoder, but nothing else did.
-                    Contract.Assert(chars > charStart, 
+                    Debug.Assert(chars > charStart, 
                         "[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
                     chars--;
 
@@ -453,7 +448,7 @@ namespace System.Text
                     else
                     {
                         // Must've advanced already
-                        Contract.Assert(chars > charStart,
+                        Debug.Assert(chars > charStart,
                             "[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
                         chars--;                                        // Aren't using this char
                     }
@@ -487,7 +482,7 @@ namespace System.Text
             }
 
             // Fix our encoder if we have one
-            Contract.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
+            Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
                 "[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
 
             if (encoder != null)
@@ -503,11 +498,10 @@ namespace System.Text
             return (int)(bytes - byteStart);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
         {
-            Contract.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null");
-            Contract.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0");
+            Debug.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null");
+            Debug.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0");
 
             UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
 
@@ -532,7 +526,7 @@ namespace System.Text
 
                 // Shouldn't have anything in fallback buffer for GetCharCount
                 // (don't have to check m_throwOnOverflow for chars or count)
-                Contract.Assert(fallbackBuffer.Remaining == 0,
+                Debug.Assert(fallbackBuffer.Remaining == 0,
                     "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
             }
             else
@@ -639,21 +633,20 @@ namespace System.Text
 
             // Shouldn't have anything in fallback buffer for GetCharCount
             // (don't have to check m_throwOnOverflow for chars or count)
-            Contract.Assert(fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer.Remaining == 0,
                 "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
 
             // Return our count
             return charCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS baseDecoder)
         {
-            Contract.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null");
-            Contract.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null");
-            Contract.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0");
-            Contract.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0");
+            Debug.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null");
+            Debug.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null");
+            Debug.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0");
+            Debug.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0");
 
             UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
 
@@ -680,7 +673,7 @@ namespace System.Text
 
                 // Shouldn't have anything in fallback buffer for GetChars
                 // (don't have to check m_throwOnOverflow for chars)
-                Contract.Assert(fallbackBuffer.Remaining == 0,
+                Debug.Assert(fallbackBuffer.Remaining == 0,
                     "[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
             }
             else
@@ -741,7 +734,7 @@ namespace System.Text
                         // Couldn't fallback, throw or wait til next time
                         // We either read enough bytes for bytes-=4 to work, or we're
                         // going to throw in ThrowCharsOverflow because chars == charStart
-                        Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
+                        Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
                             "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
                         bytes-=4;                                       // get back to where we were
                         iChar=0;                                        // Remembering nothing
@@ -765,7 +758,7 @@ namespace System.Text
                         // Throwing or stopping
                         // We either read enough bytes for bytes-=4 to work, or we're
                         // going to throw in ThrowCharsOverflow because chars == charStart
-                        Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
+                        Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
                             "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
                         bytes-=4;                                       // get back to where we were
                         iChar=0;                                        // Remembering nothing
@@ -782,7 +775,7 @@ namespace System.Text
                     // Throwing or stopping
                     // We either read enough bytes for bytes-=4 to work, or we're
                     // going to throw in ThrowCharsOverflow because chars == charStart
-                    Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
+                    Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
                         "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
                     bytes-=4;                                       // get back to where we were
                     iChar=0;                                        // Remembering nothing                    
@@ -846,7 +839,7 @@ namespace System.Text
 
             // Shouldn't have anything in fallback buffer for GetChars
             // (don't have to check m_throwOnOverflow for chars)
-            Contract.Assert(fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer.Remaining == 0,
                 "[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
 
             // Return our count
index 3270ca6..624ca73 100644 (file)
@@ -11,6 +11,7 @@ namespace System.Text
     using System;
     using System.Runtime.Serialization;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
 
@@ -175,7 +176,6 @@ namespace System.Text
             return EncodingForwarder.GetByteCount(this, s);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetByteCount(char* chars, int count)
@@ -205,7 +205,6 @@ namespace System.Text
             return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
@@ -221,7 +220,6 @@ namespace System.Text
             return EncodingForwarder.GetCharCount(this, bytes, index, count);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetCharCount(byte* bytes, int count)
@@ -235,7 +233,6 @@ namespace System.Text
             return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
@@ -254,23 +251,21 @@ namespace System.Text
         
         // End of overridden methods which use EncodingForwarder
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
         {
-            Contract.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null");
-            Contract.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0");
+            Debug.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null");
+            Debug.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0");
 
             // Just call GetBytes with bytes == null
             return GetBytes(chars, count, null, 0, baseEncoder);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS baseEncoder)
         {
-            Contract.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0");
-            Contract.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null");
-            Contract.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0");
+            Debug.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0");
+            Debug.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null");
+            Debug.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0");
 
             // Get encoder info
             UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder;
@@ -405,23 +400,21 @@ namespace System.Text
             return buffer.Count;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
         {
-            Contract.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0");
-            Contract.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null");
+            Debug.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0");
+            Debug.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null");
 
             // Just call GetChars with null char* to do counting
             return GetChars(bytes, count, null, 0, baseDecoder);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS baseDecoder)
         {
-            Contract.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0");
-            Contract.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null");
-            Contract.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0");
+            Debug.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0");
+            Debug.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null");
+            Debug.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0");
 
             // Might use a decoder
             UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder) baseDecoder;
@@ -440,7 +433,7 @@ namespace System.Text
                 bitCount = decoder.bitCount;
                 firstByte = decoder.firstByte;
 
-                Contract.Assert(firstByte == false || decoder.bitCount <= 0,
+                Debug.Assert(firstByte == false || decoder.bitCount <= 0,
                     "[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set");
             }
 
@@ -674,7 +667,6 @@ namespace System.Text
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // Any info?
@@ -737,7 +729,6 @@ namespace System.Text
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // Any info?
@@ -825,8 +816,8 @@ namespace System.Text
             public override bool Fallback(byte[] bytesUnknown, int index)
             {
                 // We expect no previous fallback in our buffer
-                Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks");
-                Contract.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte");
+                Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks");
+                Debug.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte");
 
                 // Go ahead and get our fallback
                 cFallback = (char)bytesUnknown[0];
@@ -872,7 +863,6 @@ namespace System.Text
             }
 
             // Clear the buffer
-            [System.Security.SecuritySafeCritical] // overrides public transparent member
             public override unsafe void Reset()
             {
                 iCount = -1;
@@ -880,13 +870,12 @@ namespace System.Text
             }
 
             // This version just counts the fallback and doesn't actually copy anything.
-            [System.Security.SecurityCritical]  // auto-generated
             internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
             // Right now this has both bytes and bytes[], since we might have extra bytes, hence the
             // array, and we might need the index, hence the byte*
             {
                 // We expect no previous fallback in our buffer
-                Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks");
+                Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks");
                 if (bytes.Length != 1)
                 {
                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
index ddf8017..ba19649 100644 (file)
@@ -21,6 +21,7 @@ namespace System.Text
     using System.Globalization;
     using System.Runtime.Serialization;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // Encodes text into and out of UTF-8.  UTF-8 is a way of writing
@@ -129,7 +130,6 @@ namespace System.Text
             return EncodingForwarder.GetByteCount(this, chars);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetByteCount(char* chars, int count)
@@ -158,7 +158,6 @@ namespace System.Text
             return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
@@ -174,7 +173,6 @@ namespace System.Text
             return EncodingForwarder.GetCharCount(this, bytes, index, count);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetCharCount(byte* bytes, int count)
@@ -188,7 +186,6 @@ namespace System.Text
             return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
@@ -209,7 +206,6 @@ namespace System.Text
 
         // To simplify maintenance, the structure of GetByteCount and GetBytes should be
         // kept the same as much as possible
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS baseEncoder)
         {
             // For fallback we may need a fallback buffer.
@@ -254,7 +250,7 @@ namespace System.Text
                     } else {
                         // Case of surrogates in the fallback.
                         if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
-                            Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+                            Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
                                 "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
                             
                             ch = fallbackBuffer.InternalGetNextChar();
@@ -286,7 +282,7 @@ namespace System.Text
                 }
 
                 if (ch > 0) {
-                    Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+                    Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
                         "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
 
                     // use separate helper variables for local contexts so that the jit optimizations
@@ -557,7 +553,7 @@ namespace System.Text
             }
 #endif
 
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[UTF8Encoding.GetByteCount]Expected Empty fallback buffer");
 
             return byteCount;
@@ -566,14 +562,12 @@ namespace System.Text
         // diffs two char pointers using unsigned arithmetic. The unsigned arithmetic
         // is good enough for us, and it tends to generate better code than the signed
         // arithmetic generated by default
-        [System.Security.SecurityCritical]  // auto-generated
         unsafe private static int PtrDiff(char *a, char* b)
         {
             return (int)(((uint)((byte*)a - (byte*)b)) >> 1);
         }
 
         // byte* flavor just for parity
-        [System.Security.SecurityCritical]  // auto-generated
         unsafe private static int PtrDiff(byte* a, byte* b)
         {
             return (int)(a - b);
@@ -586,14 +580,13 @@ namespace System.Text
 
         // Our workhorse
         // Note:  We ignore mismatched surrogates, unless the exception flag is set in which case we throw
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS baseEncoder)
         {
-            Contract.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null");
-            Contract.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0");
-            Contract.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0");
-            Contract.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null");
+            Debug.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null");
+            Debug.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0");
+            Debug.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0");
+            Debug.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null");
 
             UTF8Encoder encoder = null;
 
@@ -642,7 +635,7 @@ namespace System.Text
                     } else {
                         // Case of leftover surrogates in the fallback buffer
                         if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
-                            Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+                            Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
                                 "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
                             
                             int cha = ch;
@@ -670,7 +663,7 @@ namespace System.Text
 
                 if (ch > 0) {
                     // We have a high surrogate left over from a previous loop.
-                    Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+                    Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
                         "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
 
                     // use separate helper variables for local contexts so that the jit optimizations
@@ -767,7 +760,7 @@ namespace System.Text
                         if (ch > 0xFFFF)
                             pSrc--;                                 // Was surrogate, didn't use 2nd part either
                     }
-                    Contract.Assert(pSrc >= chars || pTarget == bytes,
+                    Debug.Assert(pSrc >= chars || pTarget == bytes,
                         "[UTF8Encoding.GetBytes]Expected pSrc to be within buffer or to throw with insufficient room.");
                     ThrowBytesOverflow(encoder, pTarget == bytes);  // Throw if we must
                     ch = 0;                                         // Nothing left over (we backed up to start of pair if supplimentary)
@@ -989,7 +982,7 @@ namespace System.Text
                     pTarget++;
                 }
 
-                Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd");
+                Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd");
 
 #endif // FASTLOOP
 
@@ -1000,14 +993,14 @@ namespace System.Text
             // Do we have to set the encoder bytes?
             if (encoder != null)
             {
-                Contract.Assert(!encoder.MustFlush || ch == 0,
+                Debug.Assert(!encoder.MustFlush || ch == 0,
                     "[UTF8Encoding.GetBytes] Expected no mustflush or 0 leftover ch " + ch.ToString("X2", CultureInfo.InvariantCulture));
 
                 encoder.surrogateChar = ch;
                 encoder.m_charsUsed = (int)(pSrc - chars);
             }
 
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
                 baseEncoder == null || !baseEncoder.m_throwOnOverflow,
                 "[UTF8Encoding.GetBytes]Expected empty fallback buffer if not converting");
 
@@ -1029,11 +1022,10 @@ namespace System.Text
         //
         // To simplify maintenance, the structure of GetCharCount and GetChars should be
         // kept the same as much as possible
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
         {
-            Contract.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0");
-            Contract.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null");
+            Debug.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0");
+            Debug.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null");
 
             // Initialize stuff
             byte *pSrc = bytes;
@@ -1052,7 +1044,7 @@ namespace System.Text
 
                 // Shouldn't have anything in fallback buffer for GetCharCount
                 // (don't have to check m_throwOnOverflow for count)
-                Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+                Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
                     "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at start");
             }
 
@@ -1087,7 +1079,7 @@ namespace System.Text
                 ch = (ch << 6) | (cha & 0x3F);
 
                 if ((ch & FinalByte) == 0) {
-                    Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
+                    Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
                         "[UTF8Encoding.GetChars]Invariant volation");
 
                     if ((ch & SupplimentarySeq) != 0) {
@@ -1408,7 +1400,7 @@ namespace System.Text
 
             // Shouldn't have anything in fallback buffer for GetCharCount
             // (don't have to check m_throwOnOverflow for count)
-            Contract.Assert(fallback == null || fallback.Remaining == 0,
+            Debug.Assert(fallback == null || fallback.Remaining == 0,
                 "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at end");
 
             return charCount;
@@ -1424,14 +1416,13 @@ namespace System.Text
         //
         // To simplify maintenance, the structure of GetCharCount and GetChars should be
         // kept the same as much as possible
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS baseDecoder)
         {
-            Contract.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null");
-            Contract.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0");
-            Contract.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0");
-            Contract.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null");
+            Debug.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null");
+            Debug.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0");
+            Debug.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0");
+            Debug.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null");
 
             byte *pSrc = bytes;
             char *pTarget = chars;
@@ -1448,7 +1439,7 @@ namespace System.Text
 
                 // Shouldn't have anything in fallback buffer for GetChars
                 // (don't have to check m_throwOnOverflow for chars, we always use all or none so always should be empty)
-                Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+                Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
                     "[UTF8Encoding.GetChars]Expected empty fallback buffer at start");
             }
 
@@ -1483,7 +1474,7 @@ namespace System.Text
 
                 if ((ch & FinalByte) == 0) {
                     // Not at last byte yet
-                    Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
+                    Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
                         "[UTF8Encoding.GetChars]Invariant volation");
 
                     if ((ch & SupplimentarySeq) != 0) {
@@ -1546,14 +1537,14 @@ namespace System.Text
                 {
                     // Ran out of buffer space
                     // Need to throw an exception?
-                    Contract.Assert(pSrc >= bytes || pTarget == chars,
+                    Debug.Assert(pSrc >= bytes || pTarget == chars,
                         "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer after fallback");
                     fallback.InternalReset();
                     ThrowCharsOverflow(baseDecoder, pTarget == chars);
                     ch = 0;
                     break;
                 }
-                Contract.Assert(pSrc >= bytes, 
+                Debug.Assert(pSrc >= bytes, 
                     "[UTF8Encoding.GetChars]Expected invalid byte sequence to have remained within the byte array");
                 ch = 0;
                 continue;
@@ -1639,7 +1630,7 @@ namespace System.Text
 
                     // Throw that we don't have enough room (pSrc could be < chars if we had started to process
                     // a 4 byte sequence alredy)
-                    Contract.Assert(pSrc >= bytes || pTarget == chars,
+                    Debug.Assert(pSrc >= bytes || pTarget == chars,
                         "[UTF8Encoding.GetChars]Expected pSrc to be within input buffer or throw due to no output]");
                     ThrowCharsOverflow(baseDecoder, pTarget == chars);
 
@@ -1893,7 +1884,7 @@ namespace System.Text
                 }
 #endif // FASTLOOP
 
-                Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd");
+                Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd");
 
                 // no pending bits at this point
                 ch = 0;
@@ -1920,7 +1911,7 @@ namespace System.Text
                 // This'll back us up the appropriate # of bytes if we didn't get anywhere
                 if (!FallbackInvalidByteSequence(ref pSrc, ch, fallback, ref pTarget))
                 {
-                    Contract.Assert(pSrc >= bytes || pTarget == chars,
+                    Debug.Assert(pSrc >= bytes || pTarget == chars,
                         "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer while flushing");
 
                     // Ran out of buffer space
@@ -1928,7 +1919,7 @@ namespace System.Text
                     fallback.InternalReset();
                     ThrowCharsOverflow(baseDecoder, pTarget == chars);
                 }
-                Contract.Assert(pSrc >= bytes, 
+                Debug.Assert(pSrc >= bytes, 
                     "[UTF8Encoding.GetChars]Expected flushing invalid byte sequence to have remained within the byte array");                
                 ch = 0;
             }
@@ -1939,7 +1930,7 @@ namespace System.Text
 
                 // If we're storing flush data we expect all bits to be used or else
                 // we're stuck in the middle of a conversion
-                Contract.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow,
+                Debug.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow,
                     "[UTF8Encoding.GetChars]Expected no must flush or no left over bits or no throw on overflow.");
 
                 // Remember our leftover bits.
@@ -1950,7 +1941,7 @@ namespace System.Text
 
             // Shouldn't have anything in fallback buffer for GetChars
             // (don't have to check m_throwOnOverflow for chars)
-            Contract.Assert(fallback == null || fallback.Remaining == 0,
+            Debug.Assert(fallback == null || fallback.Remaining == 0,
                 "[UTF8Encoding.GetChars]Expected empty fallback buffer at end");
 
             return PtrDiff(pTarget, chars);
@@ -1959,7 +1950,6 @@ namespace System.Text
         // During GetChars we had an invalid byte sequence
         // pSrc is backed up to the start of the bad sequence if we didn't have room to
         // fall it back.  Otherwise pSrc remains wher it is.
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe bool FallbackInvalidByteSequence(
             ref byte* pSrc, int ch, DecoderFallbackBuffer fallback, ref char* pTarget)
         {
@@ -1982,7 +1972,6 @@ namespace System.Text
         // During GetCharCount we had an invalid byte sequence
         // pSrc is used to find the index that points to the invalid bytes,
         // however the byte[] contains the fallback bytes (in case the index is -1)
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe int FallbackInvalidByteSequence(
             byte* pSrc, int ch, DecoderFallbackBuffer fallback)
         {
@@ -2001,7 +1990,6 @@ namespace System.Text
         // Note that some of these bytes may have come from a previous fallback, so we cannot
         // just decrement the pointer and use the values we read.  In those cases we have 
         // to regenerate the original values.
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe byte[] GetBytesUnknown(ref byte* pSrc, int ch)
         {
             // Get our byte[]
@@ -2194,7 +2182,6 @@ namespace System.Text
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // Any info?
@@ -2268,7 +2255,6 @@ namespace System.Text
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // Any info?
index 4cb1d24..25255c3 100644 (file)
@@ -12,6 +12,7 @@ namespace System.Text
     using System.Globalization;
     using System.Runtime.Serialization;
     using System.Security.Permissions;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
 
@@ -109,7 +110,6 @@ namespace System.Text
             return EncodingForwarder.GetByteCount(this, s);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetByteCount(char* chars, int count)
@@ -138,7 +138,6 @@ namespace System.Text
             return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
@@ -154,7 +153,6 @@ namespace System.Text
             return EncodingForwarder.GetCharCount(this, bytes, index, count);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public override unsafe int GetCharCount(byte* bytes, int count)
@@ -168,7 +166,6 @@ namespace System.Text
             return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.InteropServices.ComVisible(false)]
         public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
@@ -187,11 +184,10 @@ namespace System.Text
         
         // End of overridden methods which use EncodingForwarder
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
         {
-            Contract.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null");
-            Contract.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0");
+            Debug.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null");
+            Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0");
 
             // Start by assuming each char gets 2 bytes
             int byteCount = count << 1;
@@ -340,7 +336,7 @@ namespace System.Text
                             // Unwind the current character, this should be safe because we
                             // don't have leftover data in the fallback, so chars must have
                             // advanced already.
-                            Contract.Assert(chars > charStart, 
+                            Debug.Assert(chars > charStart, 
                                 "[UnicodeEncoding.GetByteCount]Expected chars to have advanced in unexpected high surrogate");
                             chars--;
 
@@ -407,7 +403,7 @@ namespace System.Text
                     // Rewind the current character, fallback previous character.
                     // this should be safe because we don't have leftover data in the
                     // fallback, so chars must have advanced already.
-                    Contract.Assert(chars > charStart, 
+                    Debug.Assert(chars > charStart, 
                         "[UnicodeEncoding.GetByteCount]Expected chars to have advanced when expected low surrogate");
                     chars--;
 
@@ -473,21 +469,20 @@ namespace System.Text
 
             // Shouldn't have anything in fallback buffer for GetByteCount
             // (don't have to check m_throwOnOverflow for count)
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end");
 
             // Don't remember fallbackBuffer.encoder for counting
             return byteCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetBytes(char* chars, int charCount,
                                                 byte* bytes, int byteCount, EncoderNLS encoder)
         {
-            Contract.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null");
-            Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0");
-            Contract.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0");
-            Contract.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null");
+            Debug.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null");
+            Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0");
+            Debug.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0");
+            Debug.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null");
 
             char charLeftOver = (char)0;
             char ch;
@@ -691,7 +686,7 @@ namespace System.Text
                             // Unwind the current character, this should be safe because we
                             // don't have leftover data in the fallback, so chars must have
                             // advanced already.
-                            Contract.Assert(chars > charStart, 
+                            Debug.Assert(chars > charStart, 
                                 "[UnicodeEncoding.GetBytes]Expected chars to have advanced in unexpected high surrogate");
                             chars--;
                             
@@ -757,7 +752,7 @@ namespace System.Text
                         {
                             // If we don't have enough room, then either we should've advanced a while
                             // or we should have bytes==byteStart and throw below
-                            Contract.Assert(chars > charStart + 1 || bytes == byteStart, 
+                            Debug.Assert(chars > charStart + 1 || bytes == byteStart, 
                                 "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
                             chars-=2;                                        // Didn't use either surrogate
                         }
@@ -786,7 +781,7 @@ namespace System.Text
                     // Rewind the current character, fallback previous character.
                     // this should be safe because we don't have leftover data in the
                     // fallback, so chars must have advanced already.
-                    Contract.Assert(chars > charStart, 
+                    Debug.Assert(chars > charStart, 
                         "[UnicodeEncoding.GetBytes]Expected chars to have advanced after expecting low surrogate");
                     chars--;
 
@@ -820,7 +815,7 @@ namespace System.Text
                     {
                         // Lonely charLeftOver (from previous call) would've been caught up above,
                         // so this must be a case where we've already read an input char.
-                        Contract.Assert(chars > charStart, 
+                        Debug.Assert(chars > charStart, 
                             "[UnicodeEncoding.GetBytes]Expected chars to have advanced for failed fallback");                        
                         chars--;                                         // Not using this char
                     }
@@ -888,10 +883,10 @@ namespace System.Text
 
             // Remember charLeftOver if we must, or clear it if we're flushing
             // (charLeftOver should be 0 if we're flushing)
-            Contract.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0,
+            Debug.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0,
                 "[UnicodeEncoding.GetBytes] Expected no left over characters if flushing");
 
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
                 encoder == null || !encoder.m_throwOnOverflow,
                 "[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting");
 
@@ -901,11 +896,10 @@ namespace System.Text
             return (int)(bytes - byteStart);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
         {
-            Contract.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null");
-            Contract.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0");
+            Debug.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null");
+            Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0");
 
             UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder;
 
@@ -944,7 +938,7 @@ namespace System.Text
 
                 // Shouldn't have anything in fallback buffer for GetCharCount
                 // (don't have to check m_throwOnOverflow for count)
-                Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+                Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
                     "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at start");
             }
 
@@ -1234,20 +1228,19 @@ namespace System.Text
 
             // Shouldn't have anything in fallback buffer for GetCharCount
             // (don't have to check m_throwOnOverflow for count)
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at end");
 
             return charCount;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal override unsafe int GetChars(byte* bytes, int byteCount,
                                                 char* chars, int charCount, DecoderNLS baseDecoder )
         {
-            Contract.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null");
-            Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0");
-            Contract.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0");
-            Contract.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null");
+            Debug.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null");
+            Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0");
+            Debug.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0");
+            Debug.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null");
 
             UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder;
 
@@ -1263,7 +1256,7 @@ namespace System.Text
 
                 // Shouldn't have anything in fallback buffer for GetChars
                 // (don't have to check m_throwOnOverflow for chars)
-                Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+                Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
                     "[UnicodeEncoding.GetChars]Expected empty fallback buffer at start");
             }
 
@@ -1421,7 +1414,7 @@ namespace System.Text
                             {
                                 // couldn't fall back lonely surrogate
                                 // We either advanced bytes or chars should == charStart and throw below
-                                Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+                                Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
                                     "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (bad surrogate)");
                                 bytes-=2;                                       // didn't use these 2 bytes
                                 fallbackBuffer.InternalReset();
@@ -1470,7 +1463,7 @@ namespace System.Text
                         {
                             // couldn't fall back lonely surrogate
                             // We either advanced bytes or chars should == charStart and throw below
-                            Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+                            Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
                                 "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (lonely surrogate)");
                             bytes-=2;                                       // didn't use these 2 bytes
                             fallbackBuffer.InternalReset();
@@ -1487,7 +1480,7 @@ namespace System.Text
                     {
                         // couldn't find room for this surrogate pair
                         // We either advanced bytes or chars should == charStart and throw below
-                        Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+                        Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
                             "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (surrogate pair)");
                         bytes-=2;                                       // didn't use these 2 bytes
                         ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
@@ -1529,7 +1522,7 @@ namespace System.Text
                     {
                         // couldn't fall back high surrogate, or char that would be next
                         // We either advanced bytes or chars should == charStart and throw below
-                        Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+                        Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
                             "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (no low surrogate)");
                         bytes-=2;                                       // didn't use these 2 bytes
                         fallbackBuffer.InternalReset();
@@ -1546,7 +1539,7 @@ namespace System.Text
                 {
                     // 2 bytes couldn't fall back
                     // We either advanced bytes or chars should == charStart and throw below
-                    Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+                    Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
                         "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (normal)");
                     bytes-=2;                                       // didn't use these bytes
                     ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
@@ -1591,7 +1584,7 @@ namespace System.Text
                     {
                         // 2 bytes couldn't fall back
                         // We either advanced bytes or chars should == charStart and throw below
-                        Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+                        Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
                             "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (decoder)");
                         bytes-=2;                                       // didn't use these bytes
                         if (lastByte >= 0)
@@ -1644,7 +1637,7 @@ namespace System.Text
             // Remember our decoder if we must
             if (decoder != null)
             {
-                Contract.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)),
+                Debug.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)),
                     "[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing"
 //                    + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2")
                     );
@@ -1659,7 +1652,7 @@ namespace System.Text
 
             // Shouldn't have anything in fallback buffer for GetChars
             // (don't have to check m_throwOnOverflow for count or chars)
-            Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+            Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
                 "[UnicodeEncoding.GetChars]Expected empty fallback buffer at end");
 
             return (int)(chars - charStart);
@@ -1803,7 +1796,6 @@ namespace System.Text
             }
 
             // ISerializable implementation, get data for this object
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 // Any info?
index bbfb203..6ed1545 100644 (file)
@@ -4,6 +4,7 @@
 
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Security;
 
@@ -40,7 +41,6 @@ namespace System.Threading
     //
     public sealed class AsyncLocal<T> : IAsyncLocal
     {
-        [SecurityCritical] // critical because this action will terminate the process if it throws.
         private readonly Action<AsyncLocalValueChangedArgs<T>> m_valueChangedHandler;
 
         //
@@ -54,7 +54,6 @@ namespace System.Threading
         // Constructs an AsyncLocal<T> with a delegate that is called whenever the current value changes
         // on any thread.
         //
-        [SecurityCritical]
         public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler) 
         {
             m_valueChangedHandler = valueChangedHandler;
@@ -62,23 +61,20 @@ namespace System.Threading
 
         public T Value
         {
-            [SecuritySafeCritical]
             get 
             { 
                 object obj = ExecutionContext.GetLocalValue(this);
                 return (obj == null) ? default(T) : (T)obj;
             }
-            [SecuritySafeCritical]
             set 
             {
                 ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null); 
             }
         }
 
-        [SecurityCritical]
         void IAsyncLocal.OnValueChanged(object previousValueObj, object currentValueObj, bool contextChanged)
         {
-            Contract.Assert(m_valueChangedHandler != null);
+            Debug.Assert(m_valueChangedHandler != null);
             T previousValue = previousValueObj == null ? default(T) : (T)previousValueObj;
             T currentValue = currentValueObj == null ? default(T) : (T)currentValueObj;
             m_valueChangedHandler(new AsyncLocalValueChangedArgs<T>(previousValue, currentValue, contextChanged));
@@ -90,7 +86,6 @@ namespace System.Threading
     //
     internal interface IAsyncLocal
     {
-        [SecurityCritical]
         void OnValueChanged(object previousValue, object currentValue, bool contextChanged);
     }
 
@@ -467,7 +462,7 @@ namespace System.Threading
                                 multi.UnsafeStore(index++, pair.Key, pair.Value);
                             }
                         }
-                        Contract.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
+                        Debug.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
                         return multi;
                     }
                     else
@@ -480,7 +475,7 @@ namespace System.Threading
                                 map[pair.Key] = pair.Value;
                             }
                         }
-                        Contract.Assert(map.Count == count - 1);
+                        Debug.Assert(map.Count == count - 1);
                         return map;
                     }
                 }
index 6fe6c06..78a6fa1 100644 (file)
@@ -17,7 +17,6 @@ namespace System.Threading {
     using System.Security.Permissions;
     using System.Runtime.InteropServices;
 
-    [HostProtection(Synchronization=true, ExternalThreading=true)]
     [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class AutoResetEvent : EventWaitHandle
     {
index 7f744f8..5b78f20 100644 (file)
@@ -8,9 +8,9 @@
 #pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS.
 
 using System;
-using System.Diagnostics;
 using System.Runtime.InteropServices;
 using System.Security.Permissions;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime;
 using System.Runtime.CompilerServices;
@@ -39,7 +39,6 @@ namespace System.Threading
     /// </para>
     /// </remarks>
     [ComVisible(false)]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     [DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")]
     public struct CancellationToken
     {
@@ -167,7 +166,7 @@ namespace System.Threading
         private static void ActionToActionObjShunt(object obj)
         {
             Action action = obj as Action;
-            Contract.Assert(action != null, "Expected an Action here");
+            Debug.Assert(action != null, "Expected an Action here");
             action();
         }
 
@@ -318,7 +317,6 @@ namespace System.Threading
         }
 
         // the real work..
-        [SecuritySafeCritical]
         [MethodImpl(MethodImplOptions.NoInlining)]
         private CancellationTokenRegistration Register(Action<Object> callback, Object state, bool useSynchronizationContext, bool useExecutionContext)
         {
index 34e0bb0..ac27fe3 100644 (file)
@@ -17,7 +17,6 @@ namespace System.Threading
     /// <remarks>
     /// To unregister a callback, dispose the corresponding Registration instance.
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public struct CancellationTokenRegistration : IEquatable<CancellationTokenRegistration>, IDisposable
     {
         private readonly CancellationCallbackInfo m_callbackInfo;
index 961c808..fe9e0de 100644 (file)
@@ -11,6 +11,7 @@ using System.Security;
 using System.Collections.Generic;
 using System.Runtime.InteropServices;
 using System.Security.Permissions;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime;
 
@@ -35,7 +36,6 @@ namespace System.Threading
     /// </para>
     /// </remarks>
     [ComVisible(false)]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
 
     public class CancellationTokenSource : IDisposable
     {
@@ -629,7 +629,7 @@ namespace System.Threading
             }
 
             // the CancellationToken has already checked that the token is cancelable before calling this method.
-            Contract.Assert(CanBeCanceled, "Cannot register for uncancelable token src");
+            Debug.Assert(CanBeCanceled, "Cannot register for uncancelable token src");
 
             // if not canceled, register the event handlers
             // if canceled already, run the callback synchronously
@@ -730,7 +730,7 @@ namespace System.Threading
                 // - After transition, no more delegates will be added to the 
                 // - list of handlers, and hence it can be consumed and cleared at leisure by ExecuteCallbackHandlers.
                 ExecuteCallbackHandlers(throwOnFirstException);
-                Contract.Assert(IsCancellationCompleted, "Expected cancellation to have finished");
+                Debug.Assert(IsCancellationCompleted, "Expected cancellation to have finished");
             }
         }
 
@@ -742,8 +742,8 @@ namespace System.Threading
         /// </remarks>
         private void ExecuteCallbackHandlers(bool throwOnFirstException)
         {
-            Contract.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true");
-            Contract.Assert(ThreadIDExecutingCallbacks != -1, "ThreadIDExecutingCallbacks should have been set.");
+            Debug.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true");
+            Debug.Assert(ThreadIDExecutingCallbacks != -1, "ThreadIDExecutingCallbacks should have been set.");
 
             // Design decision: call the delegates in LIFO order so that callbacks fire 'deepest first'.
             // This is intended to help with nesting scenarios so that child enlisters cancel before their parents.
@@ -791,7 +791,7 @@ namespace System.Threading
                                         var wsc = m_executingCallback as CancellationCallbackInfo.WithSyncContext;
                                         if (wsc != null)
                                         {
-                                            Contract.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx");
+                                            Debug.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx");
                                             wsc.TargetSyncContext.Send(CancellationCallbackCoreWork_OnSyncContext, args);
                                             // CancellationCallbackCoreWork_OnSyncContext may have altered ThreadIDExecutingCallbacks, so reset it. 
                                             ThreadIDExecutingCallbacks = Thread.CurrentThread.ManagedThreadId;
@@ -828,7 +828,7 @@ namespace System.Threading
 
             if (exceptionList != null)
             {
-                Contract.Assert(exceptionList.Count > 0, "Expected exception count > 0");
+                Debug.Assert(exceptionList.Count > 0, "Expected exception count > 0");
                 throw new AggregateException(exceptionList);
             }
         }
@@ -1029,14 +1029,12 @@ namespace System.Threading
         }
 
         // Cached callback delegate that's lazily initialized due to ContextCallback being SecurityCritical
-        [SecurityCritical]
         private static ContextCallback s_executionContextCallback;
 
         /// <summary>
         /// InternalExecuteCallbackSynchronously_GeneralPath
         /// This will be called on the target synchronization context, however, we still need to restore the required execution context
         /// </summary>
-        [SecuritySafeCritical]
         internal void ExecuteCallback()
         {
             if (TargetExecutionContext != null)
@@ -1059,11 +1057,10 @@ namespace System.Threading
 
         // the worker method to actually run the callback
         // The signature is such that it can be used as a 'ContextCallback'
-        [SecurityCritical]
         private static void ExecutionContextCallback(object obj)
         {
             CancellationCallbackInfo callbackInfo = obj as CancellationCallbackInfo;
-            Contract.Assert(callbackInfo != null);
+            Debug.Assert(callbackInfo != null);
             callbackInfo.Callback(callbackInfo.StateForCallback);
         }
     }
@@ -1147,14 +1144,14 @@ namespace System.Threading
                             start = 0;
                             curr.m_freeCount--; // Too many free elements; fix up.
                         }
-                        Contract.Assert(start >= 0 && start < c, "start is outside of bounds");
+                        Debug.Assert(start >= 0 && start < c, "start is outside of bounds");
 
                         // Now walk the array until we find a free slot (or reach the end).
                         for (int i = 0; i < c; i++)
                         {
                             // If the slot is null, try to CAS our element into it.
                             int tryIndex = (start + i) % c;
-                            Contract.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds");
+                            Debug.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds");
                             
                             if (curr.m_elements[tryIndex] == null && Interlocked.CompareExchange(ref curr.m_elements[tryIndex], element, null) == null)
                             {
@@ -1193,8 +1190,8 @@ namespace System.Threading
 
         internal SparselyPopulatedArrayAddInfo(SparselyPopulatedArrayFragment<T> source, int index)
         {
-            Contract.Assert(source != null);
-            Contract.Assert(index >= 0 && index < source.Length);
+            Debug.Assert(source != null);
+            Debug.Assert(index >= 0 && index < source.Length);
             m_source = source;
             m_index = index;
         }
index 2e62216..d86a2cc 100644 (file)
 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 
 using System;
-using System.Diagnostics;
 using System.Security.Permissions;
 using System.Runtime.InteropServices;
 using System.Threading;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Threading
@@ -32,7 +32,6 @@ namespace System.Threading
     /// </remarks>
     [ComVisible(false)]
     [DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public class CountdownEvent : IDisposable
     {
         // CountdownEvent is a simple synchronization primitive used for fork/join parallelism. We create a
@@ -186,7 +185,7 @@ namespace System.Threading
         public bool Signal()
         {
             ThrowIfDisposed();
-            Contract.Assert(m_event != null);
+            Debug.Assert(m_event != null);
 
             if (m_currentCount <= 0)
             {
@@ -233,7 +232,7 @@ namespace System.Threading
             }
 
             ThrowIfDisposed();
-            Contract.Assert(m_event != null);
+            Debug.Assert(m_event != null);
 
             int observedCount;
             SpinWait spin = new SpinWait();
@@ -267,7 +266,7 @@ namespace System.Threading
                 return true;
             }
 
-            Contract.Assert(m_currentCount >= 0, "latch was decremented below zero");
+            Debug.Assert(m_currentCount >= 0, "latch was decremented below zero");
             return false;
         }
 
index 6c14489..4b1611c 100644 (file)
@@ -13,7 +13,6 @@
 =============================================================================*/
 
 
-#if !FEATURE_MACL
 namespace System.Security.AccessControl
 {
     public class EventWaitHandleSecurity
@@ -23,7 +22,6 @@ namespace System.Security.AccessControl
     {
     }
 }
-#endif
 
 namespace System.Threading
 {
@@ -39,14 +37,11 @@ namespace System.Threading
     using System.Security.AccessControl;
     using System.Diagnostics.Contracts;
 
-    [HostProtection(Synchronization=true, ExternalThreading=true)]
     [ComVisibleAttribute(true)]
     public class EventWaitHandle : WaitHandle
     {
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState,mode,null) { }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public EventWaitHandle(bool initialState, EventResetMode mode, string name)
         {
             if(name != null)
@@ -89,13 +84,11 @@ namespace System.Threading
             SetHandleInternal(_handle);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew)
             : this(initialState, mode, name, out createdNew, null)
         {
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
         {
             if(name != null)
@@ -111,18 +104,6 @@ namespace System.Threading
             }
             Contract.EndContractBlock();
             Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
-#if FEATURE_MACL
-            // For ACL's, get the security descriptor from the EventWaitHandleSecurity.
-            if (eventSecurity != null) {
-                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
-                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
-                byte[] sd = eventSecurity.GetSecurityDescriptorBinaryForm();
-                byte* pSecDescriptor = stackalloc byte[sd.Length];
-                Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
-                secAttrs.pSecurityDescriptor = pSecDescriptor;
-            }
-#endif
 
             SafeWaitHandle _handle = null;
             Boolean isManualReset;
@@ -155,23 +136,16 @@ namespace System.Threading
             SetHandleInternal(_handle);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private EventWaitHandle(SafeWaitHandle handle)
         {
             SetHandleInternal(handle);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static EventWaitHandle OpenExisting(string name)
         {
-#if !FEATURE_MACL
             return OpenExisting(name, (EventWaitHandleRights)0);
-#else
-            return OpenExisting(name, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize);
-#endif
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static EventWaitHandle OpenExisting(string name, EventWaitHandleRights rights)
         {
             EventWaitHandle result;
@@ -192,23 +166,16 @@ namespace System.Threading
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static bool TryOpenExisting(string name, out EventWaitHandle result)
         {
-#if !FEATURE_MACL
             return OpenExistingWorker(name, (EventWaitHandleRights)0, out result) == OpenExistingResult.Success;
-#else
-            return OpenExistingWorker(name, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, out result) == OpenExistingResult.Success;
-#endif
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static bool TryOpenExisting(string name, EventWaitHandleRights rights, out EventWaitHandle result)
         {
             return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandleRights rights, out EventWaitHandle result)
         {
 #if PLATFORM_UNIX
@@ -233,12 +200,8 @@ namespace System.Threading
 
             result = null;
 
-#if FEATURE_MACL
-            SafeWaitHandle myHandle = Win32Native.OpenEvent((int) rights, false, name);
-#else
             SafeWaitHandle myHandle = Win32Native.OpenEvent(Win32Native.EVENT_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name);
-#endif
-            
+
             if (myHandle.IsInvalid)
             {
                 int errorCode = Marshal.GetLastWin32Error();
@@ -256,7 +219,6 @@ namespace System.Threading
             return OpenExistingResult.Success;
 #endif
         }
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public bool Reset()
         {
             bool res = Win32Native.ResetEvent(safeWaitHandle);
@@ -264,7 +226,6 @@ namespace System.Threading
                 __Error.WinIOError();
             return res;
         }
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public bool Set()
         {
             bool res = Win32Native.SetEvent(safeWaitHandle);
@@ -274,24 +235,6 @@ namespace System.Threading
 
             return res;
         }
-
-#if FEATURE_MACL
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public EventWaitHandleSecurity GetAccessControl()
-        {
-            return new EventWaitHandleSecurity(safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public void SetAccessControl(EventWaitHandleSecurity eventSecurity)
-        {
-            if (eventSecurity == null)
-                throw new ArgumentNullException(nameof(eventSecurity));
-            Contract.EndContractBlock();
-
-            eventSecurity.Persist(safeWaitHandle);
-        }
-#endif
     }
 }
 
index 7adfca8..5ea9942 100644 (file)
@@ -23,14 +23,13 @@ namespace System.Threading
     using System.Runtime.InteropServices;
     using System.Runtime.CompilerServices;
     using System.Runtime.ConstrainedExecution;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Diagnostics.CodeAnalysis;
 
-    [System.Security.SecurityCritical] // auto-generated
     [System.Runtime.InteropServices.ComVisible(true)]
     public delegate void ContextCallback(Object state);
 
-    [SecurityCritical]
     internal struct ExecutionContextSwitcher
     {
         internal ExecutionContext m_ec;
@@ -38,7 +37,7 @@ namespace System.Threading
 
         internal void Undo(Thread currentThread)
         {
-            Contract.Assert(currentThread == Thread.CurrentThread);
+            Debug.Assert(currentThread == Thread.CurrentThread);
 
             // The common case is that these have not changed, so avoid the cost of a write if not needed.
             if (currentThread.SynchronizationContext != m_sc)
@@ -91,7 +90,6 @@ namespace System.Threading
         {
         }
 
-        [SecuritySafeCritical]
         public static ExecutionContext Capture()
         {
             ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
@@ -109,7 +107,7 @@ namespace System.Threading
 
         private ExecutionContext ShallowClone(bool isFlowSuppressed)
         {
-            Contract.Assert(isFlowSuppressed != m_isFlowSuppressed);
+            Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
 
             if (!isFlowSuppressed &&
                 m_localValues == Default.m_localValues &&
@@ -156,7 +154,6 @@ namespace System.Threading
             return executionContext != null && executionContext.m_isFlowSuppressed;
         }
 
-        [SecurityCritical]
         [HandleProcessCorruptedStateExceptions]
         public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
         {
@@ -183,10 +180,9 @@ namespace System.Threading
             ecsw.Undo(currentThread);
         }
 
-        [SecurityCritical]
         internal static void Restore(Thread currentThread, ExecutionContext executionContext)
         {
-            Contract.Assert(currentThread == Thread.CurrentThread);
+            Debug.Assert(currentThread == Thread.CurrentThread);
 
             ExecutionContext previous = currentThread.ExecutionContext ?? Default;
             currentThread.ExecutionContext = executionContext;
@@ -201,22 +197,20 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw)
         {
-            Contract.Assert(currentThread == Thread.CurrentThread);
+            Debug.Assert(currentThread == Thread.CurrentThread);
             
             ecsw.m_ec = currentThread.ExecutionContext; 
             ecsw.m_sc = currentThread.SynchronizationContext;
         }
 
-        [SecurityCritical]
         [HandleProcessCorruptedStateExceptions]
         private static void OnContextChanged(ExecutionContext previous, ExecutionContext current)
         {
-            Contract.Assert(previous != null);
-            Contract.Assert(current != null);
-            Contract.Assert(previous != current);
+            Debug.Assert(previous != null);
+            Debug.Assert(current != null);
+            Debug.Assert(previous != current);
             
             foreach (IAsyncLocal local in previous.m_localChangeNotifications)
             {
@@ -257,7 +251,6 @@ namespace System.Threading
             }        
         }
 
-        [SecurityCritical]
         internal static object GetLocalValue(IAsyncLocal local)
         {
             ExecutionContext current = Thread.CurrentThread.ExecutionContext;
@@ -269,7 +262,6 @@ namespace System.Threading
             return value;
         }
 
-        [SecurityCritical]
         internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
         {
             ExecutionContext current = Thread.CurrentThread.ExecutionContext ?? ExecutionContext.Default;
@@ -290,7 +282,7 @@ namespace System.Threading
             {
                 if (hadPreviousValue)
                 {
-                    Contract.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
+                    Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
                 }
                 else
                 {
@@ -319,33 +311,28 @@ namespace System.Threading
             OptimizeDefaultCase = 0x02,
         }
 
-        [SecurityCritical]
         internal static ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions captureOptions)
         {
             return Capture();
         }
 
-        [SecuritySafeCritical]
         [FriendAccessAllowed]
         internal static ExecutionContext FastCapture()
         {
             return Capture();
         }
 
-        [SecurityCritical]
         [FriendAccessAllowed]
         internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
         {
             Run(executionContext, callback, state);
         }
 
-        [SecurityCritical]
         internal bool IsDefaultFTContext(bool ignoreSyncCtx)
         {
             return this == Default;
         }
 
-        [SecuritySafeCritical]
         public ExecutionContext CreateCopy()
         {
             return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
@@ -358,7 +345,6 @@ namespace System.Threading
 
         internal static ExecutionContext PreAllocatedDefault
         {
-            [SecuritySafeCritical]
             get { return ExecutionContext.Default; }
         }
 
@@ -376,7 +362,7 @@ namespace System.Threading
 
         internal void Initialize(Thread currentThread)
         {
-            Contract.Assert(currentThread == Thread.CurrentThread);
+            Debug.Assert(currentThread == Thread.CurrentThread);
             _thread = currentThread;
         }
 
index 50cc766..8a0b527 100644 (file)
@@ -66,34 +66,27 @@ namespace System.Threading
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         public static extern int Exchange(ref int location1, int value);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecuritySafeCritical]
         public static extern long Exchange(ref long location1, long value);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecuritySafeCritical]
         public static extern float Exchange(ref float location1, float value);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecuritySafeCritical]
         public static extern double Exchange(ref double location1, double value);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         public static extern Object Exchange(ref Object location1, Object value);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         public static extern IntPtr Exchange(ref IntPtr location1, IntPtr value);
 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [System.Runtime.InteropServices.ComVisible(false)]
-        [System.Security.SecuritySafeCritical]
         public static T Exchange<T>(ref T location1, T value) where T : class
         {
             _Exchange(__makeref(location1), __makeref(value));
@@ -106,7 +99,6 @@ namespace System.Threading
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         private static extern void _Exchange(TypedReference location1, TypedReference value);
 
         /******************************
@@ -121,29 +113,23 @@ namespace System.Threading
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         public static extern int CompareExchange(ref int location1, int value, int comparand);    
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecuritySafeCritical]
         public static extern long CompareExchange(ref long location1, long value, long comparand);    
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecuritySafeCritical]
         public static extern float CompareExchange(ref float location1, float value, float comparand);    
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [System.Security.SecuritySafeCritical]
         public static extern double CompareExchange(ref double location1, double value, double comparand);    
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         public static extern Object CompareExchange(ref Object location1, Object value, Object comparand);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         public static extern IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand);
 
         /*****************************************************************
@@ -172,7 +158,6 @@ namespace System.Threading
         
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [System.Runtime.InteropServices.ComVisible(false)]
-        [System.Security.SecuritySafeCritical]
         public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class
         {
             // _CompareExchange() passes back the value read from location1 via local named 'value'
@@ -182,13 +167,11 @@ namespace System.Threading
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         private static extern void _CompareExchange(TypedReference location1, TypedReference value, Object comparand);
 
         // BCL-internal overload that returns success via a ref bool param, useful for reliable spin locks.
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [System.Security.SecuritySafeCritical]
         internal static extern int CompareExchange(ref int location1, int value, int comparand, ref bool succeeded);
 
         /******************************
index c8e74e3..238cc89 100644 (file)
@@ -12,6 +12,7 @@
 
 
 using System.Security.Permissions;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 namespace System.Threading
 {
@@ -54,7 +55,6 @@ namespace System.Threading
     /// These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using
     /// references to ensure targets have been initialized as they are accessed.
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public static class LazyInitializer
     {
         /// <summary>
@@ -149,7 +149,7 @@ namespace System.Threading
             }
 
             Interlocked.CompareExchange(ref target, value, null);
-            Contract.Assert(target != null);
+            Debug.Assert(target != null);
             return target;
         }
 
index c5e3146..ab95e70 100644 (file)
@@ -20,9 +20,6 @@ namespace System.Threading
 
     [Serializable]
     [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public class LockRecursionException : System.Exception
     {
         public LockRecursionException() { }
index 504cfb4..0004156 100644 (file)
@@ -17,7 +17,6 @@ namespace System.Threading {
     using System.Security.Permissions;
     using System.Runtime.InteropServices;
 
-    [HostProtection(Synchronization=true, ExternalThreading=true)]
 [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class ManualResetEvent : EventWaitHandle
     {        
index a95e368..509af5b 100644 (file)
 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 
 using System;
-using System.Diagnostics;
 using System.Security.Permissions;
 using System.Threading;
 using System.Runtime.InteropServices;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Threading
@@ -47,7 +47,6 @@ namespace System.Threading
     /// </remarks>
     [ComVisible(false)]
     [DebuggerDisplay("Set = {IsSet}")]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public class ManualResetEventSlim : IDisposable
     {
         // These are the default spin counts we use on single-proc and MP machines.
@@ -144,8 +143,8 @@ namespace System.Threading
 
             private set
             {
-                Contract.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
-                Contract.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
+                Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
+                Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
                 // Don't worry about thread safety because it's set one time from the constructor
                 m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount);
             }
@@ -164,7 +163,7 @@ namespace System.Threading
             set
             {
                 //setting to <0 would indicate an internal flaw, hence Assert is appropriate.
-                Contract.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
+                Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
 
                 // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
                 if (value >= NumWaitersState_MaxValue)
@@ -242,8 +241,8 @@ namespace System.Threading
             this.m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
             //the spinCount argument has been validated by the ctors.
             //but we now sanity check our predefined constants.
-            Contract.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
-            Contract.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
+            Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
+            Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
 
             SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
 
@@ -295,7 +294,7 @@ namespace System.Threading
                 bool currentIsSet = IsSet;
                 if (currentIsSet != preInitializeIsSet)
                 {
-                    Contract.Assert(currentIsSet,
+                    Debug.Assert(currentIsSet,
                         "The only safe concurrent transition is from unset->set: detected set->unset.");
 
                     // We saw it as unsignaled, but it has since become set.
@@ -337,7 +336,7 @@ namespace System.Threading
             // If there are waiting threads, we need to pulse them.
             if (Waiters > 0)
             {
-                Contract.Assert(m_lock != null); //if waiters>0, then m_lock has already been created.
+                Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created.
                 lock (m_lock)
                 {
 
@@ -738,8 +737,8 @@ namespace System.Threading
         private static void CancellationTokenCallback(object obj)
         {
             ManualResetEventSlim mre = obj as ManualResetEventSlim;
-            Contract.Assert(mre != null, "Expected a ManualResetEventSlim");
-            Contract.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
+            Debug.Assert(mre != null, "Expected a ManualResetEventSlim");
+            Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
             lock (mre.m_lock)
             {
                 Monitor.PulseAll(mre.m_lock); // awaken all waiters
@@ -759,7 +758,7 @@ namespace System.Threading
         {
             SpinWait sw = new SpinWait();
 
-            Contract.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
+            Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
 
             do
             {
index 92176fa..94dec13 100644 (file)
@@ -24,9 +24,9 @@ namespace System.Threading {
     using System.Runtime.CompilerServices;
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
-    [HostProtection(Synchronization=true, ExternalThreading=true)]
     [System.Runtime.InteropServices.ComVisible(true)]
     public static class Monitor 
     {
@@ -38,7 +38,6 @@ namespace System.Threading {
         **
         ** Exceptions: ArgumentNullException if object is null.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void Enter(Object obj);
 
@@ -54,7 +53,7 @@ namespace System.Threading {
                 ThrowLockTakenException();
 
             ReliableEnter(obj, ref lockTaken);
-            Contract.Assert(lockTaken);
+            Debug.Assert(lockTaken);
         }
 
         private static void ThrowLockTakenException()
@@ -62,7 +61,6 @@ namespace System.Threading {
             throw new ArgumentException(Environment.GetResourceString("Argument_MustBeFalse"), "lockTaken");
         }
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void ReliableEnter(Object obj, ref bool lockTaken);
 
@@ -77,7 +75,6 @@ namespace System.Threading {
         **             SynchronizationLockException if the current thread does not
         **             own the lock.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static extern void Exit(Object obj);
@@ -154,11 +151,9 @@ namespace System.Threading {
             ReliableEnterTimeout(obj, MillisecondsTimeoutFromTimeSpan(timeout), ref lockTaken);
         }
 
-        [System.Security.SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void ReliableEnterTimeout(Object obj, int timeout, ref bool lockTaken);
 
-        [System.Security.SecuritySafeCritical]
         public static bool IsEntered(object obj)
         {
             if (obj == null)
@@ -167,7 +162,6 @@ namespace System.Threading {
             return IsEnteredNative(obj);
         }
 
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool IsEnteredNative(Object obj);
 
@@ -182,11 +176,9 @@ namespace System.Threading {
     **
         ** Exceptions: ArgumentNullException if object is null.
     ========================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool ObjWait(bool exitContext, int millisecondsTimeout, Object obj);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext)
         {
             if (obj == null)
@@ -219,11 +211,9 @@ namespace System.Threading {
         * Exceptions: SynchronizationLockException if this method is not called inside
         * a synchronized block of code.
         ========================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void ObjPulse(Object obj);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void Pulse(Object obj)
         {
             if (obj == null)
@@ -237,11 +227,9 @@ namespace System.Threading {
         /*========================================================================
         ** Sends a notification to all waiting objects. 
         ========================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void ObjPulseAll(Object obj);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void PulseAll(Object obj)
         {
             if (obj == null)
index 98789d9..506abb7 100644 (file)
@@ -24,31 +24,24 @@ namespace System.Threading
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
     using System.Security;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
-    
-#if FEATURE_MACL
-    using System.Security.AccessControl;
-#endif
 
-    [HostProtection(Synchronization=true, ExternalThreading=true)]
     [ComVisible(true)]
     public sealed class Mutex : WaitHandle
     {
         static bool dummyBool;
 
-#if !FEATURE_MACL
-        public class MutexSecurity {
+        public class MutexSecurity
+        {
         }
-#endif       
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public Mutex(bool initiallyOwned, String name, out bool createdNew)
             : this(initiallyOwned, name, out createdNew, (MutexSecurity)null)
         {
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity)
         {
@@ -65,24 +58,10 @@ namespace System.Threading
 #endif
             Contract.EndContractBlock();
             Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
-#if FEATURE_MACL
-            // For ACL's, get the security descriptor from the MutexSecurity.
-            if (mutexSecurity != null) {
-
-                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
-                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
-                byte[] sd = mutexSecurity.GetSecurityDescriptorBinaryForm();
-                byte* pSecDescriptor = stackalloc byte[sd.Length];
-                Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
-                secAttrs.pSecurityDescriptor = pSecDescriptor;
-            }
-#endif
 
             CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         internal Mutex(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs) 
         {
@@ -102,7 +81,6 @@ namespace System.Threading
             CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         internal void CreateMutexWithGuaranteedCleanup(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs)
         {
@@ -123,15 +101,13 @@ namespace System.Threading
             MutexCleanupInfo m_cleanupInfo;
             internal bool m_newMutex;
             String m_name;
-            [System.Security.SecurityCritical] // auto-generated
             Win32Native.SECURITY_ATTRIBUTES m_secAttrs;
             Mutex m_mutex;
 
-            [System.Security.SecurityCritical]  // auto-generated
             [PrePrepareMethod]
             internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex)
             {
-                Contract.Assert(name == null || name.Length != 0);
+                Debug.Assert(name == null || name.Length != 0);
 
                 m_initiallyOwned = initiallyOwned;
                 m_cleanupInfo = cleanupInfo;
@@ -140,7 +116,6 @@ namespace System.Threading
                 m_mutex = mutex;
             }
 
-            [System.Security.SecurityCritical]  // auto-generated
             [PrePrepareMethod]
             internal void MutexTryCode(object userData)
             {  
@@ -155,14 +130,10 @@ namespace System.Threading
                     if (m_initiallyOwned) 
                     {
                         m_cleanupInfo.inCriticalRegion = true;
-#if !FEATURE_CORECLR
-                        Thread.BeginThreadAffinity();
-                        Thread.BeginCriticalRegion();
-#endif //!FEATURE_CORECLR
                     }
                 }
 
-                int errorCode = 0;                    
+                int errorCode = 0;
                 RuntimeHelpers.PrepareConstrainedRegions();
                 try 
                 {
@@ -199,38 +170,27 @@ namespace System.Threading
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [PrePrepareMethod]
         private void MutexCleanupCode(Object userData, bool exceptionThrown)
         {
             MutexCleanupInfo cleanupInfo = (MutexCleanupInfo) userData;
             
             // If hasThreadAffinity isn't true, we've thrown an exception in the above try, and we must free the mutex 
-            // on this OS thread before ending our thread affninity.                
+            // on this OS thread before ending our thread affninity.
             if(!hasThreadAffinity) {
                 if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid) {
                     if( cleanupInfo.inCriticalRegion) {
-                        Win32Native.ReleaseMutex(cleanupInfo.mutexHandle);                    
+                        Win32Native.ReleaseMutex(cleanupInfo.mutexHandle);
                     }
-                    cleanupInfo.mutexHandle.Dispose();                        
-                    
+                    cleanupInfo.mutexHandle.Dispose();
                 }
-                    
-                if( cleanupInfo.inCriticalRegion) {
-#if !FEATURE_CORECLR
-                    Thread.EndCriticalRegion();
-                    Thread.EndThreadAffinity();
-#endif
-                }                    
             }
         }
 
         internal class MutexCleanupInfo
         {
-            [System.Security.SecurityCritical] // auto-generated
             internal SafeWaitHandle mutexHandle;
             internal bool inCriticalRegion;
-            [System.Security.SecurityCritical]  // auto-generated
             internal MutexCleanupInfo(SafeWaitHandle mutexHandle, bool inCriticalRegion)
             {
                 this.mutexHandle = mutexHandle;
@@ -238,24 +198,20 @@ namespace System.Threading
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool) {
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public Mutex(bool initiallyOwned) : this(initiallyOwned, null, out dummyBool)
         {
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public Mutex() : this(false, null, out dummyBool)
         {
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private Mutex(SafeWaitHandle handle)
         {
@@ -263,23 +219,15 @@ namespace System.Threading
             hasThreadAffinity = true;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Mutex OpenExisting(string name)
         {
-#if !FEATURE_MACL
             return OpenExisting(name, (MutexRights) 0);
-#else // FEATURE_MACL
-            return OpenExisting(name, MutexRights.Modify | MutexRights.Synchronize);
-#endif // FEATURE_MACL
         }
 
-#if !FEATURE_MACL
         public enum MutexRights
         {
         }
-#endif
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Mutex OpenExisting(string name, MutexRights rights)
         {
             Mutex result;
@@ -300,23 +248,16 @@ namespace System.Threading
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static bool TryOpenExisting(string name, out Mutex result)
         {
-#if !FEATURE_MACL
             return OpenExistingWorker(name, (MutexRights)0, out result) == OpenExistingResult.Success;
-#else // FEATURE_MACL
-            return OpenExistingWorker(name, MutexRights.Modify | MutexRights.Synchronize, out result) == OpenExistingResult.Success;
-#endif // FEATURE_MACL
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static bool TryOpenExisting(string name, MutexRights rights, out Mutex result)
         {
             return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success;
         }
 
-        [System.Security.SecurityCritical]
         private static OpenExistingResult OpenExistingWorker(string name, MutexRights rights, out Mutex result)
         {
             if (name == null)
@@ -342,11 +283,7 @@ namespace System.Threading
             // with parameters to allow us to view & edit the ACL.  This will
             // fail if we don't have permission to view or edit the ACL's.  
             // If that happens, ask for less permissions.
-#if FEATURE_MACL
-            SafeWaitHandle myHandle = Win32Native.OpenMutex((int) rights, false, name);
-#else
             SafeWaitHandle myHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name);
-#endif
 
             int errorCode = 0;
             if (myHandle.IsInvalid)
@@ -379,110 +316,51 @@ namespace System.Threading
         // Note: To call ReleaseMutex, you must have an ACL granting you
         // MUTEX_MODIFY_STATE rights (0x0001).  The other interesting value
         // in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001).
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]        
+        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public void ReleaseMutex()
         {
             if (Win32Native.ReleaseMutex(safeWaitHandle))
             {
-#if !FEATURE_CORECLR
-                Thread.EndCriticalRegion();
-                Thread.EndThreadAffinity();
-#endif
             }
             else
             {
-#if FEATURE_CORECLR
                 throw new Exception(Environment.GetResourceString("Arg_SynchronizationLockException"));
-#else
-                throw new ApplicationException(Environment.GetResourceString("Arg_SynchronizationLockException"));
-#endif // FEATURE_CORECLR
-            }                                                               
+            }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-        static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle) {            
-            int errorCode;  
-            bool fAffinity = false;
-            
-            while(true) {
+        static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle)
+        {
+            int errorCode;
+
+            while (true)
+            {
                 mutexHandle = Win32Native.CreateMutex(securityAttribute, initiallyOwned, name);
-                errorCode = Marshal.GetLastWin32Error();                                
-                if( !mutexHandle.IsInvalid) {
-                    break;                
-                }
+                errorCode = Marshal.GetLastWin32Error();
+                if (!mutexHandle.IsInvalid) break;
 
-                if( errorCode == Win32Native.ERROR_ACCESS_DENIED) {
-                    // If a mutex with the name already exists, OS will try to open it with FullAccess.
-                    // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access.
-                    //
-                    
-                    RuntimeHelpers.PrepareConstrainedRegions();
-                    try 
-                    {
-                        try 
-                        {
-                        } 
-                        finally 
-                        {
-#if !FEATURE_CORECLR
-                            Thread.BeginThreadAffinity();
-#endif
-                            fAffinity = true;
-                        }
-                        mutexHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name);
-                        if(!mutexHandle.IsInvalid)
-                        {
-                            errorCode = Win32Native.ERROR_ALREADY_EXISTS;
-                        }
-                        else
-                        {
-                            errorCode = Marshal.GetLastWin32Error();
-                        }
-                    }
-                    finally 
-                    {
-                        if (fAffinity) {
-#if !FEATURE_CORECLR
-                            Thread.EndThreadAffinity();
-#endif
-                        }
-                    }
+                if (errorCode != Win32Native.ERROR_ACCESS_DENIED) break;
 
-                    // There could be a race condition here, the other owner of the mutex can free the mutex,
-                    // We need to retry creation in that case.
-                    if( errorCode != Win32Native.ERROR_FILE_NOT_FOUND) {
-                        if( errorCode == Win32Native.ERROR_SUCCESS) {
-                            errorCode =  Win32Native.ERROR_ALREADY_EXISTS;
-                        }                        
-                        break;
-                    }
-                }
-                else {
+                // If a mutex with the name already exists, OS will try to open it with FullAccess.
+                // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access.
+                RuntimeHelpers.PrepareConstrainedRegions();
+
+                mutexHandle = Win32Native.OpenMutex(
+                    Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE,
+                    false,
+                    name);
+
+                errorCode = !mutexHandle.IsInvalid ? Win32Native.ERROR_ALREADY_EXISTS : Marshal.GetLastWin32Error();
+
+                // There could be a race condition here, the other owner of the mutex can free the mutex,
+                // We need to retry creation in that case.
+                if (errorCode != Win32Native.ERROR_FILE_NOT_FOUND)
+                {
+                    if (errorCode == Win32Native.ERROR_SUCCESS) errorCode = Win32Native.ERROR_ALREADY_EXISTS;
                     break;
                 }
-            }                        
+            }
             return errorCode;
         }
-        
-#if FEATURE_MACL
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public MutexSecurity GetAccessControl()
-        {
-            return new MutexSecurity(safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
-        }
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public void SetAccessControl(MutexSecurity mutexSecurity)
-        {
-            if (mutexSecurity == null)
-                throw new ArgumentNullException(nameof(mutexSecurity));
-            Contract.EndContractBlock();
-
-            mutexSecurity.Persist(safeWaitHandle);
-        }
-#endif
-
     }
 }
index 7b27464..2b192c7 100644 (file)
@@ -33,6 +33,7 @@ namespace System.Threading
     using System.Security;
     using System.Security.Permissions;
     using System.Runtime.ConstrainedExecution;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Collections.Concurrent;
 
@@ -60,20 +61,16 @@ namespace System.Threading
 
     unsafe internal class _IOCompletionCallback
     {
-        [System.Security.SecurityCritical] // auto-generated
         IOCompletionCallback _ioCompletionCallback;
         ExecutionContext _executionContext;
         uint _errorCode; // Error code
         uint _numBytes; // No. of bytes transferred 
-        [SecurityCritical]
         NativeOverlapped* _pOVERLAP;
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static _IOCompletionCallback()
         {
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ref StackCrawlMark stackMark)
         {
             _ioCompletionCallback = ioCompletionCallback;
@@ -83,21 +80,16 @@ namespace System.Threading
                 ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
         }
         // Context callback: same sig for SendOrPostCallback and ContextCallback
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #endif
         static internal ContextCallback _ccb = new ContextCallback(IOCompletionCallback_Context);
-        [System.Security.SecurityCritical]
         static internal void IOCompletionCallback_Context(Object state)
         {
             _IOCompletionCallback helper  = (_IOCompletionCallback)state;
-            Contract.Assert(helper != null,"_IOCompletionCallback cannot be null");
+            Debug.Assert(helper != null,"_IOCompletionCallback cannot be null");
             helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP);
         }
 
                                                         
         // call back helper
-        [System.Security.SecurityCritical]  // auto-generated
         static unsafe internal void PerformIOCompletionCallback(uint errorCode, // Error code
                                                                             uint numBytes, // No. of bytes transferred 
                                                                             NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
@@ -146,7 +138,6 @@ namespace System.Threading
         // ! If you make any change to the layout here, you need to make matching change 
         // ! to OverlappedObject in vm\nativeoverlapped.h
         internal IAsyncResult m_asyncResult;
-        [System.Security.SecurityCritical] // auto-generated
         internal IOCompletionCallback m_iocb;
         internal _IOCompletionCallback m_iocbHelper;
         internal Overlapped m_overlapped;
@@ -162,14 +153,9 @@ namespace System.Threading
 #pragma warning restore 169
         internal NativeOverlapped m_nativeOverlapped;
 
-#if FEATURE_CORECLR
         // Adding an empty default ctor for annotation purposes
-        [System.Security.SecuritySafeCritical] // auto-generated
         internal OverlappedData(){}
-#endif // FEATURE_CORECLR
 
-
-        [System.Security.SecurityCritical]
         internal void ReInitialize()
         {
             m_asyncResult = null;
@@ -177,10 +163,10 @@ namespace System.Threading
             m_iocbHelper = null;
             m_overlapped = null;
             m_userObject = null;
-            Contract.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf");
+            Debug.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf");
             m_pinSelf = (IntPtr)0;
             m_userObjectInternal = (IntPtr)0;
-            Contract.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain");
+            Debug.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain");
             m_AppDomainId = 0;
             m_nativeOverlapped.EventHandle = (IntPtr)0;
             m_isArray = 0;
@@ -188,7 +174,6 @@ namespace System.Threading
             m_nativeOverlapped.InternalHigh = (IntPtr)0;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
         {
@@ -222,7 +207,6 @@ namespace System.Threading
             return AllocateNativeOverlapped();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         unsafe internal NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
         {            
             if (!m_pinSelf.IsNull()) {
@@ -252,19 +236,15 @@ namespace System.Threading
             set { m_nativeOverlapped.EventHandle = value; }
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe private extern NativeOverlapped* AllocateNativeOverlapped();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe internal static extern void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr);        
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe internal static extern void CheckVMForIOPacket(out NativeOverlapped* pOVERLAP, out uint errorCode, out uint numBytes);
     }
@@ -281,9 +261,6 @@ namespace System.Threading
         private OverlappedData m_overlappedData;
         private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", ()=> new OverlappedData());
    
-#if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#endif
         public Overlapped() 
         {
             m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate();
@@ -344,7 +321,6 @@ namespace System.Threading
 
         internal IOCompletionCallback UserCallback
         {
-            [System.Security.SecurityCritical]
             get { return m_overlappedData.m_iocb; }
         }
 
@@ -353,7 +329,6 @@ namespace System.Threading
         *  Roots the iocb and stores it in the ReservedCOR field of native Overlapped 
         *  Pins the native Overlapped struct and returns the pinned index. 
         ====================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated
         [Obsolete("This method is not safe.  Use Pack (iocb, userData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
         [CLSCompliant(false)]
         unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb)
@@ -361,14 +336,12 @@ namespace System.Threading
             return Pack (iocb, null);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false),ComVisible(false)]
         unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
         {
             return m_overlappedData.Pack(iocb, userData);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [Obsolete("This method is not safe.  Use UnsafePack (iocb, userData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
         [CLSCompliant(false)]
         unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb)
@@ -376,7 +349,6 @@ namespace System.Threading
             return UnsafePack (iocb, null);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [CLSCompliant(false), ComVisible(false)]
         unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
         {            
@@ -387,7 +359,6 @@ namespace System.Threading
         *  Unpacks an unmanaged native Overlapped struct. 
         *  Unpins the native Overlapped struct
         ====================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         unsafe public static Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr)
         {
@@ -400,7 +371,6 @@ namespace System.Threading
             return overlapped;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [CLSCompliant(false)]
         unsafe public static void Free(NativeOverlapped* nativeOverlappedPtr)
         {
index dc1b2fb..e35ac76 100644 (file)
@@ -25,14 +25,12 @@ namespace System.Threading {
     using System.Runtime.Versioning;
     using System.Diagnostics.Contracts;
 
-    [HostProtection(Synchronization=true, ExternalThreading=true)]
     [ComVisible(true)]
     public sealed class ReaderWriterLock: CriticalFinalizerObject
     {
         /*
          * Constructor
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public ReaderWriterLock()
         {
             PrivateInitialize();
@@ -41,7 +39,6 @@ namespace System.Threading {
         /*
          * Destructor
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         ~ReaderWriterLock()
         {
             PrivateDestruct();
@@ -52,7 +49,6 @@ namespace System.Threading {
          * by the current thread
          */
         public bool IsReaderLockHeld {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             get {
                 return(PrivateGetIsReaderLockHeld());
@@ -64,7 +60,6 @@ namespace System.Threading {
          * by the current thread
          */
         public bool IsWriterLockHeld {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             get {
                 return(PrivateGetIsWriterLockHeld());
@@ -77,7 +72,6 @@ namespace System.Threading {
          * meaningful results
          */
         public int WriterSeqNum {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 return(PrivateGetWriterSeqNum());
                 }
@@ -87,18 +81,15 @@ namespace System.Threading {
          * Acquires reader lock. The thread will block if a different
          * thread has writer lock.
          */
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void AcquireReaderLockInternal(int millisecondsTimeout);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AcquireReaderLock(int millisecondsTimeout)
         {
             AcquireReaderLockInternal(millisecondsTimeout);
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AcquireReaderLock(TimeSpan timeout)
         {
             long tm = (long)timeout.TotalMilliseconds;
@@ -113,17 +104,14 @@ namespace System.Threading {
          * has reader lock. Use UpgardeToWriterLock when you are not
          * sure if the thread has reader lock
          */
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void AcquireWriterLockInternal(int millisecondsTimeout);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AcquireWriterLock(int millisecondsTimeout)
         {
             AcquireWriterLockInternal(millisecondsTimeout);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void AcquireWriterLock(TimeSpan timeout)
         {
             long tm = (long)timeout.TotalMilliseconds;
@@ -136,12 +124,10 @@ namespace System.Threading {
         /*
          * Releases reader lock. 
          */
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private extern void ReleaseReaderLockInternal();
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public void ReleaseReaderLock()
         {
@@ -151,12 +137,10 @@ namespace System.Threading {
         /*
          * Releases writer lock. 
          */
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private extern void ReleaseWriterLockInternal();
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public void ReleaseWriterLock()
         {
@@ -168,7 +152,6 @@ namespace System.Threading {
          * reader, it is possible that the reader lock was 
          * released before writer lock was acquired.
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public LockCookie UpgradeToWriterLock(int millisecondsTimeout)
         {
             LockCookie result = new LockCookie ();
@@ -176,7 +159,6 @@ namespace System.Threading {
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void FCallUpgradeToWriterLock(ref LockCookie result, int millisecondsTimeout);
 
@@ -192,11 +174,9 @@ namespace System.Threading {
          * Restores the lock status of the thread to the one it was
          * in when it called UpgradeToWriterLock. 
          */
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void DowngradeFromWriterLockInternal(ref LockCookie lockCookie);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void DowngradeFromWriterLock(ref LockCookie lockCookie)
         {
             DowngradeFromWriterLockInternal(ref lockCookie);
@@ -206,7 +186,6 @@ namespace System.Threading {
          * Releases the lock irrespective of the number of times the thread
          * acquired the lock
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public LockCookie ReleaseLock()
         {
             LockCookie result = new LockCookie ();
@@ -214,7 +193,6 @@ namespace System.Threading {
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void FCallReleaseLock(ref LockCookie result);
         
@@ -222,11 +200,9 @@ namespace System.Threading {
          * Restores the lock status of the thread to the one it was
          * in when it called ReleaseLock. 
          */
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void RestoreLockInternal(ref LockCookie lockCookie);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void RestoreLock(ref LockCookie lockCookie)
         {
             RestoreLockInternal(ref lockCookie);
@@ -236,7 +212,6 @@ namespace System.Threading {
          * Internal helper that returns TRUE if the reader lock is held
          * by the current thread
          */
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private extern bool PrivateGetIsReaderLockHeld();
@@ -245,7 +220,6 @@ namespace System.Threading {
          * Internal helper that returns TRUE if the writer lock is held
          * by the current thread
          */
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private extern bool PrivateGetIsWriterLockHeld();
@@ -255,7 +229,6 @@ namespace System.Threading {
          * number. The caller should be a reader or writer for getting 
          * meaningful results
          */
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern int PrivateGetWriterSeqNum();
         
@@ -264,17 +237,14 @@ namespace System.Threading {
          * sequence number was obtained. The caller should be
          * a reader or writer for getting meaningful results
          */
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern bool AnyWritersSince(int seqNum);
     
         // Initialize state kept inside the lock
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void PrivateInitialize();
 
         // Destruct resource associated with the lock
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void PrivateDestruct();
 
index b0ad4f6..1eac4aa 100644 (file)
@@ -4,6 +4,7 @@
 
 using Microsoft.Win32;
 using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.IO;
 using System.Runtime.InteropServices;
@@ -13,10 +14,8 @@ namespace System.Threading
 {
     public sealed partial class Semaphore : WaitHandle
     {
-        [SecuritySafeCritical]
         public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { }
 
-        [SecurityCritical]
         public Semaphore(int initialCount, int maximumCount, string name)
         {
             if (initialCount < 0)
@@ -49,7 +48,6 @@ namespace System.Threading
             this.SafeWaitHandle = myHandle;
         }
 
-        [SecurityCritical]
         public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew)
         {
             if (initialCount < 0)
@@ -81,13 +79,11 @@ namespace System.Threading
             this.SafeWaitHandle = myHandle;
         }
 
-        [SecurityCritical]
         private Semaphore(SafeWaitHandle handle)
         {
             this.SafeWaitHandle = handle;
         }
 
-        [SecurityCritical]
         private static SafeWaitHandle CreateSemaphone(int initialCount, int maximumCount, string name)
         {
             if (name != null)
@@ -100,15 +96,13 @@ namespace System.Threading
 #endif
             }
 
-            Contract.Assert(initialCount >= 0);
-            Contract.Assert(maximumCount >= 1);
-            Contract.Assert(initialCount <= maximumCount);
+            Debug.Assert(initialCount >= 0);
+            Debug.Assert(maximumCount >= 1);
+            Debug.Assert(initialCount <= maximumCount);
 
             return Win32Native.CreateSemaphore(null, initialCount, maximumCount, name);
         }
 
-        [SecurityCritical]
-
         public static Semaphore OpenExisting(string name)
         {
             Semaphore result;
@@ -125,13 +119,11 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         public static bool TryOpenExisting(string name, out Semaphore result)
         {
             return OpenExistingWorker(name, out result) == OpenExistingResult.Success;
         }
 
-        [SecurityCritical]
         private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result)
         {
 #if PLATFORM_UNIX
@@ -177,7 +169,6 @@ namespace System.Threading
         }
 
         // increase the count on a semaphore, returns previous count
-        [SecuritySafeCritical]
         public int Release(int releaseCount)
         {
             if (releaseCount < 1)
index e1928e0..01c5040 100644 (file)
@@ -9,9 +9,6 @@ namespace System.Threading {
 
     [Serializable]
     [ComVisibleAttribute(false)]
-#if !FEATURE_CORECLR
-    [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     public class SemaphoreFullException : SystemException {
     
         public SemaphoreFullException() : base(Environment.GetResourceString("Threading_SemaphoreFullException")){
index c47ca02..92d760d 100644 (file)
@@ -40,7 +40,6 @@ namespace System.Threading
     /// </para>
     /// </remarks>
     [ComVisible(false)]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     [DebuggerDisplay("Current Count = {m_currentCount}")]
     public class SemaphoreSlim : IDisposable
     {
@@ -89,14 +88,12 @@ namespace System.Threading
             internal TaskNode Prev, Next;
             internal TaskNode() : base() {}
 
-            [SecurityCritical]
             void IThreadPoolWorkItem.ExecuteWorkItem()
             {
                 bool setSuccessfully = TrySetResult(true);
-                Contract.Assert(setSuccessfully, "Should have been able to complete task");
+                Debug.Assert(setSuccessfully, "Should have been able to complete task");
             }
 
-            [SecurityCritical]
             void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ }
         }
         #endregion
@@ -372,7 +369,7 @@ namespace System.Threading
                 // then block on (once we've released the lock).
                 if (m_asyncHead != null)
                 {
-                    Contract.Assert(m_asyncTail != null, "tail should not be null if head isn't");
+                    Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't");
                     asyncWaitTask = WaitAsync(millisecondsTimeout, cancellationToken);
                 }
                     // There are no async waiters, so we can proceed with normal synchronous waiting.
@@ -404,7 +401,7 @@ namespace System.Threading
                     // defer to synchronous waiters in priority, which means that if it's possible an asynchronous
                     // waiter didn't get released because a synchronous waiter was present, we need to ensure
                     // that synchronous waiter succeeds so that they have a chance to release.
-                    Contract.Assert(!waitSuccessful || m_currentCount > 0, 
+                    Debug.Assert(!waitSuccessful || m_currentCount > 0, 
                         "If the wait was successful, there should be count available.");
                     if (m_currentCount > 0)
                     {
@@ -638,7 +635,7 @@ namespace System.Threading
                     // the semaphore or when the timeout expired or cancellation was requested.
                 else
                 {
-                    Contract.Assert(m_currentCount == 0, "m_currentCount should never be negative");
+                    Debug.Assert(m_currentCount == 0, "m_currentCount should never be negative");
                     var asyncWaiter = CreateAndAddAsyncWaiter();
                     return (millisecondsTimeout == Timeout.Infinite && !cancellationToken.CanBeCanceled) ?
                         asyncWaiter :
@@ -651,7 +648,7 @@ namespace System.Threading
         /// <returns>The created task.</returns>
         private TaskNode CreateAndAddAsyncWaiter()
         {
-            Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
+            Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
 
             // Create the task
             var task = new TaskNode();
@@ -659,13 +656,13 @@ namespace System.Threading
             // Add it to the linked list
             if (m_asyncHead == null)
             {
-                Contract.Assert(m_asyncTail == null, "If head is null, so too should be tail");
+                Debug.Assert(m_asyncTail == null, "If head is null, so too should be tail");
                 m_asyncHead = task;
                 m_asyncTail = task;
             }
             else
             {
-                Contract.Assert(m_asyncTail != null, "If head is not null, neither should be tail");
+                Debug.Assert(m_asyncTail != null, "If head is not null, neither should be tail");
                 m_asyncTail.Next = task;
                 task.Prev = m_asyncTail;
                 m_asyncTail = task;
@@ -681,7 +678,7 @@ namespace System.Threading
         private bool RemoveAsyncWaiter(TaskNode task)
         {
             Contract.Requires(task != null, "Expected non-null task");
-            Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
+            Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
 
             // Is the task in the list?  To be in the list, either it's the head or it has a predecessor that's in the list.
             bool wasInList = m_asyncHead == task || task.Prev != null;
@@ -691,7 +688,7 @@ namespace System.Threading
             if (task.Prev != null) task.Prev.Next = task.Next;
             if (m_asyncHead == task) m_asyncHead = task.Next;
             if (m_asyncTail == task) m_asyncTail = task.Prev;
-            Contract.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null");
+            Debug.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null");
 
             // Make sure not to leak
             task.Next = task.Prev = null;
@@ -706,8 +703,8 @@ namespace System.Threading
         /// <returns>The task to return to the caller.</returns>
         private async Task<bool> WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken)
         {
-            Contract.Assert(asyncWaiter != null, "Waiter should have been constructed");
-            Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
+            Debug.Assert(asyncWaiter != null, "Waiter should have been constructed");
+            Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
 
             // Wait until either the task is completed, timeout occurs, or cancellation is requested.
             // We need to ensure that the Task.Delay task is appropriately cleaned up if the await
@@ -812,7 +809,7 @@ namespace System.Threading
                 // waits are canceled, but the wait code path will handle that.
                 if (m_asyncHead != null)
                 {
-                    Contract.Assert(m_asyncTail != null, "tail should not be null if head isn't null");
+                    Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't null");
                     int maxAsyncToRelease = currentCount - waitCount;
                     while (maxAsyncToRelease > 0 && m_asyncHead != null)
                     {
@@ -842,7 +839,6 @@ namespace System.Threading
         /// Queues a waiter task to the ThreadPool. We use this small helper method so that
         /// the larger Release(count) method does not need to be SecuritySafeCritical.
         /// </summary>
-        [SecuritySafeCritical] // for ThreadPool.UnsafeQueueCustomWorkItem
         private static void QueueWaiterTask(TaskNode waiterTask)
         {
             ThreadPool.UnsafeQueueCustomWorkItem(waiterTask, forceGlobal: false);
@@ -896,7 +892,7 @@ namespace System.Threading
         private static void CancellationTokenCanceledEventHandler(object obj)
         {
             SemaphoreSlim semaphore = obj as SemaphoreSlim;
-            Contract.Assert(semaphore != null, "Expected a SemaphoreSlim");
+            Debug.Assert(semaphore != null, "Expected a SemaphoreSlim");
             lock (semaphore.m_lockObj)
             {
                 Monitor.PulseAll(semaphore.m_lockObj); //wake up all waiters.
index 56ff37a..1d90890 100644 (file)
 //
 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 using System;
-using System.Diagnostics;
 using System.Security.Permissions;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
 using System.Runtime.ConstrainedExecution;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Threading
@@ -55,7 +55,6 @@ namespace System.Threading
     /// </para>
     /// </remarks>
     [ComVisible(false)]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     [DebuggerTypeProxy(typeof(SystemThreading_SpinLockDebugView))]
     [DebuggerDisplay("IsHeld = {IsHeld}")]
     public struct SpinLock
@@ -107,7 +106,6 @@ namespace System.Threading
         // The waiters count is calculated by m_owner & WAITERS_MASK 01111....110
         private static int MAXIMUM_WAITERS = WAITERS_MASK;
 
-
         /// <summary>
         /// Initializes a new instance of the <see cref="T:System.Threading.SpinLock"/>
         /// structure with the option to track thread IDs to improve debugging.
@@ -123,11 +121,10 @@ namespace System.Threading
             if (!enableThreadOwnerTracking)
             {
                 m_owner |= LOCK_ID_DISABLE_MASK;
-                Contract.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now");
+                Debug.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now");
             }
         }
 
-
         /// <summary>
         /// Initializes a new instance of the <see cref="T:System.Threading.SpinLock"/>
         /// structure with the option to track thread IDs to improve debugging.
@@ -157,9 +154,6 @@ namespace System.Threading
         /// </exception>
         public void Enter(ref bool lockTaken)
         {
-#if !FEATURE_CORECLR
-            Thread.BeginCriticalRegion();
-#endif
             //Try to keep the code and branching in this method as small as possible in order to inline the method
             int observedOwner = m_owner;
             if (lockTaken || //invalid parameter
@@ -256,10 +250,6 @@ namespace System.Threading
         /// a negative number other than -1, which represents an infinite time-out.</exception>
         public void TryEnter(int millisecondsTimeout, ref bool lockTaken)
         {
-#if !FEATURE_CORECLR
-            Thread.BeginCriticalRegion();
-#endif
-
             int observedOwner = m_owner;
             if (millisecondsTimeout < -1 || //invalid parameter
                 lockTaken || //invalid parameter
@@ -277,10 +267,6 @@ namespace System.Threading
         /// <param name="lockTaken">The lockTaken param</param>
         private void ContinueTryEnter(int millisecondsTimeout, ref bool lockTaken)
         {
-            //Leave the critical region which is entered by the fast path
-#if !FEATURE_CORECLR
-            Thread.EndCriticalRegion();
-#endif
             // The fast path doesn't throw any exception, so we have to validate the parameters here
             if (lockTaken)
             {
@@ -294,20 +280,12 @@ namespace System.Threading
                     nameof(millisecondsTimeout), millisecondsTimeout, Environment.GetResourceString("SpinLock_TryEnter_ArgumentOutOfRange"));
             }
 
-
             uint startTime = 0;
             if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout != 0)
             {
                 startTime = TimeoutHelper.GetTime();
             }
 
-#if !FEATURE_CORECLR
-            if (CdsSyncEtwBCLProvider.Log.IsEnabled())
-            {
-                CdsSyncEtwBCLProvider.Log.SpinLock_FastPathFailed(m_owner);
-            }
-#endif
-
             if (IsThreadOwnerTrackingEnabled)
             {
                 // Slow path for enabled thread tracking mode
@@ -333,19 +311,12 @@ namespace System.Threading
             observedOwner = m_owner;
             if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
             {
-#if !FEATURE_CORECLR
-                Thread.BeginCriticalRegion();
-#endif
-
                 if (Interlocked.CompareExchange(ref m_owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner)
                 {
                     // Aquired lock
                     return;
                 }
 
-#if !FEATURE_CORECLR
-                Thread.EndCriticalRegion();
-#endif
                 if (millisecondsTimeout == 0)
                 {
                     // Did not aquire lock in CompareExchange and timeout is 0 so fail fast
@@ -377,23 +348,15 @@ namespace System.Threading
                     observedOwner = m_owner;
                     if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
                     {
-#if !FEATURE_CORECLR
-                        Thread.BeginCriticalRegion();
-#endif
-
                         int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero
                             observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters
                             : (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
-                        Contract.Assert((newOwner & WAITERS_MASK) >= 0);
+                        Debug.Assert((newOwner & WAITERS_MASK) >= 0);
 
                         if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
                         {
                             return;
                         }
-
-#if !FEATURE_CORECLR
-                        Thread.EndCriticalRegion();
-#endif
                     }
                 }
 
@@ -405,7 +368,6 @@ namespace System.Threading
                 }
             }
 
-
             //*** Step 3, Yielding
             //Sleep(1) every 50 yields
             int yieldsoFar = 0;
@@ -414,22 +376,15 @@ namespace System.Threading
                 observedOwner = m_owner;
                 if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
                 {
-#if !FEATURE_CORECLR
-                    Thread.BeginCriticalRegion();
-#endif
                     int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero
                            observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters
                            : (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
-                    Contract.Assert((newOwner & WAITERS_MASK) >= 0);
+                    Debug.Assert((newOwner & WAITERS_MASK) >= 0);
 
                     if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
                     {
                         return;
                     }
-
-#if !FEATURE_CORECLR
-                    Thread.EndCriticalRegion();
-#endif
                 }
 
                 if (yieldsoFar % SLEEP_ONE_FREQUENCY == 0)
@@ -471,7 +426,7 @@ namespace System.Threading
                 if ((observedOwner & WAITERS_MASK) == 0) return; // don't decrement the waiters if it's corrupted by previous call of Exit(false)
                 if (Interlocked.CompareExchange(ref m_owner, observedOwner - 2, observedOwner) == observedOwner)
                 {
-                    Contract.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped
+                    Debug.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped
                     break;
                 }
                 spinner.SpinOnce();
@@ -484,7 +439,7 @@ namespace System.Threading
         /// </summary>
         private void ContinueTryEnterWithThreadTracking(int millisecondsTimeout, uint startTime, ref bool lockTaken)
         {
-            Contract.Assert(IsThreadOwnerTrackingEnabled);
+            Debug.Assert(IsThreadOwnerTrackingEnabled);
 
             int lockUnowned = 0;
             // We are using thread IDs to mark ownership. Snap the thread ID and check for recursion.
@@ -511,17 +466,10 @@ namespace System.Threading
 
                 if (m_owner == lockUnowned)
                 {
-#if !FEATURE_CORECLR
-                    Thread.BeginCriticalRegion();
-#endif
                     if (Interlocked.CompareExchange(ref m_owner, m_newOwner, lockUnowned, ref lockTaken) == lockUnowned)
                     {
                         return;
                     }
-#if !FEATURE_CORECLR
-                    // The thread failed to get the lock, so we don't need to remain in a critical region.
-                    Thread.EndCriticalRegion();
-#endif
                 }
                 // Check the timeout.  We only RDTSC if the next spin will yield, to amortize the cost.
                 if (millisecondsTimeout == 0 ||
@@ -551,11 +499,6 @@ namespace System.Threading
                 ExitSlowPath(true);
             else
                 Interlocked.Decrement(ref m_owner);
-
-#if !FEATURE_CORECLR
-            Thread.EndCriticalRegion();
-#endif
-
         }
 
         /// <summary>
@@ -587,10 +530,6 @@ namespace System.Threading
             }
             else
                 ExitSlowPath(useMemoryBarrier);
-
-#if !FEATURE_CORECLR
-            Thread.EndCriticalRegion();
-#endif
         }
 
         /// <summary>
index 1888b60..1b31407 100644 (file)
@@ -14,6 +14,7 @@ using System;
 using System.Runtime.ConstrainedExecution;
 using System.Security.Permissions;
 using System.Threading;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Diagnostics.CodeAnalysis;
 
@@ -69,7 +70,6 @@ namespace System.Threading
     /// threads must spin, each should use its own instance of SpinWait.
     /// </para>
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public struct SpinWait
     {
 
@@ -132,10 +132,6 @@ namespace System.Threading
                 // remove the thread from the scheduler's queue for 10+ms, if the system is
                 // configured to use the (default) coarse-grained system timer.
                 //
-
-#if !FEATURE_CORECLR
-                CdsSyncEtwBCLProvider.Log.SpinWait_NextSpinWillYield();
-#endif
                 int yieldsSoFar = (m_count >= YIELD_THRESHOLD ? m_count - YIELD_THRESHOLD : m_count);
 
                 if ((yieldsSoFar % SLEEP_1_EVERY_HOW_MANY_TIMES) == (SLEEP_1_EVERY_HOW_MANY_TIMES - 1))
@@ -197,7 +193,7 @@ namespace System.Threading
 #endif
             SpinUntil(condition, Timeout.Infinite);
 #if DEBUG
-            Contract.Assert(result);
+            Debug.Assert(result);
 #endif
         }
 
@@ -304,7 +300,7 @@ namespace System.Threading
                     s_lastProcessorCountRefreshTicks = now;
                 }
 
-                Contract.Assert(procCount > 0 && procCount <= 64,
+                Debug.Assert(procCount > 0 && procCount <= 64,
                     "Processor count not within the expected range (1 - 64).");
 
                 return procCount;
@@ -345,7 +341,7 @@ namespace System.Threading
         public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout)
         {
             // The function must be called in case the time out is not infinite
-            Contract.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite);
+            Debug.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite);
 
             uint elapsedMilliseconds = (GetTime() - startTime);
 
index a9422c1..5531597 100644 (file)
@@ -24,6 +24,7 @@ namespace System.Threading
     using System.Runtime.ConstrainedExecution;
     using System.Reflection;
     using System.Security;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Diagnostics.CodeAnalysis;
 
@@ -43,17 +44,12 @@ namespace System.Threading
     // I'd like this to be an interface, or at least an abstract class - but neither seems to play nice with FriendAccessAllowed.
     //
     [FriendAccessAllowed]
-    [SecurityCritical]
     internal class WinRTSynchronizationContextFactoryBase
     {
-        [SecurityCritical]
         public virtual SynchronizationContext Create(object coreDispatcher) {return null;}
     }
 #endif //FEATURE_COMINTEROP
 
-#if !FEATURE_CORECLR
-    [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags =SecurityPermissionFlag.ControlPolicy|SecurityPermissionFlag.ControlEvidence)]
-#endif
     public class SynchronizationContext
     {
 #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
@@ -76,7 +72,6 @@ namespace System.Threading
         static Type s_cachedPreparedType5;
 
         // protected so that only the derived sync context class can enable these flags
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")]
         protected void SetWaitNotificationRequired()
         {
@@ -144,7 +139,6 @@ namespace System.Threading
 
 #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
         // Method called when the CLR does a wait operation
-        [System.Security.SecurityCritical]  // auto-generated_required
         [CLSCompliant(false)]
         [PrePrepareMethod]
         public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
@@ -153,7 +147,6 @@ namespace System.Threading
         }
 
         // Method that can be called by Wait overrides
-        [System.Security.SecurityCritical]  // auto-generated_required
         [CLSCompliant(false)]
         [PrePrepareMethod]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
@@ -170,7 +163,6 @@ namespace System.Threading
 
         // Static helper to which the above method can delegate to in order to get the default
         // COM behavior.
-        [System.Security.SecurityCritical]  // auto-generated_required
         [CLSCompliant(false)]
         [PrePrepareMethod]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -178,15 +170,11 @@ namespace System.Threading
         private static extern int WaitHelperNative(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
 #endif
 
-#if FEATURE_CORECLR
-
-        [System.Security.SecurityCritical]
         public static void SetSynchronizationContext(SynchronizationContext syncContext)
         {
             Thread.CurrentThread.SynchronizationContext = syncContext;
         }
 
-        [System.Security.SecurityCritical]
         public static void SetThreadStaticContext(SynchronizationContext syncContext)
         {
             Thread.CurrentThread.SynchronizationContext = syncContext;
@@ -217,56 +205,11 @@ namespace System.Threading
             }
         }
 
-#else //FEATURE_CORECLR
-
-        // set SynchronizationContext on the current thread
-        [System.Security.SecurityCritical]  // auto-generated_required
-        public static void SetSynchronizationContext(SynchronizationContext syncContext)
-        {
-            ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
-            ec.SynchronizationContext = syncContext;
-            ec.SynchronizationContextNoFlow = syncContext;
-        }
-
-        // Get the current SynchronizationContext on the current thread
-        public static SynchronizationContext Current 
-        {
-            get      
-            {
-                return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext ?? GetThreadLocalContext();
-            }
-        }
-
-        // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run)        
-        internal static SynchronizationContext CurrentNoFlow
-        {
-            [FriendAccessAllowed]
-            get
-            {
-                return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContextNoFlow ?? GetThreadLocalContext();
-            }
-        }
-
-        private static SynchronizationContext GetThreadLocalContext()
-        {
-            SynchronizationContext context = null;
-            
-#if FEATURE_APPX
-            if (context == null && AppDomain.IsAppXModel())
-                context = GetWinRTContext();
-#endif
-
-            return context;
-        }
-
-#endif //FEATURE_CORECLR
-
 #if FEATURE_APPX
-        [SecuritySafeCritical]
         private static SynchronizationContext GetWinRTContext()
         {
-            Contract.Assert(Environment.IsWinRTSupported);
-            Contract.Assert(AppDomain.IsAppXModel());
+            Debug.Assert(Environment.IsWinRTSupported);
+            Debug.Assert(AppDomain.IsAppXModel());
     
             //
             // We call into the VM to get the dispatcher.  This is because:
@@ -285,10 +228,8 @@ namespace System.Threading
             return null;
         }
 
-        [SecurityCritical]
         static WinRTSynchronizationContextFactoryBase s_winRTContextFactory;
 
-        [SecurityCritical]
         private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory()
         {
             //
@@ -306,7 +247,6 @@ namespace System.Threading
         }
 
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
-        [SecurityCritical]
         [SuppressUnmanagedCodeSecurity]
         [return: MarshalAs(UnmanagedType.Interface)]
         private static extern object GetWinRTDispatcherForCurrentThread();
@@ -321,7 +261,6 @@ namespace System.Threading
         }
 
 #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
-        [System.Security.SecurityCritical]  // auto-generated
         private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
         {
             return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout);
index c29b11a..ec7c5aa 100644 (file)
@@ -131,7 +131,6 @@ namespace System.Threading.Tasks
         private static Loggers f_LoggingOn; //assumes false by default
 
         // The precise static constructor will run first time somebody attempts to access this class
-        [SecuritySafeCritical]
         static AsyncCausalityTracer()
         {
             if (!Environment.IsWinRTSupported) return;
@@ -153,7 +152,7 @@ namespace System.Threading.Tasks
                 s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory;
 
                 EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler));
-                Contract.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null");
+                Debug.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null");
             }
             catch (Exception ex)
             {
@@ -165,7 +164,6 @@ namespace System.Threading.Tasks
            
         }
 
-        [SecuritySafeCritical]
         private static void TracingStatusChangedHandler(Object sender, WFD.TracingStatusChangedEventArgs args)
         {
             if (args.Enabled)
index 05e6dbf..71eb787 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.IO;
 using System.Runtime.CompilerServices;
@@ -62,9 +63,9 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion {
     /// It expects that an BeginEndAwaitableAdapter instance was supplied to the APM Begin method as the object state.</summary>
     public readonly static AsyncCallback Callback = (asyncResult) => {
 
-        Contract.Assert(asyncResult != null);
-        Contract.Assert(asyncResult.IsCompleted);
-        Contract.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter);
+        Debug.Assert(asyncResult != null);
+        Debug.Assert(asyncResult.IsCompleted);
+        Debug.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter);
 
         // Get the adapter object supplied as the "object state" to the Begin method
         BeginEndAwaitableAdapter adapter = (BeginEndAwaitableAdapter) asyncResult.AsyncState;
@@ -81,7 +82,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion {
         Action continuation = Interlocked.Exchange(ref adapter._continuation, CALLBACK_RAN);
         if (continuation != null) {
         
-            Contract.Assert(continuation != CALLBACK_RAN);
+            Debug.Assert(continuation != CALLBACK_RAN);
             continuation();
         }        
     };
@@ -108,10 +109,9 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion {
 
     /// <summary>Schedules the continuation to run when the operation completes.</summary>
     /// <param name="continuation">The continuation.</param>
-    [SecurityCritical]
     public void UnsafeOnCompleted(Action continuation) {
 
-        Contract.Assert(continuation != null);
+        Debug.Assert(continuation != null);
         OnCompleted(continuation); 
     }
 
@@ -120,7 +120,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion {
     /// <param name="continuation">The continuation.</param>
     public void OnCompleted(Action continuation) {
 
-        Contract.Assert(continuation != null);
+        Debug.Assert(continuation != null);
 
         // If the continuation field is null, then set it to be the target continuation
         // so that when the operation completes, it'll invoke the continuation.  If it's non-null,
@@ -139,7 +139,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion {
     /// <returns>The IAsyncResult for the operation.</returns>
     public IAsyncResult GetResult() {
 
-        Contract.Assert(_asyncResult != null && _asyncResult.IsCompleted);
+        Debug.Assert(_asyncResult != null && _asyncResult.IsCompleted);
 
         // Get the IAsyncResult
         IAsyncResult result = _asyncResult;
index dcf73fa..c7a96b0 100644 (file)
@@ -28,7 +28,6 @@ namespace System.Threading.Tasks
     /// Provides concurrent and exclusive task schedulers that coordinate to execute
     /// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do.
     /// </summary>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     [DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")]
     [DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))]
     public class ConcurrentExclusiveSchedulerPair
@@ -213,13 +212,13 @@ namespace System.Threading.Tasks
                 ThreadPool.QueueUserWorkItem(state =>
                 {
                     var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure
-                    Contract.Assert(!localCs.Task.IsCompleted, "Completion should only happen once.");
+                    Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once.");
 
                     var exceptions = localCs.m_exceptions;
                     bool success = (exceptions != null && exceptions.Count > 0) ?
                         localCs.TrySetException(exceptions) :
                         localCs.TrySetResult(default(VoidTaskResult));
-                    Contract.Assert(success, "Expected to complete completion task.");
+                    Debug.Assert(success, "Expected to complete completion task.");
                 }, cs);
             }
         }
@@ -336,7 +335,7 @@ namespace System.Threading.Tasks
                 // Check to see if all tasks have completed and if completion has been requested.
                 CleanupStateIfCompletingAndQuiesced();
             }
-            else Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0.");
+            else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0.");
         }
 
         /// <summary>
@@ -351,7 +350,7 @@ namespace System.Threading.Tasks
             try
             {
                 // Note that we're processing exclusive tasks on the current thread
-                Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
+                Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
                     "This thread should not yet be involved in this pair's processing.");
                 m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingExclusiveTask;
 
@@ -372,7 +371,7 @@ namespace System.Threading.Tasks
                 // We're no longer processing exclusive tasks on the current thread
                 ProcessingMode currentMode;
                 m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode);
-                Contract.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, 
+                Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, 
                     "Somehow we ended up escaping exclusive mode.");
 
                 lock (ValueLock)
@@ -382,7 +381,7 @@ namespace System.Threading.Tasks
                     // There might be more concurrent tasks available, for example, if concurrent tasks arrived
                     // after we exited the loop, or if we exited the loop while concurrent tasks were still
                     // available but we hit our maxItemsPerTask limit.
-                    Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive.");
+                    Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive.");
                     m_processingCount = 0;
                     ProcessAsyncIfNecessary(true);
                 }
@@ -400,7 +399,7 @@ namespace System.Threading.Tasks
             try
             {
                 // Note that we're processing concurrent tasks on the current thread
-                Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
+                Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
                     "This thread should not yet be involved in this pair's processing.");
                 m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingConcurrentTasks;
 
@@ -432,7 +431,7 @@ namespace System.Threading.Tasks
                 // We're no longer processing concurrent tasks on the current thread
                 ProcessingMode currentMode;
                 m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode);
-                Contract.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks,
+                Debug.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks,
                     "Somehow we ended up escaping concurrent mode.");
 
                 lock (ValueLock)
@@ -442,7 +441,7 @@ namespace System.Threading.Tasks
                     // There might be more concurrent tasks available, for example, if concurrent tasks arrived
                     // after we exited the loop, or if we exited the loop while concurrent tasks were still
                     // available but we hit our maxItemsPerTask limit.
-                    Contract.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent.");
+                    Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent.");
                     if (m_processingCount > 0) --m_processingCount;
                     ProcessAsyncIfNecessary(true);
                 }
@@ -524,10 +523,9 @@ namespace System.Threading.Tasks
 
             /// <summary>Queues a task to the scheduler.</summary>
             /// <param name="task">The task to be queued.</param>
-            [SecurityCritical]
             protected internal override void QueueTask(Task task)
             {
-                Contract.Assert(task != null, "Infrastructure should have provided a non-null task.");
+                Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
                 lock (m_pair.ValueLock)
                 {
                     // If the scheduler has already had completion requested, no new work is allowed to be scheduled
@@ -541,10 +539,9 @@ namespace System.Threading.Tasks
 
             /// <summary>Executes a task on this scheduler.</summary>
             /// <param name="task">The task to be executed.</param>
-            [SecuritySafeCritical]
             internal void ExecuteTask(Task task)
             {
-                Contract.Assert(task != null, "Infrastructure should have provided a non-null task.");
+                Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
                 base.TryExecuteTask(task);
             }
 
@@ -552,10 +549,9 @@ namespace System.Threading.Tasks
             /// <param name="task">The task to execute.</param>
             /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param>
             /// <returns>true if the task could be executed; otherwise, false.</returns>
-            [SecurityCritical]
             protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
             {
-                Contract.Assert(task != null, "Infrastructure should have provided a non-null task.");
+                Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
 
                 // If the scheduler has had completion requested, no new work is allowed to be scheduled.
                 // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because:
@@ -628,7 +624,7 @@ namespace System.Threading.Tasks
                 }
                 catch
                 {
-                    Contract.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception.");
+                    Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception.");
                     var ignored = t.Exception;
                     throw;
                 }
@@ -642,7 +638,6 @@ namespace System.Threading.Tasks
             /// This method is separated out not because of performance reasons but so that
             /// the SecuritySafeCritical attribute may be employed.
             /// </remarks>
-            [SecuritySafeCritical]
             private static bool TryExecuteTaskShim(object state)
             {
                 var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state;
@@ -651,7 +646,6 @@ namespace System.Threading.Tasks
 
             /// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary>
             /// <returns>An enumerable of the tasks queued.</returns>
-            [SecurityCritical]
             protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; }
 
             /// <summary>Gets the number of tasks queued to this scheduler.</summary>
@@ -748,11 +742,11 @@ namespace System.Threading.Tasks
                     exceptionThrown = false;
                 }
                 catch (SynchronizationLockException) { exceptionThrown = true; }
-                Contract.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed.");
+                Debug.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed.");
             }
 #endif
 #else
-            Contract.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
+            Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
 #endif
         }
         
index 838af04..c98e219 100644 (file)
@@ -15,6 +15,7 @@ using System.Security;
 using System.Security.Permissions;
 using System.Runtime.CompilerServices;
 using System.Threading;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.Versioning;
 
@@ -38,7 +39,6 @@ namespace System.Threading.Tasks
     /// <see cref="System.Threading.Tasks.Task{TResult}.Factory">Task{TResult}.Factory</see> property.
     /// </para>
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public class TaskFactory<TResult>
     {
         // Member variables, DefaultScheduler, other properties and ctors 
@@ -841,7 +841,7 @@ namespace System.Threading.Tasks
                 }, state);
                 if (asyncResult.CompletedSynchronously)
                 {
-                    Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                    Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
                     FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
                 }
             }
@@ -962,7 +962,7 @@ namespace System.Threading.Tasks
                 }, state);
                 if (asyncResult.CompletedSynchronously)
                 {
-                    Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                    Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
                     FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
                 }
             }
@@ -1092,7 +1092,7 @@ namespace System.Threading.Tasks
                 }, state);
                 if (asyncResult.CompletedSynchronously)
                 {
-                    Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                    Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
                     FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
                 }
             }
@@ -1229,7 +1229,7 @@ namespace System.Threading.Tasks
                 }, state);
                 if (asyncResult.CompletedSynchronously)
                 {
-                    Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                    Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
                     FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
                 }
             }
@@ -1270,9 +1270,9 @@ namespace System.Threading.Tasks
             where TInstance : class
         {
             // Validate arguments, but only with asserts, as this is an internal only implementation.
-            Contract.Assert(thisRef != null, "Expected a non-null thisRef");
-            Contract.Assert(beginMethod != null, "Expected a non-null beginMethod");
-            Contract.Assert(endMethod != null, "Expected a non-null endMethod");
+            Debug.Assert(thisRef != null, "Expected a non-null thisRef");
+            Debug.Assert(beginMethod != null, "Expected a non-null beginMethod");
+            Debug.Assert(endMethod != null, "Expected a non-null endMethod");
 
             // Create the promise and start the operation.
             // No try/catch is necessary here as we want exceptions to bubble out, and because
@@ -1285,7 +1285,7 @@ namespace System.Threading.Tasks
             // If it completed synchronously, we'll handle that here.
             if (asyncResult.CompletedSynchronously)
             {
-                Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
                 promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: false);
             }
 
@@ -1365,7 +1365,7 @@ namespace System.Threading.Tasks
                 TInstance thisRef, Func<TInstance, IAsyncResult, TResult> endMethod, IAsyncResult asyncResult,
                 bool requiresSynchronization)
             {
-                Contract.Assert(!IsCompleted, "The task should not have been completed yet.");
+                Debug.Assert(!IsCompleted, "The task should not have been completed yet.");
 
                 // Run the end method and complete the task
                 bool successfullySet = false;
@@ -1394,7 +1394,7 @@ namespace System.Threading.Tasks
                 {
                     successfullySet = TrySetException(exc);
                 }
-                Contract.Assert(successfullySet, "Expected the task to not yet be completed");
+                Debug.Assert(successfullySet, "Expected the task to not yet be completed");
             }
         }
 
@@ -1741,7 +1741,7 @@ namespace System.Threading.Tasks
             }
             else
             {
-                Contract.Assert(continuationAction != null);
+                Debug.Assert(continuationAction != null);
 
                 return starter.ContinueWith<TResult>(
                    // use a cached delegate
@@ -1794,7 +1794,7 @@ namespace System.Threading.Tasks
             }
             else
             {
-                Contract.Assert(continuationAction != null);
+                Debug.Assert(continuationAction != null);
                 return starter.ContinueWith<TResult>(
                     //the following delegate avoids closure capture as much as possible
                     //completedTasks.Result == tasksCopy;
@@ -2140,7 +2140,7 @@ namespace System.Threading.Tasks
             }
             else
             {
-                Contract.Assert(continuationAction != null);
+                Debug.Assert(continuationAction != null);
                 return starter.ContinueWith<TResult>(
                     //the following delegate avoids closure capture as much as possible
                     //completedTask.Result is the winning task; state == continuationAction
@@ -2186,7 +2186,7 @@ namespace System.Threading.Tasks
             }
             else
             {
-                Contract.Assert(continuationAction != null);
+                Debug.Assert(continuationAction != null);
                 return starter.ContinueWith<TResult>(
                     // Use a cached delegate
                     GenericDelegateCache<TAntecedentResult,TResult>.CWAnyActionDelegate,
index 914c7bf..7808943 100644 (file)
@@ -142,7 +142,6 @@ namespace System.Threading.Tasks
     /// The <see cref="T:System.Threading.Tasks.Parallel"/> class provides library-based data parallel replacements
     /// for common operations such as for loops, for each loops, and execution of a set of statements.
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public static class Parallel
     {
         // static counter for generating unique Fork/Join Context IDs to be used in ETW events
@@ -1031,9 +1030,9 @@ namespace System.Threading.Tasks
             Func<int, ParallelLoopState, TLocal, TLocal> bodyWithLocal,
             Func<TLocal> localInit, Action<TLocal> localFinally)
         {
-            Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
+            Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
                 "expected exactly one body function to be supplied");
-            Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
+            Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
                 "thread local functions should only be supplied for loops w/ thread local bodies");
 
             // Instantiate our result.  Specifics will be filled in later.
@@ -1157,12 +1156,12 @@ namespace System.Threading.Tasks
 
                             if (bodyWithState != null)
                             {
-                                Contract.Assert(sharedPStateFlags != null);
+                                Debug.Assert(sharedPStateFlags != null);
                                 state = new ParallelLoopState32(sharedPStateFlags);
                             }
                             else if (bodyWithLocal != null)
                             {
-                                Contract.Assert(sharedPStateFlags != null);
+                                Debug.Assert(sharedPStateFlags != null);
                                 state = new ParallelLoopState32(sharedPStateFlags);
                                 if (localInit != null)
                                 {
@@ -1346,9 +1345,9 @@ namespace System.Threading.Tasks
             Func<long, ParallelLoopState, TLocal, TLocal> bodyWithLocal,
             Func<TLocal> localInit, Action<TLocal> localFinally)
         {
-            Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
+            Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
                 "expected exactly one body function to be supplied");
-            Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
+            Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
                 "thread local functions should only be supplied for loops w/ thread local bodies");
 
             // Instantiate our result.  Specifics will be filled in later.
@@ -1471,12 +1470,12 @@ namespace System.Threading.Tasks
 
                         if (bodyWithState != null)
                         {
-                            Contract.Assert(sharedPStateFlags != null);
+                            Debug.Assert(sharedPStateFlags != null);
                             state = new ParallelLoopState64(sharedPStateFlags);
                         }
                         else if (bodyWithLocal != null)
                         {
-                            Contract.Assert(sharedPStateFlags != null);
+                            Debug.Assert(sharedPStateFlags != null);
                             state = new ParallelLoopState64(sharedPStateFlags);
 
                             // If a thread-local selector was supplied, invoke it. Otherwise, use the default.
@@ -2214,10 +2213,10 @@ namespace System.Threading.Tasks
             Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
             Func<TLocal> localInit, Action<TLocal> localFinally)
         {
-            Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
+            Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
                 (bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1,
                 "expected exactly one body function to be supplied");
-            Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
+            Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
                 "thread local functions should only be supplied for loops w/ thread local bodies");
 
             // Before getting started, do a quick peek to see if we have been canceled already
@@ -2278,8 +2277,8 @@ namespace System.Threading.Tasks
             Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
             Func<TLocal> localInit, Action<TLocal> localFinally)
         {
-            Contract.Assert(array != null);
-            Contract.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null");
+            Debug.Assert(array != null);
+            Debug.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null");
 
             int from = array.GetLowerBound(0);
             int to = array.GetUpperBound(0) + 1;
@@ -2337,8 +2336,8 @@ namespace System.Threading.Tasks
             Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
             Func<TLocal> localInit, Action<TLocal> localFinally)
         {
-            Contract.Assert(list != null);
-            Contract.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null");
+            Debug.Assert(list != null);
+            Debug.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null");
 
             if (body != null)
             {
@@ -3191,14 +3190,14 @@ namespace System.Threading.Tasks
             Func<TLocal> localInit,
             Action<TLocal> localFinally)
         {
-            Contract.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
+            Debug.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
                 (bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1,
                 "PartitionForEach: expected exactly one body function to be supplied");
-            Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
+            Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
                 "PartitionForEach: thread local functions should only be supplied for loops w/ thread local bodies");
 
             OrderablePartitioner<TSource> orderedSource = source as OrderablePartitioner<TSource>;
-            Contract.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null),
+            Debug.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null),
                 "PartitionForEach: bodies with indices are only allowable for OrderablePartitioner");
 
             if (!source.SupportsDynamicPartitions)
@@ -3401,7 +3400,7 @@ namespace System.Threading.Tasks
                             else if (bodyWithStateAndLocal != null)
                                 localValue = bodyWithStateAndLocal(t, state, localValue);
                             else
-                                Contract.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler");
+                                Debug.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler");
 
 
                             // Any break, stop or exception causes us to halt
@@ -3576,7 +3575,7 @@ namespace System.Threading.Tasks
 
             public bool LimitExceeded()
             {
-                Contract.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere");
+                Debug.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere");
 
                 // comparing against the next expected time saves an addition operation here
                 // Also we omit the comparison for wrap around here. The only side effect is one extra early yield every 38 days.
index 4db3a9d..6a62cf8 100644 (file)
@@ -26,7 +26,6 @@ namespace System.Threading.Tasks
     /// Enables iterations of <see cref="T:System.Threading.Tasks.Parallel"/> loops to interact with
     /// other iterations.
     /// </summary>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     [DebuggerDisplay("ShouldExitCurrentIteration = {ShouldExitCurrentIteration}")]
     public class ParallelLoopState
     {
@@ -47,7 +46,7 @@ namespace System.Threading.Tasks
         { 
             get 
             { 
-                Contract.Assert(false);
+                Debug.Assert(false);
                 throw new NotSupportedException(
                     Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
             } 
@@ -104,7 +103,7 @@ namespace System.Threading.Tasks
         {
             get
             {
-                Contract.Assert(false);
+                Debug.Assert(false);
                 throw new NotSupportedException(
                     Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
             }
@@ -152,7 +151,7 @@ namespace System.Threading.Tasks
         // Internal/virtual support for Break().
         internal virtual void InternalBreak()
         {
-            Contract.Assert(false);
+            Debug.Assert(false);
             throw new NotSupportedException(
                     Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
         }
index c4b66c4..49f61a6 100644 (file)
@@ -12,6 +12,7 @@
 
 using System;
 using System.Threading;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 #pragma warning disable 0420
@@ -160,7 +161,7 @@ namespace System.Threading.Tasks
 
             bool bRetVal = FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal);
 
-            Contract.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) &&
+            Debug.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) &&
                             (nToExclusiveLocal <= Int32.MaxValue) && (nToExclusiveLocal >= Int32.MinValue));
             
             // convert to 32 bit before returning
@@ -218,7 +219,7 @@ namespace System.Threading.Tasks
             //
             // find the actual number of index ranges we will need
             //
-            Contract.Assert((uSpan / uRangeSize) < Int32.MaxValue);
+            Debug.Assert((uSpan / uRangeSize) < Int32.MaxValue);
 
             int nNumRanges = (int)(uSpan / uRangeSize);
             
@@ -251,7 +252,7 @@ namespace System.Threading.Tasks
                     nCurrentIndex > nToExclusive)
                 {
                     // this should only happen at the last index
-                    Contract.Assert(i == nNumRanges - 1);
+                    Debug.Assert(i == nNumRanges - 1);
 
                     nCurrentIndex = nToExclusive;
                 }
@@ -267,7 +268,7 @@ namespace System.Threading.Tasks
         /// </summary>
         internal RangeWorker RegisterNewWorker()
         {
-            Contract.Assert(m_indexRanges != null && m_indexRanges.Length != 0);
+            Debug.Assert(m_indexRanges != null && m_indexRanges.Length != 0);
 
             int nInitialRange = (Interlocked.Increment(ref m_nCurrentIndexRangeToAssign) - 1) % m_indexRanges.Length;
 
index 462ee0a..6b9dfbb 100644 (file)
@@ -140,10 +140,10 @@ namespace System.Threading.Tasks
         internal SingleProducerSingleConsumerQueue()
         {
             // Validate constants in ctor rather than in an explicit cctor that would cause perf degradation
-            Contract.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0.");
-            Contract.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2");
-            Contract.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum.");
-            Contract.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur.");
+            Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0.");
+            Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2");
+            Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum.");
+            Debug.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur.");
 
             // Initialize the queue
             m_head = m_tail = new Segment(INIT_SEGMENT_SIZE);
@@ -183,7 +183,7 @@ namespace System.Threading.Tasks
             }
 
             int newSegmentSize = m_tail.m_array.Length << 1; // double size
-            Contract.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow.");
+            Debug.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow.");
             if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE;
 
             var newSegment = new Segment(newSegmentSize);
@@ -456,7 +456,7 @@ namespace System.Threading.Tasks
         /// <remarks>The Count is not thread safe, so we need to acquire the lock.</remarks>
         int IProducerConsumerQueue<T>.GetCountSafe(object syncObj)
         {
-            Contract.Assert(syncObj != null, "The syncObj parameter is null.");
+            Debug.Assert(syncObj != null, "The syncObj parameter is null.");
             lock (syncObj)
             {
                 return Count;
index 5f79f30..325aa91 100644 (file)
@@ -216,7 +216,6 @@ namespace System.Threading.Tasks
         /// <param name="OperationType">The kind of fork/join operation.</param>
         /// <param name="InclusiveFrom">The lower bound of the loop.</param>
         /// <param name="ExclusiveTo">The upper bound of the loop.</param>
-        [SecuritySafeCritical]
         [Event(PARALLELLOOPBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive, 
          Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Start)]        
         public void ParallelLoopBegin(
@@ -261,7 +260,6 @@ namespace System.Threading.Tasks
         /// <param name="OriginatingTaskID">The task ID.</param>
         /// <param name="ForkJoinContextID">The loop ID.</param>
         /// <param name="TotalIterations">the total number of iterations processed.</param>
-        [SecuritySafeCritical]
         [Event(PARALLELLOOPEND_ID, Level = EventLevel.Informational, Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Stop)]
         public void ParallelLoopEnd(
             int OriginatingTaskSchedulerID, int OriginatingTaskID,  // PFX_COMMON_EVENT_HEADER
@@ -298,7 +296,6 @@ namespace System.Threading.Tasks
         /// <param name="ForkJoinContextID">The invoke ID.</param>
         /// <param name="OperationType">The kind of fork/join operation.</param>
         /// <param name="ActionCount">The number of actions being invoked.</param>
-        [SecuritySafeCritical]
         [Event(PARALLELINVOKEBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive, 
          Task = TplEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Start)]
         public void ParallelInvokeBegin(
@@ -412,7 +409,6 @@ namespace System.Threading.Tasks
         /// <param name="TaskID">The task ID.</param>
         /// <param name="CreatingTaskID">The task ID</param>
         /// <param name="TaskCreationOptions">The options used to create the task.</param>
-        [SecuritySafeCritical]
         [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version=1, Opcode = EventOpcode.Send, 
          Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
         public void TaskScheduled(
@@ -475,7 +471,6 @@ namespace System.Threading.Tasks
         /// <param name="OriginatingTaskID">The task ID.</param>
         /// <param name="TaskID">The task ID.</param>
         /// <param name="IsExceptional">Whether the task completed due to an error.</param>
-        [SecuritySafeCritical]
         [Event(TASKCOMPLETED_ID, Version=1, 
          Level = EventLevel.Informational, Keywords = Keywords.TaskStops)]
         public void TaskCompleted(
@@ -513,7 +508,6 @@ namespace System.Threading.Tasks
         /// <param name="ContinueWithTaskID">If known, if 'TaskID' has a 'continueWith' task, mention give its ID here.  
         ///      0 means unknown.   This allows better visualization of the common sequential chaining case.</param>
         /// </summary>
-        [SecuritySafeCritical]
         [Event(TASKWAITBEGIN_ID, Version=3, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Send, 
          Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
         public void TaskWaitBegin(
@@ -600,7 +594,6 @@ namespace System.Threading.Tasks
         /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
         /// <param name="OriginatingTaskID">The task ID.</param>
         /// <param name="TaskID">The activityId for the continuation.</param>
-        [SecuritySafeCritical]
         [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send, 
          Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
         public void AwaitTaskContinuationScheduled(
@@ -629,7 +622,6 @@ namespace System.Threading.Tasks
             }
         }
 
-        [SecuritySafeCritical]
         [Event(TRACEOPERATIONSTART_ID, Version=1, 
          Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)]
         public void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext)
@@ -655,7 +647,6 @@ namespace System.Threading.Tasks
             }                
         }
 
-        [SecuritySafeCritical]
         [Event(TRACEOPERATIONRELATION_ID, Version=1,
          Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityRelation)]
         public void TraceOperationRelation(int TaskID, CausalityRelation Relation)
@@ -664,7 +655,6 @@ namespace System.Threading.Tasks
                 WriteEvent(TRACEOPERATIONRELATION_ID, TaskID,(int) Relation);                // optmized overload for this exists
         }
 
-        [SecuritySafeCritical]
         [Event(TRACEOPERATIONSTOP_ID, Version=1, 
          Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)]
         public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status)
@@ -673,7 +663,6 @@ namespace System.Threading.Tasks
                 WriteEvent(TRACEOPERATIONSTOP_ID, TaskID,(int) Status);                     // optmized overload for this exists
         }
 
-        [SecuritySafeCritical]
         [Event(TRACESYNCHRONOUSWORKSTART_ID, Version=1, 
          Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)]
         public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work)
@@ -682,7 +671,6 @@ namespace System.Threading.Tasks
                 WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID,(int) Work);               // optmized overload for this exists
         }
 
-        [SecuritySafeCritical]
         [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version=1, 
          Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)]
         public void TraceSynchronousWorkEnd(CausalitySynchronousWork Work)
index c48d3c4..cf081f7 100644 (file)
@@ -137,7 +137,6 @@ namespace System.Threading.Tasks
     /// InternalWait method serves a potential marker for when a Task is entering a wait operation.
     /// </para>
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     [DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskDebugView))]
     [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")]
     public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable
@@ -339,7 +338,7 @@ namespace System.Threading.Tasks
         // (action,TCO).  It should always be true.
         internal Task(object state, TaskCreationOptions creationOptions, bool promiseStyle)
         {
-            Contract.Assert(promiseStyle, "Promise CTOR: promiseStyle was false");
+            Debug.Assert(promiseStyle, "Promise CTOR: promiseStyle was false");
 
             // Check the creationOptions. We allow the AttachedToParent option to be specified for promise tasks.
             // Also allow RunContinuationsAsynchronously because this is the constructor called by TCS
@@ -609,7 +608,7 @@ namespace System.Threading.Tasks
                               InternalTaskOptions.ContinuationTask |
                               InternalTaskOptions.LazyCancellation |
                               InternalTaskOptions.QueuedByRuntime));
-            Contract.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
+            Debug.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
 #endif
 
             // Throw exception if the user specifies both LongRunning and SelfReplicating
@@ -620,8 +619,8 @@ namespace System.Threading.Tasks
             }
 
             // Assign options to m_stateAndOptionsFlag.
-            Contract.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
-            Contract.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
+            Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
+            Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
             var tmpFlags = (int)creationOptions | (int)internalOptions;
             if ((m_action == null) || ((internalOptions & InternalTaskOptions.ContinuationTask) != 0))
             {
@@ -649,7 +648,7 @@ namespace System.Threading.Tasks
             // we need to do this as the very last thing in the construction path, because the CT registration could modify m_stateFlags
             if (cancellationToken.CanBeCanceled)
             {
-                Contract.Assert((internalOptions &
+                Debug.Assert((internalOptions &
                     (InternalTaskOptions.ChildReplica | InternalTaskOptions.SelfReplicating | InternalTaskOptions.ContinuationTask)) == 0,
                     "TaskConstructorCore: Did not expect to see cancelable token for replica/replicating or continuation task.");
 
@@ -743,7 +742,7 @@ namespace System.Threading.Tasks
                     antecedentTask.RemoveContinuation(continuation);
                 }
             }
-            Contract.Assert(targetTask != null,
+            Debug.Assert(targetTask != null,
                 "targetTask should have been non-null, with the supplied argument being a task or a tuple containing one");
             targetTask.InternalCancel(false);
         }
@@ -764,10 +763,9 @@ namespace System.Threading.Tasks
         /// </summary>
         /// <param name="stackMark">A stack crawl mark pointing to the frame of the caller.</param>
 
-        [SecuritySafeCritical]
         internal void PossiblyCaptureContext(ref StackCrawlMark stackMark)
         {
-            Contract.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null,
+            Debug.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null,
                 "Captured an ExecutionContext when one was already captured.");
 
             // In the legacy .NET 3.5 build, we don't have the optimized overload of Capture()
@@ -791,7 +789,7 @@ namespace System.Threading.Tasks
         // a read of the volatile m_stateFlags field.
         internal static TaskCreationOptions OptionsMethod(int flags)
         {
-            Contract.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get");
+            Debug.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get");
             return (TaskCreationOptions)(flags & OptionsMask);
         }
 
@@ -841,7 +839,7 @@ namespace System.Threading.Tasks
         /// <param name="enabled">true to set the bit; false to unset the bit.</param>
         internal void SetNotificationForWaitCompletion(bool enabled)
         {
-            Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0,
+            Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0,
                 "Should only be used for promise-style tasks"); // hasn't been vetted on other kinds as there hasn't been a need
 
             if (enabled)
@@ -849,7 +847,7 @@ namespace System.Threading.Tasks
                 // Atomically set the END_AWAIT_NOTIFICATION bit
                 bool success = AtomicStateUpdate(TASK_STATE_WAIT_COMPLETION_NOTIFICATION,
                                   TASK_STATE_COMPLETED_MASK | TASK_STATE_COMPLETION_RESERVED);
-                Contract.Assert(success, "Tried to set enabled on completed Task");
+                Debug.Assert(success, "Tried to set enabled on completed Task");
             }
             else
             {
@@ -886,7 +884,7 @@ namespace System.Threading.Tasks
         /// <returns>true if any of the tasks require notification; otherwise, false.</returns>
         internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task[] tasks)
         {
-            Contract.Assert(tasks != null, "Expected non-null array of tasks");
+            Debug.Assert(tasks != null, "Expected non-null array of tasks");
             foreach (var task in tasks)
             {
                 if (task != null &&
@@ -926,7 +924,7 @@ namespace System.Threading.Tasks
                 // bit was unset between the time that it was checked and this method was called.
                 // It's so remote a chance that it's worth having the assert to protect against misuse.
                 bool isWaitNotificationEnabled = IsWaitNotificationEnabled;
-                Contract.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
+                Debug.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
                 return isWaitNotificationEnabled;
             }
         }
@@ -946,7 +944,7 @@ namespace System.Threading.Tasks
             // It's theoretically possible but extremely rare that this assert could fire because the 
             // bit was unset between the time that it was checked and this method was called.
             // It's so remote a chance that it's worth having the assert to protect against misuse.
-            Contract.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
+            Debug.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
 
             // Now that we're notifying the debugger, clear the bit.  The debugger should do this anyway,
             // but this adds a bit of protection in case it fails to, and given that the debugger is involved, 
@@ -991,7 +989,7 @@ namespace System.Threading.Tasks
         /// </summary>
         internal void AddNewChild()
         {
-            Contract.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context");
+            Debug.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context");
 
             var props = EnsureContingentPropertiesInitialized();
 
@@ -1014,10 +1012,10 @@ namespace System.Threading.Tasks
         // We need to subtract that child from m_completionCountdown, or the parent will never complete.
         internal void DisregardChild()
         {
-            Contract.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context");
+            Debug.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context");
 
             var props = EnsureContingentPropertiesInitialized();
-            Contract.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2");
+            Debug.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2");
             Interlocked.Decrement(ref props.m_completionCountdown);
         }
 
@@ -1161,7 +1159,6 @@ namespace System.Threading.Tasks
         //
         // Internal version of RunSynchronously that allows not waiting for completion.
         // 
-        [SecuritySafeCritical] // Needed for QueueTask
         internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForCompletion)
         {
             Contract.Requires(scheduler != null, "Task.InternalRunSynchronously(): null TaskScheduler");
@@ -1235,7 +1232,7 @@ namespace System.Threading.Tasks
                         // Mark ourselves as "handled" to avoid crashing the finalizer thread if the caller neglects to
                         // call Wait() on this task.
                         // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException()
-                        Contract.Assert(
+                        Debug.Assert(
                             (m_contingentProperties != null) &&
                             (m_contingentProperties.m_exceptionsHolder != null) &&
                             (m_contingentProperties.m_exceptionsHolder.ContainsFaultList),
@@ -1252,7 +1249,7 @@ namespace System.Threading.Tasks
             }
             else
             {
-                Contract.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set");
+                Debug.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set");
                 // Can't call this method on canceled task.
                 ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_TaskCompleted);
             }
@@ -1403,7 +1400,7 @@ namespace System.Threading.Tasks
                 // Only return an exception in faulted state (skip manufactured exceptions)
                 // A "benevolent" race condition makes it possible to return null when IsFaulted is
                 // true (i.e., if IsFaulted is set just after the check to IsFaulted above).
-                Contract.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted");
+                Debug.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted");
 
                 return e;
             }
@@ -1884,11 +1881,10 @@ namespace System.Threading.Tasks
         /// underneath us.  If false, TASK_STATE_STARTED bit is OR-ed right in.  This
         /// allows us to streamline things a bit for StartNew(), where competing cancellations
         /// are not a problem.</param>
-        [SecuritySafeCritical] // Needed for QueueTask
         internal void ScheduleAndStart(bool needsProtection)
         {
-            Contract.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected");
-            Contract.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started");
+            Debug.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected");
+            Debug.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started");
 
             // Set the TASK_STATE_STARTED bit
             if (needsProtection)
@@ -1942,7 +1938,7 @@ namespace System.Threading.Tasks
                 if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0)
                 {
                     // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException()
-                    Contract.Assert(
+                    Debug.Assert(
                         (m_contingentProperties != null) &&
                         (m_contingentProperties.m_exceptionsHolder != null) &&
                         (m_contingentProperties.m_exceptionsHolder.ContainsFaultList),
@@ -1981,13 +1977,13 @@ namespace System.Threading.Tasks
             var eoAsEdi = exceptionObject as ExceptionDispatchInfo;
             var eoAsEnumerableEdi = exceptionObject as IEnumerable<ExceptionDispatchInfo>;
 
-            Contract.Assert(
+            Debug.Assert(
                 eoAsException != null || eoAsEnumerableException != null || eoAsEdi != null || eoAsEnumerableEdi != null,
                 "Task.AddException: Expected an Exception, ExceptionDispatchInfo, or an IEnumerable<> of one of those");
 
             var eoAsOce = exceptionObject as OperationCanceledException;
 
-            Contract.Assert(
+            Debug.Assert(
                 !representsCancellation ||
                 eoAsOce != null ||
                 (eoAsEdi != null && eoAsEdi.SourceException is OperationCanceledException),
@@ -2078,7 +2074,7 @@ namespace System.Threading.Tasks
             {
                 // There are exceptions; get the aggregate and optionally add the canceled
                 // exception to the aggregate (if applicable).
-                Contract.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null
+                Debug.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null
 
                 // No need to lock around this, as other logic prevents the consumption of exceptions
                 // before they have been completely processed.
@@ -2097,7 +2093,7 @@ namespace System.Threading.Tasks
         internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos()
         {
             bool exceptionsAvailable = IsFaulted && ExceptionRecorded;
-            Contract.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions.");
+            Debug.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions.");
             return exceptionsAvailable ?
                 m_contingentProperties.m_exceptionsHolder.GetExceptionDispatchInfos() :
                 new ReadOnlyCollection<ExceptionDispatchInfo>(new ExceptionDispatchInfo[0]);
@@ -2107,7 +2103,7 @@ namespace System.Threading.Tasks
         /// <returns>The ExceptionDispatchInfo.  May be null if no OCE was stored for the task.</returns>
         internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo()
         {
-            Contract.Assert(IsCanceled, "Must only be used when the task has canceled.");
+            Debug.Assert(IsCanceled, "Must only be used when the task has canceled.");
             return Volatile.Read(ref m_contingentProperties)?.m_exceptionsHolder?.GetCancellationExceptionDispatchInfo(); // may be null
         }
 
@@ -2344,7 +2340,7 @@ namespace System.Threading.Tasks
             Contract.Requires(childTask != null);
             Contract.Requires(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task");
 
-            Contract.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task");
+            Debug.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task");
 
             var props = Volatile.Read(ref m_contingentProperties);
 
@@ -2404,11 +2400,11 @@ namespace System.Threading.Tasks
                     {
                         // Ensure any exceptions thrown by children are added to the parent.
                         // In doing this, we are implicitly marking children as being "handled".
-                        Contract.Assert(task.IsCompleted, "Expected all tasks in list to be completed");
+                        Debug.Assert(task.IsCompleted, "Expected all tasks in list to be completed");
                         if (task.IsFaulted && !task.IsExceptionObservedByParent)
                         {
                             TaskExceptionHolder exceptionHolder = Volatile.Read(ref task.m_contingentProperties).m_exceptionsHolder;
-                            Contract.Assert(exceptionHolder != null);
+                            Debug.Assert(exceptionHolder != null);
 
                             // No locking necessary since child task is finished adding exceptions
                             // and concurrent CreateExceptionObject() calls do not constitute
@@ -2435,7 +2431,7 @@ namespace System.Threading.Tasks
         /// <param name="delegateRan">Whether the delegate was executed.</param>
         internal void FinishThreadAbortedTask(bool bTAEAddedToExceptionHolder, bool delegateRan)
         {
-            Contract.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null,
+            Debug.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null,
                             "FinishThreadAbortedTask() called on a task whose exception holder wasn't initialized");
 
             // this will only be false for non-root self replicating task copies, because all of their exceptions go to the root task.
@@ -2671,7 +2667,6 @@ namespace System.Threading.Tasks
         /// IThreadPoolWorkItem override, which is the entry function for this task when the TP scheduler decides to run it.
         /// 
         /// </summary>
-        [SecurityCritical]
         void IThreadPoolWorkItem.ExecuteWorkItem()
         {
             ExecuteEntry(false);
@@ -2681,7 +2676,6 @@ namespace System.Threading.Tasks
         /// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem.  This may occur
         /// before Task would otherwise be able to observe it.  
         /// </summary>
-        [SecurityCritical]
         void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
         {
             // If the task has marked itself as Completed, then it either a) already observed this exception (so we shouldn't handle it here)
@@ -2700,7 +2694,6 @@ namespace System.Threading.Tasks
         /// </summary>
         /// <param name="bPreventDoubleExecution"> Performs atomic updates to prevent double execution. Should only be set to true
         /// in codepaths servicing user provided TaskSchedulers. The ConcRT or ThreadPool schedulers don't need this. </param>
-        [SecuritySafeCritical]
         internal bool ExecuteEntry(bool bPreventDoubleExecution)
         {
             if (bPreventDoubleExecution || ((Options & (TaskCreationOptions)InternalTaskOptions.SelfReplicating) != 0))
@@ -2742,7 +2735,6 @@ namespace System.Threading.Tasks
         }
 
         // A trick so we can refer to the TLS slot with a byref.
-        [SecurityCritical]
         private void ExecuteWithThreadLocal(ref Task currentTaskSlot)
         {
             // Remember the current task so we can restore it after running, and then
@@ -2819,14 +2811,12 @@ namespace System.Threading.Tasks
         }
 
         // Cached callback delegate that's lazily initialized due to ContextCallback being SecurityCritical
-        [SecurityCritical]
         private static ContextCallback s_ecCallback;
 
-        [SecurityCritical]
         private static void ExecutionContextCallback(object obj)
         {
             Task task = obj as Task;
-            Contract.Assert(task != null, "expected a task object");
+            Debug.Assert(task != null, "expected a task object");
             task.Execute();
         }
 
@@ -2837,7 +2827,7 @@ namespace System.Threading.Tasks
         internal virtual void InnerInvoke()
         {
             // Invoke the delegate
-            Contract.Assert(m_action != null, "Null action in InnerInvoke()");
+            Debug.Assert(m_action != null, "Null action in InnerInvoke()");
             var action = m_action as Action;
             if (action != null)
             {
@@ -2850,7 +2840,7 @@ namespace System.Threading.Tasks
                 actionWithState(m_stateObject);
                 return;
             }
-            Contract.Assert(false, "Invalid m_action in Task");
+            Debug.Assert(false, "Invalid m_action in Task");
         }
 
         /// <summary>
@@ -2929,7 +2919,6 @@ namespace System.Threading.Tasks
         /// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param>
         /// <param name="stackMark">A stack crawl mark tied to execution context.</param>
         /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
-        [SecurityCritical]
         internal void SetContinuationForAwait(
             Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext, ref StackCrawlMark stackMark)
         {
@@ -2986,7 +2975,7 @@ namespace System.Threading.Tasks
             }
             else
             {
-                Contract.Assert(!flowExecutionContext, "We already determined we're not required to flow context.");
+                Debug.Assert(!flowExecutionContext, "We already determined we're not required to flow context.");
                 if (!AddTaskContinuation(continuationAction, addBeforeOthers: false))
                     AwaitTaskContinuation.UnsafeScheduleAction(continuationAction, this);
             }
@@ -3019,7 +3008,7 @@ namespace System.Threading.Tasks
             Wait(Timeout.Infinite, default(CancellationToken));
 
 #if DEBUG
-            Contract.Assert(waitResult, "expected wait to succeed");
+            Debug.Assert(waitResult, "expected wait to succeed");
 #endif
         }
 
@@ -3154,7 +3143,7 @@ namespace System.Threading.Tasks
                 ThrowIfExceptional(true);
             }
 
-            Contract.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state.");
+            Debug.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state.");
 
             return true;
         }
@@ -3230,7 +3219,7 @@ namespace System.Threading.Tasks
                 }
             }
 
-            Contract.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite);
+            Debug.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite);
 
             // ETW event for Task Wait End
             if (etwIsEnabled)
@@ -3358,7 +3347,6 @@ namespace System.Threading.Tasks
         /// For custom schedulers we also attempt an atomic state transition.
         /// </param>
         /// <returns>true if the task was successfully canceled; otherwise, false.</returns>
-        [SecuritySafeCritical]
         internal bool InternalCancel(bool bCancelNonExecutingOnly)
         {
             Contract.Requires((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) == 0, "Task.InternalCancel() did not expect promise-style task");
@@ -3426,7 +3414,7 @@ namespace System.Threading.Tasks
                 if (bPopSucceeded)
                 {
                     // hitting this would mean something wrong with the AtomicStateUpdate above
-                    Contract.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()");
+                    Debug.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()");
 
                     // Include TASK_STATE_DELEGATE_INVOKED in "illegal" bits to protect against the situation where
                     // TS.TryDequeue() returns true but the task is still left on the queue.
@@ -3466,8 +3454,8 @@ namespace System.Threading.Tasks
         {
             RecordInternalCancellationRequest();
 
-            Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task");
-            Contract.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken));
+            Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task");
+            Debug.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken));
 
             // Store the supplied cancellation token as this task's token.
             // Waiting on this task will then result in an OperationCanceledException containing this token.
@@ -3492,11 +3480,11 @@ namespace System.Threading.Tasks
                 if (oce == null)
                 {
                     var edi = cancellationException as ExceptionDispatchInfo;
-                    Contract.Assert(edi != null, "Expected either an OCE or an EDI");
+                    Debug.Assert(edi != null, "Expected either an OCE or an EDI");
                     oce = edi.SourceException as OperationCanceledException;
-                    Contract.Assert(oce != null, "Expected EDI to contain an OCE");
+                    Debug.Assert(oce != null, "Expected EDI to contain an OCE");
                 }
-                Contract.Assert(oce.CancellationToken == tokenToRecord, 
+                Debug.Assert(oce.CancellationToken == tokenToRecord, 
                                 "Expected OCE's token to match the provided token.");
 #endif
                 AddException(cancellationException, representsCancellation: true);
@@ -3507,10 +3495,10 @@ namespace System.Threading.Tasks
         // And this method should be called at most once per task.
         internal void CancellationCleanupLogic()
         {
-            Contract.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved.");
+            Debug.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved.");
             // I'd like to do this, but there is a small window for a race condition.  If someone calls Wait() between InternalCancel() and
             // here, that will set m_completionEvent, leading to a meaningless/harmless assertion.
-            //Contract.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set.");
+            //Debug.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set.");
 
             // This may have been set already, but we need to make sure.
             Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED);
@@ -3541,8 +3529,8 @@ namespace System.Threading.Tasks
         /// </summary>    
         private void SetCancellationAcknowledged()
         {
-            Contract.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task");
-            Contract.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled");
+            Debug.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task");
+            Debug.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled");
 
             m_stateFlags |= TASK_STATE_CANCELLATIONACKNOWLEDGED;
         }
@@ -3558,7 +3546,6 @@ namespace System.Threading.Tasks
         /// <summary>
         /// Runs all of the continuations, as appropriate.
         /// </summary>
-        [SecuritySafeCritical] // for AwaitTaskContinuation.RunOrScheduleAction
         internal void FinishContinuations()
         {
             // Atomically store the fact that this task is completing.  From this point on, the adding of continuations will
@@ -3684,7 +3671,7 @@ namespace System.Threading.Tasks
                         // Otherwise, it must be an ITaskCompletionAction, so invoke it.
                         else
                         {
-                            Contract.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction");
+                            Debug.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction");
                             var action = (ITaskCompletionAction)currentContinuation;
 
                             if (bCanInlineContinuations || !action.InvokeMayRunArbitraryCode)
@@ -4730,7 +4717,7 @@ namespace System.Threading.Tasks
             // m_continuationObject is guaranteed at this point to be either a List or
             // s_taskCompletionSentinel.
             List<object> list = m_continuationObject as List<object>;
-            Contract.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel),
+            Debug.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel),
                 "Expected m_continuationObject to be list or sentinel");
 
             // If list is null, it can only mean that s_taskCompletionSentinel has been exchanged
@@ -4873,7 +4860,7 @@ namespace System.Threading.Tasks
             WaitAll(tasks, Timeout.Infinite);
 
 #if DEBUG
-            Contract.Assert(waitResult, "expected wait to succeed");
+            Debug.Assert(waitResult, "expected wait to succeed");
 #endif
         }
 
@@ -5134,7 +5121,7 @@ namespace System.Threading.Tasks
 
                 // Now gather up and throw all of the exceptions.
                 foreach (var task in tasks) AddExceptionsForCompletedTask(ref exceptions, task);
-                Contract.Assert(exceptions != null, "Should have seen at least one exception");
+                Debug.Assert(exceptions != null, "Should have seen at least one exception");
                 ThrowHelper.ThrowAggregateException(exceptions);
             }
 
@@ -5159,8 +5146,8 @@ namespace System.Threading.Tasks
         /// <returns>true if all of the tasks completed; otherwise, false.</returns>
         private static bool WaitAllBlockingCore(List<Task> tasks, int millisecondsTimeout, CancellationToken cancellationToken)
         {
-            Contract.Assert(tasks != null, "Expected a non-null list of tasks");
-            Contract.Assert(tasks.Count > 0, "Expected at least one task");
+            Debug.Assert(tasks != null, "Expected a non-null list of tasks");
+            Debug.Assert(tasks.Count > 0, "Expected at least one task");
 
             bool waitCompleted = false;
             var mres = new SetOnCountdownMres(tasks.Count);
@@ -5206,14 +5193,14 @@ namespace System.Threading.Tasks
 
             internal SetOnCountdownMres(int count)
             {
-                Contract.Assert(count > 0, "Expected count > 0");
+                Debug.Assert(count > 0, "Expected count > 0");
                 _count = count;
             }
 
             public void Invoke(Task completingTask)
             {
                 if (Interlocked.Decrement(ref _count) == 0) Set();
-                Contract.Assert(_count >= 0, "Count should never go below 0");
+                Debug.Assert(_count >= 0, "Count should never go below 0");
             }
 
             public bool InvokeMayRunArbitraryCode { get { return false; } }
@@ -5304,7 +5291,7 @@ namespace System.Threading.Tasks
         public static int WaitAny(params Task[] tasks)
         {
             int waitResult = WaitAny(tasks, Timeout.Infinite);
-            Contract.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed");
+            Debug.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed");
             return waitResult;
         }
 
@@ -5475,9 +5462,9 @@ namespace System.Threading.Tasks
                 bool waitCompleted = firstCompleted.Wait(millisecondsTimeout, cancellationToken);
                 if (waitCompleted)
                 {
-                    Contract.Assert(firstCompleted.Status == TaskStatus.RanToCompletion);
+                    Debug.Assert(firstCompleted.Status == TaskStatus.RanToCompletion);
                     signaledTaskIndex = Array.IndexOf(tasks, firstCompleted.Result);
-                    Contract.Assert(signaledTaskIndex >= 0);
+                    Debug.Assert(signaledTaskIndex >= 0);
                 }
             }
 
@@ -5521,7 +5508,7 @@ namespace System.Threading.Tasks
 
             var task = new Task<TResult>();
             bool succeeded = task.TrySetException(exception);
-            Contract.Assert(succeeded, "This should always succeed on a new task.");
+            Debug.Assert(succeeded, "This should always succeed on a new task.");
             return task;
         }
 
@@ -5559,7 +5546,7 @@ namespace System.Threading.Tasks
 
             var task = new Task<TResult>();
             bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception);
-            Contract.Assert(succeeded, "This should always succeed on a new task.");
+            Debug.Assert(succeeded, "This should always succeed on a new task.");
             return task;
         }
         
@@ -6124,7 +6111,7 @@ namespace System.Threading.Tasks
                     for (int i = 0; i < m_tasks.Length; i++)
                     {
                         var task = m_tasks[i];
-                        Contract.Assert(task != null, "Constituent task in WhenAll should never be null");
+                        Debug.Assert(task != null, "Constituent task in WhenAll should never be null");
 
                         if (task.IsFaulted)
                         {
@@ -6144,7 +6131,7 @@ namespace System.Threading.Tasks
 
                     if (observedExceptions != null)
                     {
-                        Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception");
+                        Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception");
 
                         //We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
 
@@ -6166,7 +6153,7 @@ namespace System.Threading.Tasks
                         TrySetResult(default(VoidTaskResult));
                     }
                 }
-                Contract.Assert(m_count >= 0, "Count should never go below 0");
+                Debug.Assert(m_count >= 0, "Count should never go below 0");
             }
 
             public bool InvokeMayRunArbitraryCode { get { return true; } }
@@ -6371,7 +6358,7 @@ namespace System.Threading.Tasks
                     for (int i = 0; i < m_tasks.Length; i++)
                     {
                         Task<T> task = m_tasks[i];
-                        Contract.Assert(task != null, "Constituent task in WhenAll should never be null");
+                        Debug.Assert(task != null, "Constituent task in WhenAll should never be null");
 
                         if (task.IsFaulted)
                         {
@@ -6384,7 +6371,7 @@ namespace System.Threading.Tasks
                         }
                         else
                         {
-                            Contract.Assert(task.Status == TaskStatus.RanToCompletion);
+                            Debug.Assert(task.Status == TaskStatus.RanToCompletion);
                             results[i] = task.GetResultCore(waitCompletionNotification: false); // avoid Result, which would triggering debug notification
                         }
 
@@ -6396,7 +6383,7 @@ namespace System.Threading.Tasks
 
                     if (observedExceptions != null)
                     {
-                        Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception");
+                        Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception");
 
                         //We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
 
@@ -6418,7 +6405,7 @@ namespace System.Threading.Tasks
                         TrySetResult(results);
                     }
                 }
-                Contract.Assert(m_count >= 0, "Count should never go below 0");
+                Debug.Assert(m_count >= 0, "Count should never go below 0");
             }
 
             public bool InvokeMayRunArbitraryCode { get { return true; } }
@@ -6612,7 +6599,7 @@ namespace System.Threading.Tasks
                 Task continuationTask = continuationObject as Task;
                 if (continuationTask != null)
                 {
-                    Contract.Assert(continuationTask.m_action == null);
+                    Debug.Assert(continuationTask.m_action == null);
                     Delegate[] delegates = continuationTask.GetDelegateContinuationsForDebugger();
                     if (delegates != null)
                         return delegates;
@@ -6677,13 +6664,11 @@ namespace System.Threading.Tasks
             m_completingTask = completingTask;
         }
 
-        [SecurityCritical]
         void IThreadPoolWorkItem.ExecuteWorkItem()
         {
             m_action.Invoke(m_completingTask);
         }
 
-        [SecurityCritical]
         void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
         {
             /* NOP */
@@ -6999,25 +6984,12 @@ namespace System.Threading.Tasks
         // that can SO in 20 inlines on a typical 1MB stack size probably needs to be revisited anyway.
         private const int MAX_UNCHECKED_INLINING_DEPTH = 20;
 
-#if !FEATURE_CORECLR
-
-        private UInt64 m_lastKnownWatermark;
-        private static int s_pageSize;
-
-        // We are conservative here. We assume that the platform needs a whole 64KB to
-        // respond to stack overflow. This means that for very small stacks (e.g. 128KB) 
-        // we'll fail a lot of stack checks incorrectly.
-        private const long STACK_RESERVED_SPACE = 4096 * 16;
-
-#endif  // !FEATURE_CORECLR
-
         /// <summary>
         /// This method needs to be called before attempting inline execution on the current thread. 
         /// If false is returned, it means we are too close to the end of the stack and should give up inlining.
         /// Each call to TryBeginInliningScope() that returns true must be matched with a 
         /// call to EndInliningScope() regardless of whether inlining actually took place.
         /// </summary>
-        [SecuritySafeCritical]
         internal bool TryBeginInliningScope()
         {
             // If we're still under the 'safe' limit we'll just skip the stack probe to save p/invoke calls
@@ -7037,59 +7009,15 @@ namespace System.Threading.Tasks
         internal void EndInliningScope()
         {
             m_inliningDepth--;
-            Contract.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative.");
+            Debug.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative.");
 
             // do the right thing just in case...
             if (m_inliningDepth < 0) m_inliningDepth = 0;
         }
 
-        [SecurityCritical]
         private unsafe bool CheckForSufficientStack()
         {
-#if FEATURE_CORECLR
             return RuntimeHelpers.TryEnsureSufficientExecutionStack();
-#else
-            // see if we already have the system page size info recorded
-            int pageSize = s_pageSize;
-            if (pageSize == 0)
-            {
-                // If not we need to query it from GetSystemInfo()
-                // Note that this happens only once for the process lifetime
-                Win32Native.SYSTEM_INFO sysInfo = new Win32Native.SYSTEM_INFO();
-                Win32Native.GetSystemInfo(ref sysInfo);
-
-                s_pageSize = pageSize = sysInfo.dwPageSize;
-            }
-
-            Win32Native.MEMORY_BASIC_INFORMATION stackInfo = new Win32Native.MEMORY_BASIC_INFORMATION();
-
-            // We subtract one page for our request. VirtualQuery rounds UP to the next page.
-            // Unfortunately, the stack grows down. If we're on the first page (last page in the
-            // VirtualAlloc), we'll be moved to the next page, which is off the stack! 
-
-            UIntPtr currentAddr = new UIntPtr(&stackInfo - pageSize);
-            UInt64 current64 = currentAddr.ToUInt64();
-
-            // Check whether we previously recorded a deeper stack than where we currently are,
-            // If so we don't need to do the P/Invoke to VirtualQuery
-            if (m_lastKnownWatermark != 0 && current64 > m_lastKnownWatermark)
-                return true;
-
-            // Actual stack probe. P/Invoke to query for the current stack allocation information.            
-            Win32Native.VirtualQuery(currentAddr.ToPointer(), ref stackInfo, (UIntPtr)(sizeof(Win32Native.MEMORY_BASIC_INFORMATION)));
-
-            // If the current address minus the base (remember: the stack grows downward in the
-            // address space) is greater than the number of bytes requested plus the reserved
-            // space at the end, the request has succeeded.
-
-            if ((current64 - ((UIntPtr)stackInfo.AllocationBase).ToUInt64()) > STACK_RESERVED_SPACE)
-            {
-                m_lastKnownWatermark = current64;
-                return true;
-            }
-
-            return false;
-#endif
         }
     }
 
@@ -7204,16 +7132,15 @@ namespace System.Threading.Tasks
                 case STATE_WAITING_ON_INNER_TASK:
                     bool result = TrySetFromTask(completingTask, lookForOce: false);
                     _state = STATE_DONE; // bump the state
-                    Contract.Assert(result, "Expected TrySetFromTask from inner task to succeed");
+                    Debug.Assert(result, "Expected TrySetFromTask from inner task to succeed");
                     break;
                 default:
-                    Contract.Assert(false, "UnwrapPromise in illegal state");
+                    Debug.Assert(false, "UnwrapPromise in illegal state");
                     break;
             }
         }
 
         // Calls InvokeCore asynchronously.
-        [SecuritySafeCritical]
         private void InvokeCoreAsync(Task completingTask)
         {
             // Queue a call to Invoke.  If we're so deep on the stack that we're at risk of overflowing,
@@ -7233,7 +7160,7 @@ namespace System.Threading.Tasks
         private void ProcessCompletedOuterTask(Task task)
         {
             Contract.Requires(task != null && task.IsCompleted, "Expected non-null, completed outer task");
-            Contract.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!");
+            Debug.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!");
 
             // Bump our state before proceeding any further
             _state = STATE_WAITING_ON_INNER_TASK;
@@ -7245,7 +7172,7 @@ namespace System.Threading.Tasks
                 case TaskStatus.Canceled:
                 case TaskStatus.Faulted:
                     bool result = TrySetFromTask(task, _lookForOce);
-                    Contract.Assert(result, "Expected TrySetFromTask from outer task to succeed");
+                    Debug.Assert(result, "Expected TrySetFromTask from outer task to succeed");
                     break;
 
                 // Otherwise, process the inner task it returned.
index 8b1dd2a..320f704 100644 (file)
@@ -12,6 +12,7 @@
 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 
 using System;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Collections.Generic;
 using System.Runtime.CompilerServices;
@@ -47,7 +48,6 @@ namespace System.Threading.Tasks
     /// </remarks>
     /// <typeparam name="TResult">The type of the result value assocatied with this <see
     /// cref="TaskCompletionSource{TResult}"/>.</typeparam>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public class TaskCompletionSource<TResult>
     {
         private readonly Task<TResult> m_task;
@@ -209,9 +209,9 @@ namespace System.Threading.Tasks
         /// <remarks>Unlike the public methods, this method doesn't currently validate that its arguments are correct.</remarks>
         internal bool TrySetException(IEnumerable<ExceptionDispatchInfo> exceptions)
         {
-            Contract.Assert(exceptions != null);
+            Debug.Assert(exceptions != null);
 #if DEBUG
-            foreach(var edi in exceptions) Contract.Assert(edi != null, "Contents must be non-null");
+            foreach(var edi in exceptions) Debug.Assert(edi != null, "Contents must be non-null");
 #endif
 
             bool rval = m_task.TrySetException(exceptions);
index b078d27..70b9418 100644 (file)
@@ -11,6 +11,7 @@
 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 
 using System.Security;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Runtime.ExceptionServices;
 using System.Runtime.CompilerServices;
@@ -45,7 +46,7 @@ namespace System.Threading.Tasks
             // Get and null out the antecedent.  This is crucial to avoid a memory
             // leak with long chains of continuations.
             var antecedent = m_antecedent;
-            Contract.Assert(antecedent != null, 
+            Debug.Assert(antecedent != null, 
                 "No antecedent was set for the ContinuationTaskFromTask.");
             m_antecedent = null;
 
@@ -53,7 +54,7 @@ namespace System.Threading.Tasks
             antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
 
             // Invoke the delegate
-            Contract.Assert(m_action != null);
+            Debug.Assert(m_action != null);
             var action = m_action as Action<Task>;
             if (action != null)
             {
@@ -66,7 +67,7 @@ namespace System.Threading.Tasks
                 actionWithState(antecedent, m_stateObject);
                 return;
             }
-            Contract.Assert(false, "Invalid m_action in ContinuationTaskFromTask");
+            Debug.Assert(false, "Invalid m_action in ContinuationTaskFromTask");
         }
     }
 
@@ -93,7 +94,7 @@ namespace System.Threading.Tasks
             // Get and null out the antecedent.  This is crucial to avoid a memory
             // leak with long chains of continuations.
             var antecedent = m_antecedent;
-            Contract.Assert(antecedent != null, 
+            Debug.Assert(antecedent != null, 
                 "No antecedent was set for the ContinuationResultTaskFromTask.");
             m_antecedent = null;
 
@@ -101,7 +102,7 @@ namespace System.Threading.Tasks
             antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
 
             // Invoke the delegate
-            Contract.Assert(m_action != null);
+            Debug.Assert(m_action != null);
             var func = m_action as Func<Task, TResult>;
             if (func != null)
             {
@@ -114,7 +115,7 @@ namespace System.Threading.Tasks
                 m_result = funcWithState(antecedent, m_stateObject);
                 return;
             }
-            Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask");
+            Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask");
         }
     }
 
@@ -141,7 +142,7 @@ namespace System.Threading.Tasks
             // Get and null out the antecedent.  This is crucial to avoid a memory
             // leak with long chains of continuations.
             var antecedent = m_antecedent;
-            Contract.Assert(antecedent != null, 
+            Debug.Assert(antecedent != null, 
                 "No antecedent was set for the ContinuationTaskFromResultTask.");
             m_antecedent = null;
 
@@ -149,7 +150,7 @@ namespace System.Threading.Tasks
             antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
 
             // Invoke the delegate
-            Contract.Assert(m_action != null);
+            Debug.Assert(m_action != null);
             var action = m_action as Action<Task<TAntecedentResult>>;
             if (action != null)
             {
@@ -162,7 +163,7 @@ namespace System.Threading.Tasks
                 actionWithState(antecedent, m_stateObject);
                 return;
             }
-            Contract.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask");
+            Debug.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask");
         }
     }
 
@@ -189,7 +190,7 @@ namespace System.Threading.Tasks
             // Get and null out the antecedent.  This is crucial to avoid a memory
             // leak with long chains of continuations.
             var antecedent = m_antecedent;
-            Contract.Assert(antecedent != null, 
+            Debug.Assert(antecedent != null, 
                 "No antecedent was set for the ContinuationResultTaskFromResultTask.");
             m_antecedent = null;
 
@@ -197,7 +198,7 @@ namespace System.Threading.Tasks
             antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
 
             // Invoke the delegate
-            Contract.Assert(m_action != null);
+            Debug.Assert(m_action != null);
             var func = m_action as Func<Task<TAntecedentResult>, TResult>;
             if (func != null)
             {
@@ -210,7 +211,7 @@ namespace System.Threading.Tasks
                 m_result = funcWithState(antecedent, m_stateObject);
                 return;
             }
-            Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask");
+            Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask");
         }
     }
 
@@ -235,11 +236,10 @@ namespace System.Threading.Tasks
         /// <param name="needsProtection">
         /// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false.
         /// </param>
-        [SecuritySafeCritical]
         protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection)
         {
             Contract.Requires(task != null);
-            Contract.Assert(task.m_taskScheduler != null);
+            Debug.Assert(task.m_taskScheduler != null);
 
             // Set the TASK_STATE_STARTED flag.  This only needs to be done
             // if the task may be canceled or if someone else has a reference to it
@@ -318,8 +318,8 @@ namespace System.Threading.Tasks
         /// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param>
         internal override void Run(Task completedTask, bool bCanInlineContinuationTask)
         {
-            Contract.Assert(completedTask != null);
-            Contract.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
+            Debug.Assert(completedTask != null);
+            Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
 
             // Check if the completion status of the task works with the desired 
             // activation criteria of the TaskContinuationOptions.
@@ -384,7 +384,6 @@ namespace System.Threading.Tasks
         /// <summary>SendOrPostCallback delegate to invoke the action.</summary>
         private readonly static SendOrPostCallback s_postCallback = state => ((Action)state)(); // can't use InvokeAction as it's SecurityCritical
         /// <summary>Cached delegate for PostAction</summary>
-        [SecurityCritical]
         private static ContextCallback s_postActionCallback;
         /// <summary>The context with which to run the action.</summary>
         private readonly SynchronizationContext m_syncContext;
@@ -394,19 +393,17 @@ namespace System.Threading.Tasks
         /// <param name="action">The action to invoke. Must not be null.</param>
         /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
         /// <param name="stackMark">The captured stack mark.</param>
-        [SecurityCritical]
         internal SynchronizationContextAwaitTaskContinuation(
             SynchronizationContext context, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) :
             base(action, flowExecutionContext, ref stackMark)
         {
-            Contract.Assert(context != null);
+            Debug.Assert(context != null);
             m_syncContext = context;
         }
 
         /// <summary>Inlines or schedules the continuation.</summary>
         /// <param name="ignored">The antecedent task, which is ignored.</param>
         /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
-        [SecuritySafeCritical]
         internal sealed override void Run(Task task, bool canInlineContinuationTask)
         {
             // If we're allowed to inline, run the action on this thread.
@@ -431,7 +428,6 @@ namespace System.Threading.Tasks
 
         /// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary>
         /// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param>
-        [SecurityCritical]
         private static void PostAction(object state)
         {
             var c = (SynchronizationContextAwaitTaskContinuation)state;
@@ -465,7 +461,6 @@ namespace System.Threading.Tasks
         /// to be passed as state.
         /// </returns>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        [SecurityCritical]
         private static ContextCallback GetPostActionCallback()
         {
             ContextCallback callback = s_postActionCallback;
@@ -485,12 +480,11 @@ namespace System.Threading.Tasks
         /// <param name="action">The action to invoke. Must not be null.</param>
         /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
         /// <param name="stackMark">The captured stack mark.</param>
-        [SecurityCritical]
         internal TaskSchedulerAwaitTaskContinuation(
             TaskScheduler scheduler, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) :
             base(action, flowExecutionContext, ref stackMark)
         {
-            Contract.Assert(scheduler != null);
+            Debug.Assert(scheduler != null);
             m_scheduler = scheduler;
         }
 
@@ -550,7 +544,6 @@ namespace System.Threading.Tasks
         /// <param name="action">The action to invoke. Must not be null.</param>
         /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
         /// <param name="stackMark">The captured stack mark with which to construct an ExecutionContext.</param>
-        [SecurityCritical]
         internal AwaitTaskContinuation(Action action, bool flowExecutionContext, ref StackCrawlMark stackMark)
         {
             Contract.Requires(action != null);
@@ -566,7 +559,6 @@ namespace System.Threading.Tasks
         /// <summary>Initializes the continuation.</summary>
         /// <param name="action">The action to invoke. Must not be null.</param>
         /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
-        [SecurityCritical]
         internal AwaitTaskContinuation(Action action, bool flowExecutionContext)
         {
             Contract.Requires(action != null);
@@ -598,7 +590,6 @@ namespace System.Threading.Tasks
         /// <summary>Inlines or schedules the continuation onto the default scheduler.</summary>
         /// <param name="ignored">The antecedent task, which is ignored.</param>
         /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
-        [SecuritySafeCritical]
         internal override void Run(Task task, bool canInlineContinuationTask)
         {
             // For the base AwaitTaskContinuation, we allow inlining if our caller allows it
@@ -657,7 +648,6 @@ namespace System.Threading.Tasks
         }
 
         /// <summary>IThreadPoolWorkItem override, which is the entry function for this when the ThreadPool scheduler decides to run it.</summary>
-        [SecurityCritical]
         void ExecuteWorkItemHelper()
         {
             var etwLog = TplEtwProvider.Log;
@@ -696,7 +686,6 @@ namespace System.Threading.Tasks
             }
         }
 
-        [SecurityCritical]
         void IThreadPoolWorkItem.ExecuteWorkItem()
         {
             // inline the fast path
@@ -714,20 +703,16 @@ namespace System.Threading.Tasks
         /// <summary>
         /// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem.
         /// </summary>
-        [SecurityCritical]
         void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ }
 
         /// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary>
-        [SecurityCritical]
         private static ContextCallback s_invokeActionCallback;
 
         /// <summary>Runs an action provided as an object parameter.</summary>
         /// <param name="state">The Action to invoke.</param>
-        [SecurityCritical]
         private static void InvokeAction(object state) { ((Action)state)(); }
 
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        [SecurityCritical]
         protected static ContextCallback GetInvokeActionCallback()
         {
             ContextCallback callback = s_invokeActionCallback;
@@ -739,11 +724,10 @@ namespace System.Threading.Tasks
         /// <param name="callback">The callback to run.</param>
         /// <param name="state">The state to pass to the callback.</param>
         /// <param name="currentTask">A reference to Task.t_currentTask.</param>
-        [SecurityCritical]
         protected void RunCallback(ContextCallback callback, object state, ref Task currentTask)
         {
             Contract.Requires(callback != null);
-            Contract.Assert(currentTask == Task.t_currentTask);
+            Debug.Assert(currentTask == Task.t_currentTask);
 
             // Pretend there's no current task, so that no task is seen as a parent
             // and TaskScheduler.Current does not reflect false information
@@ -787,10 +771,9 @@ namespace System.Threading.Tasks
         /// only happens in Task.SetContinuationForAwait if execution context flow was disabled
         /// via using TaskAwaiter.UnsafeOnCompleted or a similar path.
         /// </remarks>
-        [SecurityCritical]
         internal static void RunOrScheduleAction(Action action, bool allowInlining, ref Task currentTask)
         {
-            Contract.Assert(currentTask == Task.t_currentTask);
+            Debug.Assert(currentTask == Task.t_currentTask);
 
             // If we're not allowed to run here, schedule the action
             if (!allowInlining || !IsValidLocationForInlining)
@@ -818,7 +801,6 @@ namespace System.Threading.Tasks
 
         /// <summary>Schedules the action to be executed.  No ExecutionContext work is performed used.</summary>
         /// <param name="action">The action to invoke or queue.</param>
-        [SecurityCritical]
         internal static void UnsafeScheduleAction(Action action, Task task)
         {
             AwaitTaskContinuation atc = new AwaitTaskContinuation(action, flowExecutionContext: false);
@@ -859,7 +841,7 @@ namespace System.Threading.Tasks
 
         internal override Delegate[] GetDelegateContinuationsForDebugger()
         {
-            Contract.Assert(m_action != null);
+            Debug.Assert(m_action != null);
             return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) };
         }
     }
index 30fa54c..45817da 100644 (file)
@@ -18,6 +18,7 @@ namespace System.Threading.Tasks
     using System;
     using System.Collections.Generic;
     using System.Collections.ObjectModel;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Runtime.ExceptionServices;
     using System.Security;
@@ -62,14 +63,9 @@ namespace System.Threading.Tasks
             EnsureADUnloadCallbackRegistered();
         }
 
-        [SecuritySafeCritical]
         private static bool ShouldFailFastOnUnobservedException()
         {
-            bool shouldFailFast = false;
-            #if !FEATURE_CORECLR
-            shouldFailFast = System.CLRConfig.CheckThrowUnobservedTaskExceptions();
-            #endif
-            return shouldFailFast;
+            return false;
         }
 
         private static void EnsureADUnloadCallbackRegistered()
@@ -202,12 +198,12 @@ namespace System.Threading.Tasks
         {
             Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null.");
             
-            Contract.Assert(m_cancellationException == null, 
+            Debug.Assert(m_cancellationException == null, 
                 "Expected SetCancellationException to be called only once.");
                 // Breaking this assumption will overwrite a previously OCE,
                 // and implies something may be wrong elsewhere, since there should only ever be one.
 
-            Contract.Assert(m_faultExceptions == null, 
+            Debug.Assert(m_faultExceptions == null, 
                 "Expected SetCancellationException to be called before any faults were added.");
                 // Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere.
                 // If this changes, make sure to only conditionally mark as handled below.
@@ -221,7 +217,7 @@ namespace System.Threading.Tasks
             else
             {
                 var edi = exceptionObject as ExceptionDispatchInfo;
-                Contract.Assert(edi != null && edi.SourceException is OperationCanceledException,
+                Debug.Assert(edi != null && edi.SourceException is OperationCanceledException,
                     "Expected an OCE or an EDI that contained an OCE");
                 m_cancellationException = edi;
             }
@@ -242,7 +238,7 @@ namespace System.Threading.Tasks
             // Initialize the exceptions list if necessary.  The list should be non-null iff it contains exceptions.
             var exceptions = m_faultExceptions;
             if (exceptions == null) m_faultExceptions = exceptions = new List<ExceptionDispatchInfo>(1);
-            else Contract.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions.");
+            else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions.");
 
             // Handle Exception by capturing it into an ExceptionDispatchInfo and storing that
             var exception = exceptionObject as Exception;
@@ -270,13 +266,13 @@ namespace System.Threading.Tasks
                         foreach (var exc in exColl)
                         {
 #if DEBUG
-                            Contract.Assert(exc != null, "No exceptions should be null");
+                            Debug.Assert(exc != null, "No exceptions should be null");
                             numExceptions++;
 #endif
                             exceptions.Add(ExceptionDispatchInfo.Capture(exc));
                         }
 #if DEBUG
-                        Contract.Assert(numExceptions > 0, "Collection should contain at least one exception.");
+                        Debug.Assert(numExceptions > 0, "Collection should contain at least one exception.");
 #endif
                     }
                     else
@@ -287,10 +283,10 @@ namespace System.Threading.Tasks
                         {
                             exceptions.AddRange(ediColl);
 #if DEBUG
-                            Contract.Assert(exceptions.Count > 0, "There should be at least one dispatch info.");
+                            Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info.");
                             foreach(var tmp in exceptions)
                             {
-                                Contract.Assert(tmp != null, "No dispatch infos should be null");
+                                Debug.Assert(tmp != null, "No dispatch infos should be null");
                             }
 #endif
                         }
@@ -370,8 +366,8 @@ namespace System.Threading.Tasks
         internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exception includeThisException)
         {
             var exceptions = m_faultExceptions;
-            Contract.Assert(exceptions != null, "Expected an initialized list.");
-            Contract.Assert(exceptions.Count > 0, "Expected at least one exception.");
+            Debug.Assert(exceptions != null, "Expected an initialized list.");
+            Debug.Assert(exceptions.Count > 0, "Expected at least one exception.");
 
             // Mark as handled and aggregate the exceptions.
             MarkAsHandled(calledFromFinalizer);
@@ -400,8 +396,8 @@ namespace System.Threading.Tasks
         internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos()
         {
             var exceptions = m_faultExceptions;
-            Contract.Assert(exceptions != null, "Expected an initialized list.");
-            Contract.Assert(exceptions.Count > 0, "Expected at least one exception.");
+            Debug.Assert(exceptions != null, "Expected an initialized list.");
+            Debug.Assert(exceptions.Count > 0, "Expected at least one exception.");
             MarkAsHandled(false);
             return new ReadOnlyCollection<ExceptionDispatchInfo>(exceptions);
         }
@@ -416,7 +412,7 @@ namespace System.Threading.Tasks
         internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo()
         {
             var edi = m_cancellationException;
-            Contract.Assert(edi == null || edi.SourceException is OperationCanceledException,
+            Debug.Assert(edi == null || edi.SourceException is OperationCanceledException,
                 "Expected the EDI to be for an OperationCanceledException");
             return edi;
         }
index 699ab5a..aa4c2df 100644 (file)
@@ -18,6 +18,7 @@ using System.Security;
 using System.Security.Permissions;
 using System.Runtime.CompilerServices;
 using System.Threading;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Threading.Tasks
@@ -37,7 +38,6 @@ namespace System.Threading.Tasks
     /// <see cref="System.Threading.Tasks.Task.Factory">Task.Factory</see> property.
     /// </para>
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public class TaskFactory
     {
         // member variables
@@ -1666,7 +1666,7 @@ namespace System.Threading.Tasks
 
                     TrySetResult(_tasks);
                 }
-                Contract.Assert(_count >= 0, "Count should never go below 0");
+                Debug.Assert(_count >= 0, "Count should never go below 0");
             }
 
             public bool InvokeMayRunArbitraryCode { get { return true; } }
@@ -1746,7 +1746,7 @@ namespace System.Threading.Tasks
 
                     TrySetResult(_tasks);
                 }
-                Contract.Assert(_count >= 0, "Count should never go below 0");
+                Debug.Assert(_count >= 0, "Count should never go below 0");
             }
 
             public bool InvokeMayRunArbitraryCode { get { return true; } }
@@ -2448,7 +2448,7 @@ namespace System.Threading.Tasks
                     }
 
                     bool success = TrySetResult(completingTask);
-                    Contract.Assert(success, "Only one task should have gotten to this point, and thus this must be successful.");
+                    Debug.Assert(success, "Only one task should have gotten to this point, and thus this must be successful.");
 
                     // We need to remove continuations that may be left straggling on other tasks.
                     // Otherwise, repeated calls to WhenAny using the same task could leak actions.
index f824924..fad3fc0 100644 (file)
@@ -41,10 +41,6 @@ namespace System.Threading.Tasks
     /// </remarks>
     [DebuggerDisplay("Id={Id}")]
     [DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskSchedulerDebugView))]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
-#pragma warning disable 618
-    [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
     public abstract class TaskScheduler
     {
         ////////////////////////////////////////////////////////////
@@ -70,7 +66,6 @@ namespace System.Threading.Tasks
         /// </remarks>
         /// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be queued.</param>
         /// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception>
-        [SecurityCritical]
         protected internal abstract void QueueTask(Task task);
 
         /// <summary>
@@ -113,7 +108,6 @@ namespace System.Threading.Tasks
         /// null.</exception>
         /// <exception cref="T:System.InvalidOperationException">The <paramref name="task"/> was already
         /// executed.</exception>
-        [SecurityCritical]
         protected abstract bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued);
 
         /// <summary>
@@ -157,7 +151,6 @@ namespace System.Threading.Tasks
         /// <exception cref="T:System.NotSupportedException">
         /// This scheduler is unable to generate a list of queued tasks at this time.
         /// </exception>
-        [SecurityCritical]
         protected abstract IEnumerable<Task> GetScheduledTasks();
 
         /// <summary>
@@ -185,7 +178,6 @@ namespace System.Threading.Tasks
         /// <param name="taskWasPreviouslyQueued">True if the task may have been previously queued,
         /// false if the task was absolutely not previously queued.</param>
         /// <returns>True if it ran, false otherwise.</returns>
-        [SecuritySafeCritical]
         internal bool TryRunInline(Task task, bool taskWasPreviouslyQueued)
         {
             // Do not inline unstarted tasks (i.e., task.ExecutingTaskScheduler == null).
@@ -237,7 +229,6 @@ namespace System.Threading.Tasks
         /// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be dequeued.</param>
         /// <returns>A Boolean denoting whether the <paramref name="task"/> argument was successfully dequeued.</returns>
         /// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception>
-        [SecurityCritical]
         protected internal virtual bool TryDequeue(Task task)
         {
             return false;
@@ -262,7 +253,6 @@ namespace System.Threading.Tasks
         /// <summary>
         /// Calls QueueTask() after performing any needed firing of events
         /// </summary>
-        [SecurityCritical]
         internal void InternalQueueTask(Task task)
         {
             Contract.Requires(task != null);
@@ -444,7 +434,6 @@ namespace System.Threading.Tasks
         /// <returns>A Boolean that is true if <paramref name="task"/> was successfully executed, false if it
         /// was not. A common reason for execution failure is that the task had previously been executed or
         /// is in the process of being executed by another thread.</returns>
-        [SecurityCritical]
         protected bool TryExecuteTask(Task task)
         {
             if (task.ExecutingTaskScheduler != this)
@@ -475,7 +464,6 @@ namespace System.Threading.Tasks
         /// </remarks>
         public static event EventHandler<UnobservedTaskExceptionEventArgs> UnobservedTaskException
         {
-            [System.Security.SecurityCritical]
             add
             {
                 if (value != null)
@@ -485,7 +473,6 @@ namespace System.Threading.Tasks
                 }
             }
 
-            [System.Security.SecurityCritical]
             remove
             {
                 lock (_unobservedTaskExceptionLockObject) _unobservedTaskException -= value;
@@ -531,7 +518,6 @@ namespace System.Threading.Tasks
         /// <exception cref="T:System.NotSupportedException">
         /// This scheduler is unable to generate a list of queued tasks at this time.
         /// </exception>
-        [SecurityCritical]
         internal Task[] GetScheduledTasksForDebugger()
         {
             // this can throw InvalidOperationException indicating that they are unable to provide the info
@@ -566,7 +552,6 @@ namespace System.Threading.Tasks
         /// It should not be called by any other codepaths.
         /// </remarks>
         /// <returns>An array of <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> instances.</returns> 
-        [SecurityCritical]
         internal static TaskScheduler[] GetTaskSchedulersForDebugger()
         {
             if (s_activeTaskSchedulers == null)
@@ -587,7 +572,7 @@ namespace System.Threading.Tasks
             schedulers.CopyTo(arr, 0);
             foreach (var scheduler in arr)
             {
-                Contract.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed");
+                Debug.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed");
                 int tmp = scheduler.Id; // force Ids for debugger
             }
             return arr;
@@ -613,7 +598,6 @@ namespace System.Threading.Tasks
             // returns the scheduler\92s GetScheduledTasks
             public IEnumerable<Task> ScheduledTasks 
             {
-                [SecurityCritical]
                 get { return m_taskScheduler.GetScheduledTasks(); }
             }
         }
@@ -656,7 +640,6 @@ namespace System.Threading.Tasks
         /// Simply posts the tasks to be executed on the associated <see cref="T:System.Threading.SynchronizationContext"/>.
         /// </summary>
         /// <param name="task"></param>
-        [SecurityCritical]
         protected internal override void QueueTask(Task task)
         {
             m_synchronizationContext.Post(s_postCallback, (object)task);
@@ -670,7 +653,6 @@ namespace System.Threading.Tasks
         /// </summary>
         /// <param name="task"></param>
         /// <param name="taskWasPreviouslyQueued"></param>
-        [SecurityCritical]
         protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
         {
             if (SynchronizationContext.Current == m_synchronizationContext)
@@ -682,7 +664,6 @@ namespace System.Threading.Tasks
         }
 
         // not implemented
-        [SecurityCritical]
         protected override IEnumerable<Task> GetScheduledTasks()
         {
             return null;
index 02b130c..90743ae 100644 (file)
@@ -22,6 +22,7 @@
 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 
 using System.IO;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Threading.Tasks
@@ -76,7 +77,7 @@ namespace System.Threading.Tasks
             if (twar != null)
             {
                 task = twar.Task;
-                Contract.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
+                Debug.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
             }
             // Otherwise, the IAsyncResult should be a Task.
             else
@@ -101,7 +102,7 @@ namespace System.Threading.Tasks
             if (twar != null)
             {
                 task = twar.Task as Task<TResult>;
-                Contract.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
+                Debug.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
             }
             // Otherwise, the IAsyncResult should be a Task<TResult>.
             else
index dd4cbc9..5c6ca9b 100644 (file)
@@ -13,6 +13,7 @@
 
 using System;
 using System.Security;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.Collections.Generic;
 using System.Text;
@@ -39,7 +40,7 @@ namespace System.Threading.Tasks
         {
             Contract.Requires(obj != null, "TaskScheduler.LongRunningThreadWork: obj is null");
             Task t = obj as Task;
-            Contract.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null");
+            Debug.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null");
             t.ExecuteEntry(false);
         }
 
@@ -47,7 +48,6 @@ namespace System.Threading.Tasks
         /// Schedules a task to the ThreadPool.
         /// </summary>
         /// <param name="task">The task to schedule.</param>
-        [SecurityCritical]
         protected internal override void QueueTask(Task task)
         {
             if ((task.Options & TaskCreationOptions.LongRunning) != 0)
@@ -73,7 +73,6 @@ namespace System.Threading.Tasks
         /// IMPORTANT NOTE: TryExecuteTaskInline will NOT throw task exceptions itself. Any wait code path using this function needs
         /// to account for exceptions that need to be propagated, and throw themselves accordingly.
         /// </summary>
-        [SecurityCritical]
         protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
         {
             // If the task was previously scheduled, and we can't pop it, then return false.
@@ -95,14 +94,12 @@ namespace System.Threading.Tasks
             return rval;
         }
 
-        [SecurityCritical]
         protected internal override bool TryDequeue(Task task)
         {
             // just delegate to TP
             return ThreadPool.TryPopCustomWorkItem(task);
         }
 
-        [SecurityCritical]
         protected override IEnumerable<Task> GetScheduledTasks()
         {
             return FilterTasksFromWorkItems(ThreadPool.GetQueuedWorkItems());
index d5b2bdb..0c3fec8 100644 (file)
@@ -65,7 +65,6 @@ namespace System.Threading.Tasks
     /// and may be used from multiple threads concurrently.
     /// </para>
     /// </remarks>
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     [DebuggerTypeProxy(typeof(SystemThreadingTasks_FutureDebugView<>))]
     [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}, Result = {DebuggerDisplayResultDescription}")]
     public class Task<TResult> : Task
@@ -457,7 +456,7 @@ namespace System.Threading.Tasks
         internal bool TrySetResult(TResult result)
         {
             if (IsCompleted) return false;
-            Contract.Assert(m_action == null, "Task<T>.TrySetResult(): non-null m_action");
+            Debug.Assert(m_action == null, "Task<T>.TrySetResult(): non-null m_action");
 
             // "Reserve" the completion for this task, while making sure that: (1) No prior reservation
             // has been made, (2) The result has not already been set, (3) An exception has not previously 
@@ -497,7 +496,7 @@ namespace System.Threading.Tasks
         // the task, avoiding expensive completion paths, before the task is actually given to anyone.
         internal void DangerousSetResult(TResult result)
         {
-            Contract.Assert(!IsCompleted, "The promise must not yet be completed.");
+            Debug.Assert(!IsCompleted, "The promise must not yet be completed.");
 
             // If we have a parent, we need to notify it of the completion.  Take the slow path to handle that.
             if (m_contingentProperties?.m_parent != null)
@@ -505,7 +504,7 @@ namespace System.Threading.Tasks
                 bool success = TrySetResult(result);
 
                 // Nobody else has had a chance to complete this Task yet, so we should succeed.
-                Contract.Assert(success); 
+                Debug.Assert(success); 
             }
             else
             {
@@ -539,7 +538,7 @@ namespace System.Threading.Tasks
         {
             get
             {
-                Contract.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion,
+                Debug.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion,
                     "Should only be used when the task completed successfully and there's no wait notification enabled");
                 return m_result; 
             }
@@ -558,7 +557,7 @@ namespace System.Threading.Tasks
             if (!IsRanToCompletion) ThrowIfExceptional(includeTaskCanceledExceptions: true);
 
             // We shouldn't be here if the result has not been set.
-            Contract.Assert(IsRanToCompletion, "Task<T>.Result getter: Expected result to have been set.");
+            Debug.Assert(IsRanToCompletion, "Task<T>.Result getter: Expected result to have been set.");
 
             return m_result;
         }
@@ -572,13 +571,13 @@ namespace System.Threading.Tasks
         // Called from TaskCompletionSource<T>.SetException(IEnumerable<Exception>).
         internal bool TrySetException(object exceptionObject)
         {
-            Contract.Assert(m_action == null, "Task<T>.TrySetException(): non-null m_action");
+            Debug.Assert(m_action == null, "Task<T>.TrySetException(): non-null m_action");
 
             // TCS.{Try}SetException() should have checked for this
-            Contract.Assert(exceptionObject != null, "Expected non-null exceptionObject argument");
+            Debug.Assert(exceptionObject != null, "Expected non-null exceptionObject argument");
 
             // Only accept these types.
-            Contract.Assert(
+            Debug.Assert(
                 (exceptionObject is Exception) || (exceptionObject is IEnumerable<Exception>) ||
                 (exceptionObject is ExceptionDispatchInfo) || (exceptionObject is IEnumerable<ExceptionDispatchInfo>),
                 "Expected exceptionObject to be either Exception, ExceptionDispatchInfo, or IEnumerable<> of one of those");
@@ -620,10 +619,10 @@ namespace System.Threading.Tasks
         // This method is only valid for promise tasks.
         internal bool TrySetCanceled(CancellationToken tokenToRecord, object cancellationException)
         {
-            Contract.Assert(m_action == null, "Task<T>.TrySetCanceled(): non-null m_action");
+            Debug.Assert(m_action == null, "Task<T>.TrySetCanceled(): non-null m_action");
 #if DEBUG
             var ceAsEdi = cancellationException as ExceptionDispatchInfo;
-            Contract.Assert(
+            Debug.Assert(
                 cancellationException == null ||
                 cancellationException is OperationCanceledException ||
                 (ceAsEdi != null && ceAsEdi.SourceException is OperationCanceledException),
@@ -669,7 +668,7 @@ namespace System.Threading.Tasks
         internal override void InnerInvoke()
         {
             // Invoke the delegate
-            Contract.Assert(m_action != null);
+            Debug.Assert(m_action != null);
             var func = m_action as Func<TResult>;
             if (func != null)
             {
@@ -682,7 +681,7 @@ namespace System.Threading.Tasks
                 m_result = funcWithState(m_stateObject);
                 return;
             }
-            Contract.Assert(false, "Invalid m_action in Task<TResult>");
+            Debug.Assert(false, "Invalid m_action in Task<TResult>");
         }
 
         #region Await Support
index 1a3bbf8..8294c20 100644 (file)
@@ -18,12 +18,7 @@ namespace System.Threading {
     using System.Threading;
     using System.Runtime;
     using System.Runtime.InteropServices;
-#if FEATURE_REMOTING    
-    using System.Runtime.Remoting.Contexts;
-    using System.Runtime.Remoting.Messaging;
-#endif
     using System;
-    using System.Diagnostics;
     using System.Security.Permissions;
     using System.Security.Principal;
     using System.Globalization;
@@ -33,13 +28,13 @@ namespace System.Threading {
     using System.Runtime.ConstrainedExecution;
     using System.Security;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     internal delegate Object InternalCrossContextDelegate(Object[] args);
 
     internal class ThreadHelper
     {
-        [System.Security.SecuritySafeCritical]
         static ThreadHelper() {}
 
         Delegate _start;
@@ -55,10 +50,8 @@ namespace System.Threading {
             _executionContext = ec;
         }
 
-        [System.Security.SecurityCritical]
         static internal ContextCallback _ccb = new ContextCallback(ThreadStart_Context);
         
-        [System.Security.SecurityCritical]
         static private void ThreadStart_Context(Object state)
         {
             ThreadHelper t = (ThreadHelper)state;
@@ -73,11 +66,6 @@ namespace System.Threading {
         }
 
         // call back helper
-        #if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-        #else
-        [System.Security.SecurityCritical]
-        #endif
         internal void ThreadStart(object obj)
         {               
             _startArg = obj;
@@ -92,11 +80,6 @@ namespace System.Threading {
         }
 
         // call back helper
-        #if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-        #else
-        [System.Security.SecurityCritical]
-        #endif
         internal void ThreadStart()
         {
             if (_executionContext != null) 
@@ -131,17 +114,12 @@ namespace System.Threading {
         ** ThreadBaseObject to maintain alignment between the two classes.
         ** DON'T CHANGE THESE UNLESS YOU MODIFY ThreadBaseObject in vm\object.h
         =========================================================================*/
-#if FEATURE_REMOTING        
-        private Context         m_Context;
-#endif 
         private ExecutionContext m_ExecutionContext;    // this call context follows the logical thread
-#if FEATURE_CORECLR
         private SynchronizationContext m_SynchronizationContext;    // On CoreCLR, this is maintained separately from ExecutionContext
-#endif
 
         private String          m_Name;
         private Delegate        m_Delegate;             // Delegate
-        
+
 #if FEATURE_LEAK_CULTURE_INFO 
         private CultureInfo     m_CurrentCulture;
         private CultureInfo     m_CurrentUICulture;
@@ -214,11 +192,8 @@ namespace System.Threading {
 #endif // FEATURE_LEAK_CULTURE_INFO
         }
 
-#if FEATURE_CORECLR
         // Adding an empty default ctor for annotation purposes
-        [System.Security.SecuritySafeCritical] // auto-generated
         internal Thread(){}
-#endif // FEATURE_CORECLR
 
         /*=========================================================================
         ** Creates a new Thread object which will begin execution at
@@ -226,7 +201,6 @@ namespace System.Threading {
         **
         ** Exceptions: ArgumentNullException if start == null.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Thread(ThreadStart start) {
             if (start == null) {
                 throw new ArgumentNullException(nameof(start));
@@ -235,7 +209,6 @@ namespace System.Threading {
             SetStartHelper((Delegate)start,0);  //0 will setup Thread with default stackSize
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Thread(ThreadStart start, int maxStackSize) {
             if (start == null) {
                 throw new ArgumentNullException(nameof(start));
@@ -245,7 +218,6 @@ namespace System.Threading {
             Contract.EndContractBlock();
             SetStartHelper((Delegate)start, maxStackSize);
         }
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Thread(ParameterizedThreadStart start) {
             if (start == null) {
                 throw new ArgumentNullException(nameof(start));
@@ -254,7 +226,6 @@ namespace System.Threading {
             SetStartHelper((Delegate)start, 0);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Thread(ParameterizedThreadStart start, int maxStackSize) {
             if (start == null) {
                 throw new ArgumentNullException(nameof(start));
@@ -275,7 +246,6 @@ namespace System.Threading {
         {
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get;
         }
 
@@ -301,7 +271,6 @@ namespace System.Threading {
         **
         ** Exceptions: ThreadStateException if the thread has already been started.
         =========================================================================*/
-        [HostProtection(Synchronization=true,ExternalThreading=true)]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public new void Start()
         {
@@ -309,7 +278,6 @@ namespace System.Threading {
             Start(ref stackMark);
         }
 
-        [HostProtection(Synchronization=true,ExternalThreading=true)]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public new void Start(object parameter)
         {
@@ -327,7 +295,6 @@ namespace System.Threading {
             Start(ref stackMark);
         }
 
-        [System.Security.SecuritySafeCritical]
         private void Start(ref StackCrawlMark stackMark)
         {
 #if FEATURE_COMINTEROP_APARTMENT_SUPPORT
@@ -353,7 +320,6 @@ namespace System.Threading {
             StartInternal(principal, ref stackMark);
         }
 
-#if FEATURE_CORECLR
         internal ExecutionContext ExecutionContext
         {
             get { return m_ExecutionContext; } 
@@ -364,89 +330,12 @@ namespace System.Threading {
         {
             get { return m_SynchronizationContext; }
             set { m_SynchronizationContext = value; }
-        }      
-#else // !FEATURE_CORECLR
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        internal ExecutionContext.Reader GetExecutionContextReader()
-        {
-            return new ExecutionContext.Reader(m_ExecutionContext);
-        }
-
-        internal bool ExecutionContextBelongsToCurrentScope
-        {
-            get { return !m_ExecutionContextBelongsToOuterScope; }
-            set { m_ExecutionContextBelongsToOuterScope = !value; }
-        }
-
-#if DEBUG
-        internal bool ForbidExecutionContextMutation
-        {
-            set { m_ForbidExecutionContextMutation = value; }
-        }
-#endif
-
-        // note: please don't access this directly from mscorlib.  Use GetMutableExecutionContext or GetExecutionContextReader instead.
-        public  ExecutionContext ExecutionContext
-        {
-            [SecuritySafeCritical]
-            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-            get
-            {
-                ExecutionContext result;
-                if (this == Thread.CurrentThread)
-                    result = GetMutableExecutionContext();
-                else
-                    result = m_ExecutionContext;
-
-                return result;
-            }
-        }
-
-        [SecurityCritical]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-        internal ExecutionContext GetMutableExecutionContext()
-        {
-            Contract.Assert(Thread.CurrentThread == this);
-#if DEBUG
-            Contract.Assert(!m_ForbidExecutionContextMutation);
-#endif
-            if (m_ExecutionContext == null)
-            {
-                m_ExecutionContext = new ExecutionContext();
-            }
-            else if (!ExecutionContextBelongsToCurrentScope)
-            {
-                ExecutionContext copy = m_ExecutionContext.CreateMutableCopy();
-                m_ExecutionContext = copy;
-            }
-
-            ExecutionContextBelongsToCurrentScope = true;
-            return m_ExecutionContext;
-        }
-
-        [SecurityCritical]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        internal void SetExecutionContext(ExecutionContext value, bool belongsToCurrentScope) 
-        {
-            m_ExecutionContext = value;
-            ExecutionContextBelongsToCurrentScope = belongsToCurrentScope;
-        }
-
-        [SecurityCritical]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        internal void SetExecutionContext(ExecutionContext.Reader value, bool belongsToCurrentScope)
-        {
-            m_ExecutionContext = value.DangerousGetRawExecutionContext();
-            ExecutionContextBelongsToCurrentScope = belongsToCurrentScope;
         }
-#endif //!FEATURE_CORECLR
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void StartInternal(IPrincipal principal, ref StackCrawlMark stackMark);
 #if FEATURE_COMPRESSEDSTACK
         /// <internalonly/>
-        [System.Security.SecurityCritical]  // auto-generated_required
         [DynamicSecurityMethodAttribute()]
         [Obsolete("Thread.SetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")]         
         public void SetCompressedStack( CompressedStack stack )
@@ -454,17 +343,14 @@ namespace System.Threading {
             throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ThreadAPIsNotSupported"));
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal extern IntPtr SetAppDomainStack( SafeCompressedStackHandle csHandle);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         internal extern void RestoreAppDomainStack( IntPtr appDomainStack);
         
 
         /// <internalonly/>
-        [System.Security.SecurityCritical]  // auto-generated_required
         [Obsolete("Thread.GetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")]
         public CompressedStack GetCompressedStack()
         {
@@ -476,7 +362,6 @@ namespace System.Threading {
         // Helper method to get a logical thread ID for StringBuilder (for
         // correctness) and for FileStream's async code path (for perf, to
         // avoid creating a Thread instance).
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern static IntPtr InternalGetCurrentThread();
 
@@ -495,34 +380,6 @@ namespace System.Threading {
         ** If Abort is called twice on the same thread, a DuplicateThreadAbort
         ** exception is thrown.
         =========================================================================*/
-
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread=true)]
-        public void Abort(Object stateInfo)
-        {
-            // If two aborts come at the same time, it is possible that the state info
-            //  gets set by one, and the actual abort gets delivered by another. But this
-            //  is not distinguishable by an application.
-            // The accessor helper will only set the value if it isn't already set,
-            //  and that particular bit of native code can test much faster than this
-            //  code could, because testing might cause a cross-appdomain marshalling.
-            AbortReason = stateInfo;
-
-            // Note: we demand ControlThread permission, then call AbortInternal directly
-            // rather than delegating to the Abort() function below. We do this to ensure
-            // that only callers with ControlThread are allowed to change the AbortReason
-            // of the thread. We call AbortInternal directly to avoid demanding the same
-            // permission twice.
-            AbortInternal();
-        }
-#endif
-
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
 #pragma warning disable 618
         [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
 #pragma warning restore 618
@@ -533,138 +390,9 @@ namespace System.Threading {
 
         // Internal helper (since we can't place security demands on
         // ecalls/fcalls).
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void AbortInternal();
 
-#if !FEATURE_CORECLR
-        /*=========================================================================
-        ** Resets a thread abort.
-        ** Should be called by trusted code only
-          =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread=true)]
-        public static void ResetAbort()
-        {
-            Thread thread = Thread.CurrentThread;
-            if ((thread.ThreadState & ThreadState.AbortRequested) == 0)
-                throw new ThreadStateException(Environment.GetResourceString("ThreadState_NoAbortRequested"));
-            thread.ResetAbortNative();
-            thread.ClearAbortReason();
-        }
-
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private extern void ResetAbortNative();
-
-        /*=========================================================================
-        ** Suspends the thread. If the thread is already suspended, this call has
-        ** no effect.
-        **
-        ** Exceptions: ThreadStateException if the thread has not been started or
-        **             it is dead.
-        =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [Obsolete("Thread.Suspend has been deprecated.  Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources.  http://go.microsoft.com/fwlink/?linkid=14202", false)][SecurityPermission(SecurityAction.Demand, ControlThread=true)]
-        [SecurityPermission(SecurityAction.Demand, ControlThread=true)]
-        public void Suspend() { SuspendInternal(); }
-
-        // Internal helper (since we can't place security demands on
-        // ecalls/fcalls).
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private extern void SuspendInternal();
-
-        /*=========================================================================
-        ** Resumes a thread that has been suspended.
-        **
-        ** Exceptions: ThreadStateException if the thread has not been started or
-        **             it is dead or it isn't in the suspended state.
-        =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [Obsolete("Thread.Resume has been deprecated.  Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources.  http://go.microsoft.com/fwlink/?linkid=14202", false)]
-        [SecurityPermission(SecurityAction.Demand, ControlThread=true)]
-        public void Resume() { ResumeInternal(); }
-
-        // Internal helper (since we can't place security demands on
-        // ecalls/fcalls).
-        [System.Security.SecurityCritical]  // auto-generated
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private extern void ResumeInternal();
-
-        /*=========================================================================
-        ** Interrupts a thread that is inside a Wait(), Sleep() or Join().  If that
-        ** thread is not currently blocked in that manner, it will be interrupted
-        ** when it next begins to block.
-        =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
-        public new void Interrupt() => base.Interrupt();
-
-        /*=========================================================================
-        ** Returns the priority of the thread.
-        **
-        ** Exceptions: ThreadStateException if the thread is dead.
-        =========================================================================*/
-
-        public new ThreadPriority Priority
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            get
-            {
-                return base.Priority;
-            }
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [HostProtection(SelfAffectingThreading = true)]
-            set
-            {
-                base.Priority = value;
-            }
-        }
-
-        /*=========================================================================
-        ** Returns true if the thread has been started and is not dead.
-        =========================================================================*/
-        public new bool IsAlive
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            get
-            {
-                return base.IsAlive;
-            }
-        }
-
-        /*=========================================================================
-        ** Returns true if the thread is a threadpool thread.
-        =========================================================================*/
-        public new bool IsThreadPoolThread
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            get
-            {
-                return base.IsThreadPoolThread;
-            }
-        }
-
-        /*=========================================================================
-        ** Waits for the thread to die or for timeout milliseconds to elapse.
-        ** Returns true if the thread died, or false if the wait timed out. If
-        ** Timeout.Infinite is given as the parameter, no timeout will occur.
-        **
-        ** Exceptions: ArgumentException if timeout < 0.
-        **             ThreadInterruptedException if the thread is interrupted while waiting.
-        **             ThreadStateException if the thread has not been started yet.
-        =========================================================================*/
-        [System.Security.SecuritySafeCritical]
-        [HostProtection(Synchronization = true, ExternalThreading = true)]
-        public new void Join() => base.Join();
-
-        [System.Security.SecuritySafeCritical]
-        [HostProtection(Synchronization = true, ExternalThreading = true)]
-        public new bool Join(int millisecondsTimeout) => base.Join(millisecondsTimeout);
-#endif // !FEATURE_CORECLR
-
-        [HostProtection(Synchronization=true, ExternalThreading=true)]
         public bool Join(TimeSpan timeout)
         {
             long tm = (long)timeout.TotalMilliseconds;
@@ -682,11 +410,9 @@ namespace System.Threading {
         ** Exceptions: ArgumentException if timeout < 0.
         **             ThreadInterruptedException if the thread is interrupted while sleeping.
         =========================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void SleepInternal(int millisecondsTimeout);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static new void Sleep(int millisecondsTimeout)
         {
             SleepInternal(millisecondsTimeout);
@@ -708,29 +434,21 @@ namespace System.Threading {
            only take a few machine instructions.  Calling this API is preferable to coding
            a explict busy loop because the hardware can be informed that it is busy waiting. */
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [HostProtection(Synchronization=true,ExternalThreading=true)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private static extern void SpinWaitInternal(int iterations);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [HostProtection(Synchronization=true,ExternalThreading=true)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static new void SpinWait(int iterations)
         {
             SpinWaitInternal(iterations);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
-        [HostProtection(Synchronization = true, ExternalThreading = true)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         private static extern bool YieldInternal();
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [HostProtection(Synchronization = true, ExternalThreading = true)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         public static new bool Yield()
         {
@@ -738,39 +456,19 @@ namespace System.Threading {
         }
         
         public static new Thread CurrentThread {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
             get {
                 Contract.Ensures(Contract.Result<Thread>() != null);
                 return GetCurrentThreadNative();
             }
         }
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private static extern Thread GetCurrentThreadNative();
 
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetStartHelper(Delegate start, int maxStackSize)
         {
-#if FEATURE_CORECLR
             // We only support default stacks in CoreCLR
-            Contract.Assert(maxStackSize == 0);
-#else
-            // Only fully-trusted code is allowed to create "large" stacks.  Partial-trust falls back to
-            // the default stack size.
-            ulong defaultStackSize = GetProcessDefaultStackSize();
-            if ((ulong)(uint)maxStackSize > defaultStackSize)
-            {
-                try
-                {
-                    SecurityPermission.Demand(PermissionType.FullTrust);
-                }
-                catch (SecurityException)
-                {
-                    maxStackSize = (int)Math.Min(defaultStackSize, (ulong)(uint)int.MaxValue);
-                }
-            }
-#endif
+            Debug.Assert(maxStackSize == 0);
 
             ThreadHelper threadStartCallBack = new ThreadHelper(start);
             if(start is ThreadStart)
@@ -783,7 +481,6 @@ namespace System.Threading {
             }                
         }
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern ulong GetProcessDefaultStackSize();
@@ -792,14 +489,12 @@ namespace System.Threading {
         ** PRIVATE Sets the IThreadable interface for the thread. Assumes that
         ** start != null.
         =========================================================================*/
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void SetStart(Delegate start, int maxStackSize);
 
         /*=========================================================================
         ** Clean up the thread when it goes away.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         ~Thread()
         {
@@ -807,56 +502,10 @@ namespace System.Threading {
             InternalFinalize();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void InternalFinalize();
 
-#if !FEATURE_CORECLR
-#if FEATURE_COMINTEROP
-        [System.Security.SecurityCritical]  // auto-generated
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        public new void DisableComObjectEagerCleanup()
-        {
-            base.DisableComObjectEagerCleanup();
-        }
-#endif // FEATURE_COMINTEROP
-
-        /*=========================================================================
-        ** Return whether or not this thread is a background thread.  Background
-        ** threads do not affect when the Execution Engine shuts down.
-        **
-        ** Exceptions: ThreadStateException if the thread is dead.
-        =========================================================================*/
-        public new bool IsBackground
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            get
-            {
-                return base.IsBackground;
-            }
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [HostProtection(SelfAffectingThreading = true)]
-            set
-            {
-                base.IsBackground = value;
-            }
-        }
-
-        /*=========================================================================
-        ** Return the thread state as a consistent set of bits.  This is more
-        ** general then IsAlive or IsBackground.
-        =========================================================================*/
-        public new ThreadState ThreadState
-        {
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            get
-            {
-                return base.ThreadState;
-            }
-        }
-#endif // !FEATURE_CORECLR
-
 #if FEATURE_COMINTEROP_APARTMENT_SUPPORT
         /*=========================================================================
         ** An unstarted thread can be marked to indicate that it will host a
@@ -868,31 +517,17 @@ namespace System.Threading {
         [Obsolete("The ApartmentState property has been deprecated.  Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)]
         public ApartmentState ApartmentState
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return (ApartmentState)GetApartmentStateNative();
             }
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [HostProtection(Synchronization=true, SelfAffectingThreading=true)]
             set
             {
                 SetApartmentStateNative((int)value, true);
             }
         }
 
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        public new ApartmentState GetApartmentState() => base.GetApartmentState();
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [HostProtection(Synchronization=true, SelfAffectingThreading=true)]
-        public new bool TrySetApartmentState(ApartmentState state) => base.TrySetApartmentState(state);
-#endif // !FEATURE_CORECLR
-
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [HostProtection(Synchronization=true, SelfAffectingThreading=true)]
         public void SetApartmentState(ApartmentState state)
         {
             bool result = SetApartmentStateHelper(state, true);
@@ -900,7 +535,6 @@ namespace System.Threading {
                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ApartmentStateSwitchFailed"));
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern void StartupSetApartmentStateInternal();
 #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
@@ -909,7 +543,6 @@ namespace System.Threading {
         ** Allocates an un-named data slot. The slot is allocated on ALL the
         ** threads.
         =========================================================================*/
-        [HostProtection(SharedState=true, ExternalThreading=true)]
         public static LocalDataStoreSlot AllocateDataSlot()
         {
             return LocalDataStoreManager.AllocateDataSlot();
@@ -920,7 +553,6 @@ namespace System.Threading {
         ** threads.  Named data slots are "public" and can be manipulated by
         ** anyone.
         =========================================================================*/
-        [HostProtection(SharedState=true, ExternalThreading=true)]
         public static LocalDataStoreSlot AllocateNamedDataSlot(String name)
         {
             return LocalDataStoreManager.AllocateNamedDataSlot(name);
@@ -931,7 +563,6 @@ namespace System.Threading {
         ** allocated.  Named data slots are "public" and can be manipulated by
         ** anyone.
         =========================================================================*/
-        [HostProtection(SharedState=true, ExternalThreading=true)]
         public static LocalDataStoreSlot GetNamedDataSlot(String name)
         {
             return LocalDataStoreManager.GetNamedDataSlot(name);
@@ -942,7 +573,6 @@ namespace System.Threading {
         ** threads.  Named data slots are "public" and can be manipulated by
         ** anyone.
         =========================================================================*/
-        [HostProtection(SharedState=true, ExternalThreading=true)]
         public static void FreeNamedDataSlot(String name)
         {
             LocalDataStoreManager.FreeNamedDataSlot(name);
@@ -951,7 +581,6 @@ namespace System.Threading {
         /*=========================================================================
         ** Retrieves the value from the specified slot on the current thread, for that thread's current domain.
         =========================================================================*/
-        [HostProtection(SharedState=true, ExternalThreading=true)]
         public static Object GetData(LocalDataStoreSlot slot)
         {
             LocalDataStoreHolder dls = s_LocalDataStore;
@@ -968,7 +597,6 @@ namespace System.Threading {
         /*=========================================================================
         ** Sets the data in the specified slot on the currently running thread, for that thread's current domain.
         =========================================================================*/
-        [HostProtection(SharedState=true, ExternalThreading=true)]
         public static void SetData(LocalDataStoreSlot slot, Object data)
         {
             LocalDataStoreHolder dls = s_LocalDataStore;
@@ -1009,7 +637,6 @@ namespace System.Threading {
         // default domain to lookup resources. See Environment.cs for more details.
         // 
 #if FEATURE_LEAK_CULTURE_INFO
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static extern private bool nativeGetSafeCulture(Thread t, int appDomainId, bool isUI, ref CultureInfo safeCulture);
 #endif // FEATURE_LEAK_CULTURE_INFO
@@ -1040,8 +667,6 @@ namespace System.Threading {
                 }
             }
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [HostProtection(ExternalThreading=true)]
             set {
                 if (value == null) {
                     throw new ArgumentNullException(nameof(value));
@@ -1084,7 +709,6 @@ namespace System.Threading {
         }
 
 #if FEATURE_LEAK_CULTURE_INFO
-        [System.Security.SecuritySafeCritical]  // auto-generated
 #endif
         internal CultureInfo GetCurrentUICultureNoAppX() {
 
@@ -1117,7 +741,6 @@ namespace System.Threading {
 
         // This returns the exposed context for a given context ID.
 #if FEATURE_LEAK_CULTURE_INFO
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         static extern private bool nativeSetThreadUILocale(String locale);
 #endif
@@ -1149,9 +772,7 @@ namespace System.Threading {
                 }
             }
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
 #if FEATURE_LEAK_CULTURE_INFO
-            [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
 #endif
             set {
                 if (null==value) {
@@ -1190,7 +811,6 @@ namespace System.Threading {
         }
 
 #if FEATURE_LEAK_CULTURE_INFO
-        [System.Security.SecuritySafeCritical]  // auto-generated
 #endif
         private CultureInfo GetCurrentCultureNoAppX() {
 
@@ -1221,7 +841,6 @@ namespace System.Threading {
         }
 
 #if !FEATURE_LEAK_CULTURE_INFO
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void nativeInitCultureAccessors();
@@ -1231,14 +850,11 @@ namespace System.Threading {
         ** Returns the current domain in which current thread is running.
         ======================================================================*/
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern AppDomain GetDomainInternal();
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern AppDomain GetFastDomainInternal();
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static AppDomain GetDomain()
         {
             Contract.Ensures(Contract.Result<AppDomain>() != null);
@@ -1268,8 +884,6 @@ namespace System.Threading {
             get {
                 return m_Name;
             }
-            [System.Security.SecuritySafeCritical]  // auto-generated
-            [HostProtection(ExternalThreading=true)]
             set {
                 lock(this) {
                     if (m_Name != null)
@@ -1281,13 +895,11 @@ namespace System.Threading {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void InformThreadNameChange(ThreadHandle t, String name, int len);
 
         internal Object AbortReason {
-            [System.Security.SecurityCritical]  // auto-generated
             get {
                 object result = null;
                 try
@@ -1300,46 +912,9 @@ namespace System.Threading {
                 }
                 return result;
             }
-            [System.Security.SecurityCritical]  // auto-generated
             set { SetAbortReason(value); }
         }
 
-#if !FEATURE_CORECLR
-        /*
-         *  This marks the beginning of a critical code region.
-         */
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [HostProtection(Synchronization=true, ExternalThreading=true)]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-        public static extern void BeginCriticalRegion();
-
-        /*
-         *  This marks the end of a critical code region.
-         */
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        [HostProtection(Synchronization=true, ExternalThreading=true)]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        public static extern void EndCriticalRegion();
-
-        /*
-         *  This marks the beginning of a code region that requires thread affinity.
-         */
-        [System.Security.SecurityCritical]  // auto-generated_required
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-        public static extern void BeginThreadAffinity();
-
-        /*
-         *  This marks the end of a code region that requires thread affinity.
-         */
-        [System.Security.SecurityCritical]  // auto-generated_required
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-        public static extern void EndThreadAffinity();
-#endif // !FEATURE_CORECLR
-
         /*=========================================================================
         ** Volatile Read & Write and MemoryBarrier methods.
         ** Provides the ability to read and write values ensuring that the values
@@ -1551,7 +1126,6 @@ namespace System.Threading {
             address = value;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern void MemoryBarrier();
 
@@ -1568,45 +1142,20 @@ namespace System.Threading {
             }
         }
 
-#if !FEATURE_CORECLR
-        void _Thread.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Thread.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Thread.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Thread.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
         // Helper function to set the AbortReason for a thread abort.
         //  Checks that they're not alredy set, and then atomically updates
         //  the reason info (object + ADID).
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void SetAbortReason(Object o);
     
         // Helper function to retrieve the AbortReason from a thread
         //  abort.  Will perform cross-AppDomain marshalling if the object
         //  lives in a different AppDomain from the requester.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern Object GetAbortReason();
     
         // Helper function to clear the AbortReason.  Takes care of
         //  AppDomain related cleanup if required.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void ClearAbortReason();
 
index 11c8744..09ad4e1 100644 (file)
@@ -39,7 +39,6 @@ namespace System.Threading
    
         public Object ExceptionState 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {return Thread.CurrentThread.AbortReason;}
         }
     }
index 1af377f..2b996cb 100644 (file)
@@ -15,9 +15,9 @@
 //
 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 
-using System.Diagnostics;
 using System.Collections.Generic;
 using System.Security.Permissions;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 namespace System.Threading
@@ -35,7 +35,6 @@ namespace System.Threading
     /// </remarks>
     [DebuggerTypeProxy(typeof(SystemThreading_ThreadLocalDebugView<>))]
     [DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")]
-    [HostProtection(Synchronization = true, ExternalThreading = true)]
     public class ThreadLocal<T> : IDisposable
     {
 
@@ -193,7 +192,7 @@ namespace System.Threading
 
                 if (id < 0 || !m_initialized)
                 {
-                    Contract.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
+                    Debug.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
 
                     // Handle double Dispose calls or disposal of an instance whose constructor threw an exception.
                     return;
@@ -550,7 +549,7 @@ namespace System.Threading
         /// </summary>
         private void GrowTable(ref LinkedSlotVolatile[] table, int minLength)
         {
-            Contract.Assert(table.Length < minLength);
+            Debug.Assert(table.Length < minLength);
 
             // Determine the size of the new table and allocate it.
             int newLen = GetNewTableSize(minLength);
@@ -588,7 +587,7 @@ namespace System.Threading
                 // Intentionally return a value that will result in an OutOfMemoryException
                 return int.MaxValue;
             }
-            Contract.Assert(minSize > 0);
+            Debug.Assert(minSize > 0);
 
             //
             // Round up the size to the next power of 2
@@ -737,7 +736,7 @@ namespace System.Threading
             ~FinalizationHelper()
             {
                 LinkedSlotVolatile[] slotArray = SlotArray;
-                Contract.Assert(slotArray != null);
+                Debug.Assert(slotArray != null);
 
                 for (int i = 0; i < slotArray.Length; i++)
                 {
@@ -765,7 +764,7 @@ namespace System.Threading
                             }
 
                             // Since the list uses a dummy head node, the Previous reference should never be null.
-                            Contract.Assert(linkedSlot.Previous != null);
+                            Debug.Assert(linkedSlot.Previous != null);
                             linkedSlot.Previous.Next = linkedSlot.Next;
                         }
                     }
index c11e149..451b15d 100644 (file)
@@ -29,9 +29,6 @@
 namespace System.Threading
 {
     using System.Security;
-#if FEATURE_REMOTING
-    using System.Runtime.Remoting;
-#endif
     using System.Security.Permissions;
     using System;
     using Microsoft.Win32;
@@ -39,6 +36,7 @@ namespace System.Threading
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.InteropServices;
     using System.Collections.Generic;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Diagnostics.CodeAnalysis;
     using System.Diagnostics.Tracing;
@@ -56,10 +54,8 @@ namespace System.Threading
         public static volatile bool vmTpInitialized;
         public static bool enableWorkerTracking;
 
-        [SecurityCritical]
         public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
 
-        [System.Security.SecuritySafeCritical] // static constructors should be safe to call
         static ThreadPoolGlobals()
         {
         }
@@ -174,7 +170,7 @@ namespace System.Threading
                             //
                             m_headIndex = m_headIndex & m_mask;
                             m_tailIndex = tail = m_tailIndex & m_mask;
-                            Contract.Assert(m_headIndex <= m_tailIndex);
+                            Debug.Assert(m_headIndex <= m_tailIndex);
                         }
                     }
                     finally
@@ -236,7 +232,7 @@ namespace System.Threading
                     IThreadPoolWorkItem unused;
                     if (LocalPop(out unused))
                     {
-                        Contract.Assert(unused == obj);
+                        Debug.Assert(unused == obj);
                         return true;
                     }
                     return false;
@@ -435,23 +431,23 @@ namespace System.Threading
                 upper = (i >> 16) & SixteenBits;
                 lower = i & SixteenBits;
 
-                Contract.Assert(upper >= lower);
-                Contract.Assert(upper <= nodes.Length);
-                Contract.Assert(lower <= nodes.Length);
-                Contract.Assert(upper >= 0);
-                Contract.Assert(lower >= 0);
+                Debug.Assert(upper >= lower);
+                Debug.Assert(upper <= nodes.Length);
+                Debug.Assert(lower <= nodes.Length);
+                Debug.Assert(upper >= 0);
+                Debug.Assert(lower >= 0);
             }
 
             bool CompareExchangeIndexes(ref int prevUpper, int newUpper, ref int prevLower, int newLower)
             {
-                Contract.Assert(newUpper >= newLower);
-                Contract.Assert(newUpper <= nodes.Length);
-                Contract.Assert(newLower <= nodes.Length);
-                Contract.Assert(newUpper >= 0);
-                Contract.Assert(newLower >= 0);
-                Contract.Assert(newUpper >= prevUpper);
-                Contract.Assert(newLower >= prevLower);
-                Contract.Assert(newUpper == prevUpper ^ newLower == prevLower);
+                Debug.Assert(newUpper >= newLower);
+                Debug.Assert(newUpper <= nodes.Length);
+                Debug.Assert(newLower <= nodes.Length);
+                Debug.Assert(newUpper >= 0);
+                Debug.Assert(newLower >= 0);
+                Debug.Assert(newUpper >= prevUpper);
+                Debug.Assert(newLower >= prevLower);
+                Debug.Assert(newUpper == prevUpper ^ newLower == prevLower);
 
                 int oldIndexes = (prevUpper << 16) | (prevLower & SixteenBits);
                 int newIndexes = (newUpper << 16) | (newLower & SixteenBits);
@@ -464,7 +460,7 @@ namespace System.Threading
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
             public QueueSegment()
             {
-                Contract.Assert(QueueSegmentLength <= SixteenBits);
+                Debug.Assert(QueueSegmentLength <= SixteenBits);
                 nodes = new IThreadPoolWorkItem[QueueSegmentLength];
             }
 
@@ -487,7 +483,7 @@ namespace System.Threading
                 // with a busy-wait loop, waiting for the element to become non-null.  This implies
                 // that we can never store null nodes in this data structure.
                 //
-                Contract.Assert(null != node);
+                Debug.Assert(null != node);
 
                 int upper, lower;
                 GetIndexes(out upper, out lower);
@@ -499,7 +495,7 @@ namespace System.Threading
 
                     if (CompareExchangeIndexes(ref upper, upper + 1, ref lower, lower))
                     {
-                        Contract.Assert(Volatile.Read(ref nodes[upper]) == null);
+                        Debug.Assert(Volatile.Read(ref nodes[upper]) == null);
                         Volatile.Write(ref nodes[upper], node);
                         return true;
                     }
@@ -557,7 +553,6 @@ namespace System.Threading
             loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool|FrameworkEventSource.Keywords.ThreadTransfer);
         }
 
-        [SecurityCritical]
         public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue()
         {
             if (null == ThreadPoolWorkQueueThreadLocals.threadLocals)
@@ -565,7 +560,6 @@ namespace System.Threading
             return ThreadPoolWorkQueueThreadLocals.threadLocals;
         }
 
-        [SecurityCritical]
         internal void EnsureThreadRequested()
         {
             //
@@ -586,7 +580,6 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         internal void MarkThreadRequestSatisfied()
         {
             //
@@ -607,7 +600,6 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         public void Enqueue(IThreadPoolWorkItem callback, bool forceGlobal)
         {
             ThreadPoolWorkQueueThreadLocals tl = null;
@@ -640,7 +632,6 @@ namespace System.Threading
             EnsureThreadRequested();
         }
 
-        [SecurityCritical]
         internal bool LocalFindAndPop(IThreadPoolWorkItem callback)
         {
             ThreadPoolWorkQueueThreadLocals tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
@@ -650,7 +641,6 @@ namespace System.Threading
             return tl.workStealingQueue.LocalFindAndPop(callback);
         }
 
-        [SecurityCritical]
         public void Dequeue(ThreadPoolWorkQueueThreadLocals tl, out IThreadPoolWorkItem callback, out bool missedSteal)
         {
             callback = null;
@@ -658,7 +648,7 @@ namespace System.Threading
             WorkStealingQueue wsq = tl.workStealingQueue;
 
             if (wsq.LocalPop(out callback))
-                Contract.Assert(null != callback);
+                Debug.Assert(null != callback);
 
             if (null == callback)
             {
@@ -667,7 +657,7 @@ namespace System.Threading
                 {
                     if (tail.TryDequeue(out callback))
                     {
-                        Contract.Assert(null != callback);
+                        Debug.Assert(null != callback);
                         break;
                     }
 
@@ -697,7 +687,7 @@ namespace System.Threading
                         otherQueue != wsq &&
                         otherQueue.TrySteal(out callback, ref missedSteal))
                     {
-                        Contract.Assert(null != callback);
+                        Debug.Assert(null != callback);
                         break;
                     }
                     c--;
@@ -705,7 +695,6 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         static internal bool Dispatch()
         {
             var workQueue = ThreadPoolGlobals.workQueue;
@@ -856,7 +845,7 @@ namespace System.Threading
             }
 
             // we can never reach this point, but the C# compiler doesn't know that, because it doesn't know the ThreadAbortException will be reraised above.
-            Contract.Assert(false);
+            Debug.Assert(false);
             return true;
         }
     }
@@ -865,7 +854,6 @@ namespace System.Threading
     internal sealed class ThreadPoolWorkQueueThreadLocals
     {
         [ThreadStatic]
-        [SecurityCritical]
         public static ThreadPoolWorkQueueThreadLocals threadLocals;
 
         public readonly ThreadPoolWorkQueue workQueue;
@@ -879,7 +867,6 @@ namespace System.Threading
             ThreadPoolWorkQueue.allThreadQueues.Add(workStealingQueue);
         }
 
-        [SecurityCritical]
         private void CleanUp()
         {
             if (null != workStealingQueue)
@@ -896,7 +883,7 @@ namespace System.Threading
                             IThreadPoolWorkItem cb = null;
                             if (workStealingQueue.LocalPop(out cb))
                             {
-                                Contract.Assert(null != cb);
+                                Debug.Assert(null != cb);
                                 workQueue.Enqueue(cb, true);
                             }
                             else
@@ -911,7 +898,6 @@ namespace System.Threading
             }
         }
 
-        [SecuritySafeCritical]
         ~ThreadPoolWorkQueueThreadLocals()
         {
             // Since the purpose of calling CleanUp is to transfer any pending workitems into the global
@@ -928,7 +914,6 @@ namespace System.Threading
     {
         private static IntPtr InvalidHandle
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 return Win32Native.INVALID_HANDLE_VALUE;
@@ -939,9 +924,6 @@ namespace System.Threading
         private bool bReleaseNeeded = false;
         private volatile int m_lock = 0;
 
-        #if FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical] // auto-generated
-        #endif
         internal RegisteredWaitHandleSafe()
         {
             registeredWaitHandle = InvalidHandle;
@@ -957,7 +939,6 @@ namespace System.Threading
             registeredWaitHandle = handle;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         internal void SetWaitObject(WaitHandle waitObject)
         {
@@ -976,7 +957,6 @@ namespace System.Threading
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         internal bool Unregister(
              WaitHandle     waitObject          // object to be notified when all callbacks to delegates have completed
@@ -1034,7 +1014,6 @@ namespace System.Threading
             return (registeredWaitHandle != InvalidHandle && registeredWaitHandle != IntPtr.Zero);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         ~RegisteredWaitHandleSafe()
         {
             // if the app has already unregistered the wait, there is nothing to cleanup
@@ -1085,11 +1064,9 @@ namespace System.Threading
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void WaitHandleCleanupNative(IntPtr handle);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool UnregisterWaitNative(IntPtr handle, SafeHandle waitObject);
     }
@@ -1108,14 +1085,12 @@ namespace System.Threading
            internalRegisteredWait.SetHandle(handle);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetWaitObject(WaitHandle waitObject)
         {
            internalRegisteredWait.SetWaitObject(waitObject);
         }
 
     
-[System.Security.SecuritySafeCritical]  // auto-generated
 [System.Runtime.InteropServices.ComVisible(true)]
         // This is the only public method on this class
         public bool Unregister(
@@ -1140,7 +1115,6 @@ namespace System.Threading
     //
     internal static class _ThreadPoolWaitCallback
     {
-        [System.Security.SecurityCritical]
         static internal bool PerformWaitCallback()
         {
             return ThreadPoolWorkQueue.Dispatch();
@@ -1158,15 +1132,12 @@ namespace System.Threading
     //
     internal interface IThreadPoolWorkItem
     {
-        [SecurityCritical]
         void ExecuteWorkItem();
-        [SecurityCritical]
         void MarkAborted(ThreadAbortException tae);
     }
 
     internal sealed class QueueUserWorkItemCallback : IThreadPoolWorkItem
     {
-        [System.Security.SecuritySafeCritical]
         static QueueUserWorkItemCallback() {}
 
         private WaitCallback callback;
@@ -1178,7 +1149,7 @@ namespace System.Threading
 
         ~QueueUserWorkItemCallback()
         {
-            Contract.Assert(
+            Debug.Assert(
                 executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(), 
                 "A QueueUserWorkItemCallback was never called!");
         }
@@ -1186,13 +1157,12 @@ namespace System.Threading
         void MarkExecuted(bool aborted)
         {
             GC.SuppressFinalize(this);
-            Contract.Assert(
+            Debug.Assert(
                 0 == Interlocked.Exchange(ref executed, 1) || aborted,
                 "A QueueUserWorkItemCallback was called twice!");
         }
 #endif
 
-        [SecurityCritical]
         internal QueueUserWorkItemCallback(WaitCallback waitCallback, Object stateObj, ExecutionContext ec)
         {
             callback = waitCallback;
@@ -1200,7 +1170,6 @@ namespace System.Threading
             context = ec;
         }
 
-        [SecurityCritical]
         void IThreadPoolWorkItem.ExecuteWorkItem()
         {
 #if DEBUG
@@ -1219,7 +1188,6 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
         {
 #if DEBUG
@@ -1229,22 +1197,19 @@ namespace System.Threading
 #endif
         }
 
-        [System.Security.SecurityCritical]
         static internal ContextCallback ccb = new ContextCallback(WaitCallback_Context);
 
-        [System.Security.SecurityCritical]
         static private void WaitCallback_Context(Object state)
         {
             QueueUserWorkItemCallback obj = (QueueUserWorkItemCallback)state;
             WaitCallback wc = obj.callback as WaitCallback;
-            Contract.Assert(null != wc);
+            Debug.Assert(null != wc);
             wc(obj.state);
         }
     }
 
     internal sealed class QueueUserWorkItemCallbackDefaultContext : IThreadPoolWorkItem
     {
-        [System.Security.SecuritySafeCritical]
         static QueueUserWorkItemCallbackDefaultContext() { }
 
         private WaitCallback callback;
@@ -1255,7 +1220,7 @@ namespace System.Threading
 
         ~QueueUserWorkItemCallbackDefaultContext()
         {
-            Contract.Assert(
+            Debug.Assert(
                 executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
                 "A QueueUserWorkItemCallbackDefaultContext was never called!");
         }
@@ -1263,20 +1228,18 @@ namespace System.Threading
         void MarkExecuted(bool aborted)
         {
             GC.SuppressFinalize(this);
-            Contract.Assert(
+            Debug.Assert(
                 0 == Interlocked.Exchange(ref executed, 1) || aborted,
                 "A QueueUserWorkItemCallbackDefaultContext was called twice!");
         }
 #endif
 
-        [SecurityCritical]
         internal QueueUserWorkItemCallbackDefaultContext(WaitCallback waitCallback, Object stateObj)
         {
             callback = waitCallback;
             state = stateObj;
         }
 
-        [SecurityCritical]
         void IThreadPoolWorkItem.ExecuteWorkItem()
         {
 #if DEBUG
@@ -1285,7 +1248,6 @@ namespace System.Threading
             ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, ccb, this, true);
         }
 
-        [SecurityCritical]
         void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
         {
 #if DEBUG
@@ -1295,15 +1257,13 @@ namespace System.Threading
 #endif
         }
 
-        [System.Security.SecurityCritical]
         static internal ContextCallback ccb = new ContextCallback(WaitCallback_Context);
 
-        [System.Security.SecurityCritical]
         static private void WaitCallback_Context(Object state)
         {
             QueueUserWorkItemCallbackDefaultContext obj = (QueueUserWorkItemCallbackDefaultContext)state;
             WaitCallback wc = obj.callback as WaitCallback;
-            Contract.Assert(null != wc);
+            Debug.Assert(null != wc);
             obj.callback = null;
             wc(obj.state);
         }
@@ -1311,18 +1271,14 @@ namespace System.Threading
 
     internal class _ThreadPoolWaitOrTimerCallback
     {
-        [System.Security.SecuritySafeCritical]
         static _ThreadPoolWaitOrTimerCallback() {}
 
         WaitOrTimerCallback _waitOrTimerCallback;
         ExecutionContext _executionContext;
         Object _state;
-        [System.Security.SecurityCritical]
         static private ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
-        [System.Security.SecurityCritical]
         static private ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, Object state, bool compressStack, ref StackCrawlMark stackMark)
         {
             _waitOrTimerCallback = waitOrTimerCallback;
@@ -1337,13 +1293,11 @@ namespace System.Threading
             }
         }
         
-        [System.Security.SecurityCritical]
         static private void WaitOrTimerCallback_Context_t(Object state)
         {
             WaitOrTimerCallback_Context(state, true);
         }
 
-        [System.Security.SecurityCritical]
         static private void WaitOrTimerCallback_Context_f(Object state)
         {
             WaitOrTimerCallback_Context(state, false);
@@ -1356,11 +1310,10 @@ namespace System.Threading
         }
             
         // call back helper
-        [System.Security.SecurityCritical]  // auto-generated
         static internal void PerformWaitOrTimerCallback(Object state, bool timedOut)
         {
             _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state; 
-            Contract.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
+            Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
             // call directly if it is an unsafe call OR EC flow is suppressed
             if (helper._executionContext == null)
             {
@@ -1381,7 +1334,6 @@ namespace System.Threading
 
     }
 
-    [System.Security.SecurityCritical]
     [CLSCompliant(false)]
     [System.Runtime.InteropServices.ComVisible(true)]
     unsafe public delegate void IOCompletionCallback(uint errorCode, // Error code
@@ -1389,55 +1341,34 @@ namespace System.Threading
                                        NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
                                        );   
 
-    [HostProtection(Synchronization=true, ExternalThreading=true)]
     public static class ThreadPool
     {
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
-#pragma warning restore 618
         public static bool SetMaxThreads(int workerThreads, int completionPortThreads)
         {
             return SetMaxThreadsNative(workerThreads, completionPortThreads);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void GetMaxThreads(out int workerThreads, out int completionPortThreads)
         {
             GetMaxThreadsNative(out workerThreads, out completionPortThreads);
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
-#pragma warning restore 618
         public static bool SetMinThreads(int workerThreads, int completionPortThreads)
         {
             return SetMinThreadsNative(workerThreads, completionPortThreads);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void GetMinThreads(out int workerThreads, out int completionPortThreads)
         {
             GetMinThreadsNative(out workerThreads, out completionPortThreads);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static void GetAvailableThreads(out int workerThreads, out int completionPortThreads)
         {
             GetAvailableThreadsNative(out workerThreads, out completionPortThreads);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable            
         public static RegisteredWaitHandle RegisterWaitForSingleObject(  // throws RegisterWaitException
@@ -1452,7 +1383,6 @@ namespace System.Threading
             return RegisterWaitForSingleObject(waitObject,callBack,state,millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [CLSCompliant(false)]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(  // throws RegisterWaitException
@@ -1468,7 +1398,6 @@ namespace System.Threading
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         private static RegisteredWaitHandle RegisterWaitForSingleObject(  // throws RegisterWaitException
              WaitHandle             waitObject,
              WaitOrTimerCallback    callBack,
@@ -1479,12 +1408,6 @@ namespace System.Threading
              bool               compressStack
              )
         {
-#if FEATURE_REMOTING
-            if (RemotingServices.IsTransparentProxy(waitObject))
-                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy"));
-            Contract.EndContractBlock();
-#endif            
-
             RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle();
 
             if (callBack != null)
@@ -1511,7 +1434,6 @@ namespace System.Threading
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static RegisteredWaitHandle RegisterWaitForSingleObject(  // throws RegisterWaitException
              WaitHandle             waitObject,
@@ -1528,7 +1450,6 @@ namespace System.Threading
             return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable            
         public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(  // throws RegisterWaitException
              WaitHandle             waitObject,
@@ -1545,7 +1466,6 @@ namespace System.Threading
             return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static RegisteredWaitHandle RegisterWaitForSingleObject(  // throws RegisterWaitException
             WaitHandle          waitObject,
@@ -1562,7 +1482,6 @@ namespace System.Threading
             return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(  // throws RegisterWaitException
             WaitHandle          waitObject,
@@ -1579,7 +1498,6 @@ namespace System.Threading
             return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static RegisteredWaitHandle RegisterWaitForSingleObject(
                           WaitHandle            waitObject,
@@ -1598,7 +1516,6 @@ namespace System.Threading
             return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)tm,executeOnlyOnce,ref stackMark,true);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
                           WaitHandle            waitObject,
@@ -1617,7 +1534,6 @@ namespace System.Threading
             return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)tm,executeOnlyOnce,ref stackMark,false);
         }
             
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable    
         public static bool QueueUserWorkItem(           
              WaitCallback           callBack,     // NOTE: we do not expose options that allow the callback to be queued as an APC
@@ -1628,7 +1544,6 @@ namespace System.Threading
             return QueueUserWorkItemHelper(callBack,state,ref stackMark,true);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static bool QueueUserWorkItem(           
              WaitCallback           callBack     // NOTE: we do not expose options that allow the callback to be queued as an APC
@@ -1638,7 +1553,6 @@ namespace System.Threading
             return QueueUserWorkItemHelper(callBack,null,ref stackMark,true);
         }
     
-        [System.Security.SecurityCritical]  // auto-generated_required
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static bool UnsafeQueueUserWorkItem(
              WaitCallback           callBack,     // NOTE: we do not expose options that allow the callback to be queued as an APC
@@ -1652,7 +1566,6 @@ namespace System.Threading
         //ThreadPool has per-appdomain managed queue of work-items. The VM is
         //responsible for just scheduling threads into appdomains. After that
         //work-items are dispatched from the managed queue.
-        [System.Security.SecurityCritical]  // auto-generated
         private static bool QueueUserWorkItemHelper(WaitCallback callBack, Object state, ref StackCrawlMark stackMark, bool compressStack )
         {
             bool success =  true;
@@ -1692,10 +1605,9 @@ namespace System.Threading
             return success;
         }
 
-        [SecurityCritical]
         internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal)
         {
-            Contract.Assert(null != workItem);
+            Debug.Assert(null != workItem);
             EnsureVMInitialized();
 
             //
@@ -1709,17 +1621,15 @@ namespace System.Threading
         }
 
         // This method tries to take the target callback out of the current thread's queue.
-        [SecurityCritical]
         internal static bool TryPopCustomWorkItem(IThreadPoolWorkItem workItem)
         {
-            Contract.Assert(null != workItem);
+            Debug.Assert(null != workItem);
             if (!ThreadPoolGlobals.vmTpInitialized)
                 return false; //Not initialized, so there's no way this workitem was ever queued.
             return ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem);
         }
 
         // Get all workitems.  Called by TaskScheduler in its debugger hooks.
-        [SecurityCritical]
         internal static IEnumerable<IThreadPoolWorkItem> GetQueuedWorkItems()
         {
             return EnumerateQueuedWorkItems(ThreadPoolWorkQueue.allThreadQueues.Current, ThreadPoolGlobals.workQueue.queueTail);
@@ -1763,13 +1673,11 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         internal static IEnumerable<IThreadPoolWorkItem> GetLocallyQueuedWorkItems()
         {
             return EnumerateQueuedWorkItems(new ThreadPoolWorkQueue.WorkStealingQueue[] { ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue }, null);
         }
 
-        [SecurityCritical]
         internal static IEnumerable<IThreadPoolWorkItem> GetGloballyQueuedWorkItems()
         {
             return EnumerateQueuedWorkItems(null, ThreadPoolGlobals.workQueue.queueTail);
@@ -1797,41 +1705,34 @@ namespace System.Threading
 
         // This is the method the debugger will actually call, if it ends up calling
         // into ThreadPool directly.  Tests can use this to simulate a debugger, as well.
-        [SecurityCritical]
         internal static object[] GetQueuedWorkItemsForDebugger()
         {
             return ToObjectArray(GetQueuedWorkItems());
         }
 
-        [SecurityCritical]
         internal static object[] GetGloballyQueuedWorkItemsForDebugger()
         {
             return ToObjectArray(GetGloballyQueuedWorkItems());
         }
 
-        [SecurityCritical]
         internal static object[] GetLocallyQueuedWorkItemsForDebugger()
         {
             return ToObjectArray(GetLocallyQueuedWorkItems());
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         internal static extern bool RequestWorkerThread();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         unsafe private static extern bool PostQueuedCompletionStatus(NativeOverlapped* overlapped);
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [CLSCompliant(false)]
         unsafe public static bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped)
         {
             return PostQueuedCompletionStatus(overlapped);
         }
 
-        [SecurityCritical]
         private static void EnsureVMInitialized()
         {
             if (!ThreadPoolGlobals.vmTpInitialized)
@@ -1843,35 +1744,27 @@ namespace System.Threading
 
         // Native methods: 
     
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool SetMinThreadsNative(int workerThreads, int completionPortThreads);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool SetMaxThreadsNative(int workerThreads, int completionPortThreads);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void GetMinThreadsNative(out int workerThreads, out int completionPortThreads);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void GetMaxThreadsNative(out int workerThreads, out int completionPortThreads);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern void GetAvailableThreadsNative(out int workerThreads, out int completionPortThreads);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool NotifyWorkItemComplete();
 
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void ReportThreadStatus(bool isWorking);
 
-        [System.Security.SecuritySafeCritical]
         internal static void NotifyWorkItemProgress()
         {
             if (!ThreadPoolGlobals.vmTpInitialized)
@@ -1879,20 +1772,16 @@ namespace System.Threading
             NotifyWorkItemProgressNative();
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void NotifyWorkItemProgressNative();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool IsThreadPoolHosted();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void InitializeVMTp(ref bool enableWorkerTracking);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern IntPtr RegisterWaitForSingleObjectNative(  
              WaitHandle             waitHandle,
@@ -1905,11 +1794,7 @@ namespace System.Threading
              );
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated.  Please use ThreadPool.BindHandle(SafeHandle) instead.", false)]
-#pragma warning disable 618
-        [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         public static bool BindHandle(
              IntPtr osHandle
              )
@@ -1917,14 +1802,6 @@ namespace System.Threading
             return BindIOCompletionCallbackNative(osHandle);
         }
 
-        #if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-        #else
-        [System.Security.SecuritySafeCritical]
-        #endif        
-#pragma warning disable 618
-        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
         public static bool BindHandle(SafeHandle osHandle)
         {
             if (osHandle == null)
@@ -1944,7 +1821,6 @@ namespace System.Threading
             return ret;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private static extern bool BindIOCompletionCallbackNative(IntPtr fileHandle);
index c8a1a3b..5bfefcc 100644 (file)
@@ -14,6 +14,7 @@ namespace System.Threading
     using System.Runtime.InteropServices;
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Diagnostics.Tracing;
     using Microsoft.Win32.SafeHandles;
@@ -76,7 +77,6 @@ namespace System.Threading
         //
         private static int TickCount
         {
-            [SecuritySafeCritical]
             get
             {
 #if !FEATURE_PAL
@@ -102,7 +102,6 @@ namespace System.Threading
         //
         // We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded.
         //
-        [SecurityCritical]
         class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
         {
             public AppDomainTimerSafeHandle()
@@ -110,7 +109,6 @@ namespace System.Threading
             {
             }
 
-            [SecurityCritical]
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             protected override bool ReleaseHandle()
             {
@@ -118,14 +116,12 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         AppDomainTimerSafeHandle m_appDomainTimer;
 
         bool m_isAppDomainTimerScheduled;
         int m_currentAppDomainTimerStartTicks;
         uint m_currentAppDomainTimerDuration;
 
-        [SecuritySafeCritical]
         private bool EnsureAppDomainTimerFiresBy(uint requestedDuration)
         {
             //
@@ -154,14 +150,14 @@ namespace System.Threading
             // A later update during resume will re-schedule
             if(m_pauseTicks != 0)
             {
-                Contract.Assert(!m_isAppDomainTimerScheduled);
-                Contract.Assert(m_appDomainTimer == null);
+                Debug.Assert(!m_isAppDomainTimerScheduled);
+                Debug.Assert(m_appDomainTimer == null);
                 return true;
             }
  
             if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid)
             {
-                Contract.Assert(!m_isAppDomainTimerScheduled);
+                Debug.Assert(!m_isAppDomainTimerScheduled);
 
                 m_appDomainTimer = CreateAppDomainTimer(actualDuration);
                 if (!m_appDomainTimer.IsInvalid)
@@ -195,23 +191,19 @@ namespace System.Threading
         //
         // The VM calls this when the native timer fires.
         //
-        [SecuritySafeCritical]
         internal static void AppDomainTimerCallback()
         {
             Instance.FireNextTimers();
         }
 
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime);
 
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime);
 
-        [System.Security.SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
@@ -229,7 +221,6 @@ namespace System.Threading
 
         volatile int m_pauseTicks = 0; // Time when Pause was called
 
-        [SecurityCritical]
         internal void Pause()
         {
             lock(this)
@@ -245,7 +236,6 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         internal void Resume()
         {
             //
@@ -269,8 +259,8 @@ namespace System.Threading
                     TimerQueueTimer timer = m_timers;
                     while (timer != null)
                     {
-                        Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
-                        Contract.Assert(resumedTicks >= timer.m_startTicks);
+                        Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
+                        Debug.Assert(resumedTicks >= timer.m_startTicks);
 
                         uint elapsed; // How much of the timer dueTime has already elapsed
 
@@ -343,7 +333,7 @@ namespace System.Threading
                     TimerQueueTimer timer = m_timers;
                     while (timer != null)
                     {
-                        Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
+                        Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
 
                         uint elapsed = (uint)(nowTicks - timer.m_startTicks);
                         if (elapsed >= timer.m_dueTime)
@@ -413,7 +403,6 @@ namespace System.Threading
                 timerToFireOnThisThread.Fire();
         }
 
-        [SecuritySafeCritical]
         private static void QueueTimerCompletion(TimerQueueTimer timer)
         {
             WaitCallback callback = s_fireQueuedTimerCompletion;
@@ -523,7 +512,6 @@ namespace System.Threading
         volatile WaitHandle m_notifyWhenNoCallbacksRunning;
 
 
-        [SecurityCritical]
         internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, ref StackCrawlMark stackMark)
         {
             m_timerCallback = timerCallback;
@@ -673,13 +661,11 @@ namespace System.Threading
                 SignalNoCallbacksRunning();
         }
 
-        [SecuritySafeCritical]
         internal void SignalNoCallbacksRunning()
         {
             Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle);
         }
 
-        [SecuritySafeCritical]
         internal void CallCallback()
         {
             if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
@@ -708,10 +694,8 @@ namespace System.Threading
             }
         }
 
-        [SecurityCritical]
         private static ContextCallback s_callCallbackInContext;
 
-        [SecurityCritical]
         private static void CallCallbackInContext(object state)
         {
             TimerQueueTimer t = (TimerQueueTimer)state;
@@ -772,7 +756,6 @@ namespace System.Threading
     }
 
 
-    [HostProtection(Synchronization=true, ExternalThreading=true)]
     [System.Runtime.InteropServices.ComVisible(true)]
     public sealed class Timer : MarshalByRefObject, IDisposable
     {
@@ -780,7 +763,6 @@ namespace System.Threading
 
         private TimerHolder m_timer;
 
-        [SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public Timer(TimerCallback callback, 
                      Object        state,  
@@ -797,7 +779,6 @@ namespace System.Threading
             TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period,ref stackMark);
         }
 
-        [SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public Timer(TimerCallback callback, 
                      Object        state,  
@@ -821,7 +802,6 @@ namespace System.Threading
         }
 
         [CLSCompliant(false)]
-        [SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public Timer(TimerCallback callback, 
                      Object        state,  
@@ -832,7 +812,6 @@ namespace System.Threading
             TimerSetup(callback,state,dueTime,period,ref stackMark);
         }
 
-        [SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable                                        
         public Timer(TimerCallback callback, 
                      Object        state,  
@@ -852,7 +831,6 @@ namespace System.Threading
             TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period,ref stackMark);
         }
 
-        [SecuritySafeCritical]
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public Timer(TimerCallback callback)
         {
@@ -865,7 +843,6 @@ namespace System.Threading
             TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period, ref stackMark);
         }
 
-        [SecurityCritical]
         private void TimerSetup(TimerCallback callback,
                                 Object state, 
                                 UInt32 dueTime,
@@ -879,13 +856,11 @@ namespace System.Threading
             m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, ref stackMark));
         }
 
-        [SecurityCritical]
         internal static void Pause()
         {
             TimerQueue.Instance.Pause();
         }
 
-        [SecurityCritical]
         internal static void Resume()
         {
             TimerQueue.Instance.Resume();
index af687fb..3894b43 100644 (file)
@@ -129,7 +129,6 @@ namespace System.Threading
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [CLSCompliant(false)]
         [System.Runtime.Versioning.NonVersionable]
-        [SecuritySafeCritical] // to match 32-bit version
         public static ulong Read(ref ulong location)
         {
             // 
@@ -154,7 +153,6 @@ namespace System.Threading
 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [CLSCompliant(false)]
-        [SecuritySafeCritical] // contains unsafe code
         public static ulong Read(ref ulong location)
         {
             unsafe
@@ -222,7 +220,6 @@ namespace System.Threading
         }
 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [SecuritySafeCritical] //the intrinsic implementation of this method contains unverifiable code
         [System.Runtime.Versioning.NonVersionable]
         public static T Read<T>(ref T location) where T : class
         {
@@ -332,7 +329,6 @@ namespace System.Threading
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [CLSCompliant(false)]
         [System.Runtime.Versioning.NonVersionable]
-        [SecuritySafeCritical] // to match 32-bit version
         public static void Write(ref ulong location, ulong value)
         {
             // 
@@ -356,7 +352,6 @@ namespace System.Threading
 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
         [CLSCompliant(false)]
-        [SecuritySafeCritical] // contains unsafe code
         public static void Write(ref ulong location, ulong value)
         {
             //
@@ -427,7 +422,6 @@ namespace System.Threading
         }
 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-        [SecuritySafeCritical] //the intrinsic implementation of this method contains unverifiable code
         [System.Runtime.Versioning.NonVersionable]
         public static void Write<T>(ref T location, T value) where T : class
         {
index 15d39a0..7638c8b 100644 (file)
@@ -27,7 +27,7 @@ namespace System.Threading
     using System.Diagnostics.CodeAnalysis;
     using Win32Native = Microsoft.Win32.Win32Native;
 
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class WaitHandle : MarshalByRefObject, IDisposable {
         public const int WaitTimeout = 0x102;                    
 
@@ -37,12 +37,10 @@ namespace System.Threading
         private IntPtr waitHandle;  // !!! DO NOT MOVE THIS FIELD. (See defn of WAITHANDLEREF in object.h - has hardcoded access to this field.)
 #pragma warning restore 414
 
-        [System.Security.SecurityCritical] // auto-generated
         internal volatile SafeWaitHandle safeWaitHandle;
 
         internal bool hasThreadAffinity;
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private static IntPtr GetInvalidHandle()
         {
             return Win32Native.INVALID_HANDLE_VALUE;
@@ -66,7 +64,6 @@ namespace System.Threading
             Init();
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private void Init()
         {
             safeWaitHandle = null;
@@ -78,13 +75,7 @@ namespace System.Threading
         [Obsolete("Use the SafeWaitHandle property instead.")]
         public virtual IntPtr Handle 
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle();}
-        
-            [System.Security.SecurityCritical]  // auto-generated_required
-#if !FEATURE_CORECLR
-            [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#endif
             set
             {
                 if (value == InvalidHandle)
@@ -109,13 +100,8 @@ namespace System.Threading
             }
         }
 
-
         public SafeWaitHandle SafeWaitHandle 
         {
-            [System.Security.SecurityCritical]  // auto-generated_required
-#if !FEATURE_CORECLR
-            [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#endif
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
             get
             {
@@ -125,11 +111,7 @@ namespace System.Threading
                 }
                 return safeWaitHandle;
             }
-        
-            [System.Security.SecurityCritical]  // auto-generated_required
-#if !FEATURE_CORECLR
-            [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#endif
+
             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
             set
             {
@@ -164,7 +146,6 @@ namespace System.Threading
         // FileStream, which will then call Sethandle, which requires a link time
         // security check.).  While security has fixed that problem, we still
         // don't need to do a linktime check here.
-        [System.Security.SecurityCritical]  // auto-generated
         internal void SetHandleInternal(SafeWaitHandle handle)
         {
             safeWaitHandle = handle;
@@ -207,14 +188,12 @@ namespace System.Threading
             return WaitOne(timeout, false); 
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")]
         private bool WaitOne(long timeout, bool exitContext)
         {
             return InternalWaitOne(safeWaitHandle, timeout, hasThreadAffinity, exitContext);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal static bool InternalWaitOne(SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext)
         {
             if (waitableSafeHandle == null)
@@ -234,7 +213,6 @@ namespace System.Threading
             return (ret != WaitTimeout);
         }
         
-        [System.Security.SecurityCritical]
         internal bool WaitOneWithoutFAS()
         {
             // version of waitone without fast application switch (FAS) support
@@ -254,7 +232,6 @@ namespace System.Threading
             return (ret != WaitTimeout);
          }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext);
     
@@ -267,12 +244,10 @@ namespace System.Threading
         ** (if in a synchronized context) is exited before the wait and reacquired 
         ========================================================================*/
         
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)] 
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
         {
             if (waitHandles == null)
@@ -290,11 +265,7 @@ namespace System.Threading
                 // in CoreCLR, and ArgumentNullException in the desktop CLR.  This is ugly, but so is breaking
                 // user code.
                 //
-#if FEATURE_CORECLR
                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray"));
-#else
-                throw new ArgumentNullException(nameof(waitHandles), Environment.GetResourceString("Argument_EmptyWaithandleArray"));
-#endif
             }
             if (waitHandles.Length > MAX_WAITHANDLES)
             {
@@ -313,11 +284,6 @@ namespace System.Threading
                 if (waitHandle == null)
                     throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement"));
 
-#if FEATURE_REMOTING        
-                if (RemotingServices.IsTransparentProxy(waitHandle))
-                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy"));
-#endif
-
                 internalWaitHandles[i] = waitHandle;
             }
 #if _DEBUG
@@ -384,7 +350,6 @@ namespace System.Threading
         ** (if in a synchronized context) is exited before the wait and reacquired 
         ========================================================================*/
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
         public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
         {
@@ -413,11 +378,6 @@ namespace System.Threading
                 if (waitHandle == null)
                     throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement"));
 
-#if FEATURE_REMOTING        
-                if (RemotingServices.IsTransparentProxy(waitHandle))
-                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy"));
-#endif
-
                 internalWaitHandles[i] = waitHandle;
             }
 #if _DEBUG
@@ -487,7 +447,6 @@ namespace System.Threading
         ==
         ==================================================*/
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)] 
         private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout,
                                             bool hasThreadAffinity,  bool exitContext);
@@ -521,7 +480,6 @@ namespace System.Threading
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")]
         public static bool SignalAndWait(
                                         WaitHandle toSignal,
@@ -550,14 +508,6 @@ namespace System.Threading
             int ret = SignalAndWaitOne(toSignal.safeWaitHandle,toWaitOn.safeWaitHandle,millisecondsTimeout,
                                 toWaitOn.hasThreadAffinity,exitContext);
 
-#if !FEATURE_CORECLR
-            if(WAIT_FAILED != ret  && toSignal.hasThreadAffinity)
-            {
-                Thread.EndCriticalRegion();
-                Thread.EndThreadAffinity();
-            }
-#endif
-
             if(WAIT_ABANDONED == ret)
             {
                 ThrowAbandonedMutexException();
@@ -595,7 +545,6 @@ namespace System.Threading
             GC.SuppressFinalize(this);
         }
             
-        [System.Security.SecuritySafeCritical]  // auto-generated
         protected virtual void Dispose(bool explicitDisposing)
         {
             if (safeWaitHandle != null)
index 9c471e3..a534dec 100644 (file)
@@ -39,6 +39,7 @@ namespace System {
     using Collections.Generic;
     using System.Runtime.CompilerServices;
     using System.Runtime.Serialization;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Pure]
@@ -59,6 +60,18 @@ namespace System {
         internal static void ThrowArgumentOutOfRangeException() {
             throw new ArgumentOutOfRangeException();
         }
+
+        internal static void ThrowArgumentException_DestinationTooShort() {
+            throw new ArgumentException(Environment.GetResourceString("Argument_DestinationTooShort"));
+        }
+
+        internal static void ThrowNotSupportedException_CannotCallEqualsOnSpan() {
+            throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotCallEqualsOnSpan"));
+        }
+
+        internal static void ThrowNotSupportedException_CannotCallGetHashCodeOnSpan() {
+            throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotCallGetHashCodeOnSpan"));
+        }
 #endif
 
         internal static void ThrowArgumentOutOfRange_IndexException() {
@@ -94,8 +107,6 @@ namespace System {
             throw GetWrongValueTypeArgumentException(value, targetType);
         }
 
-
-#if FEATURE_CORECLR
         private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) {
             return new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicateWithKey", key));
         }
@@ -103,7 +114,6 @@ namespace System {
         internal static void ThrowAddingDuplicateWithKeyArgumentException(object key) {
             throw GetAddingDuplicateWithKeyArgumentException(key);
         }
-#endif
 
         internal static void ThrowKeyNotFoundException() {
             throw new System.Collections.Generic.KeyNotFoundException();
@@ -252,7 +262,7 @@ namespace System {
         // Second function in chain so as to not propergate the non-inlining to outside caller
         [MethodImpl(MethodImplOptions.NoInlining)]
         private static string GetArgumentNameInner(ExceptionArgument argument) {
-            Contract.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
+            Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
                 "The enum value is not defined, please check the ExceptionArgument Enum.");
 
             return argument.ToString();
@@ -271,7 +281,7 @@ namespace System {
         // Second function in chain so as to not propergate the non-inlining to outside caller
         [MethodImpl(MethodImplOptions.NoInlining)]
         private static string GetResourceStringInner(ExceptionResource resource) {
-            Contract.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
+            Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
                 "The enum value is not defined, please check the ExceptionResource Enum.");
 
             return Environment.GetResourceString(resource.ToString());
index 6dd35b8..a594da2 100644 (file)
@@ -28,7 +28,7 @@ namespace System {
     // details of this type should change, or new fields added, we need to remember to add
     // an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled.
     //
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     [Serializable] public struct TimeSpan : IComparable
         , IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
     {
@@ -406,26 +406,8 @@ namespace System {
         //        [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
         //        "TimeSpan_LegacyFormatMode"=dword:00000001
         //
-#if !FEATURE_CORECLR
-        [System.Security.SecurityCritical]
-        [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        private static extern bool LegacyFormatMode();
-#endif // !FEATURE_CORECLR
-        //
-        // In Silverlight v4, specifying the APP_EARLIER_THAN_SL4.0 quirks mode allows applications to
-        // run in v2 - v3 legacy behavior.
-        //
-#if !FEATURE_CORECLR
-        [System.Security.SecuritySafeCritical]
-#endif
         private static bool GetLegacyFormatMode() {
-#if !FEATURE_CORECLR
-            if (LegacyFormatMode()) // FCALL to check COMPlus_TimeSpan_LegacyFormatMode
-                return true;
-            return CompatibilitySwitches.IsNetFx40TimeSpanLegacyFormatMode;
-#else
             return false;
-#endif // !FEATURE_CORECLR
         }
 
         private static volatile bool _legacyConfigChecked;
index 602e86a..c0a369f 100644 (file)
@@ -26,10 +26,8 @@ namespace System {
     using System.Globalization;
 
     [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
+    [System.Runtime.InteropServices.ComVisible(true)]
     [Obsolete("System.TimeZone has been deprecated.  Please investigate the use of System.TimeZoneInfo instead.")]
-#endif
     public abstract class TimeZone {
         private static volatile TimeZone currentTimeZone = null;
 
index 85f28ca..72fc28f 100644 (file)
@@ -49,22 +49,18 @@ namespace System {
         NoThrowOnInvalidTime      = 2
     };
 
-
     [Serializable]
     [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
-    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
     sealed public class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
     {
         // ---- SECTION:  members supporting exposed properties -------------*
-        private String m_id;
-        private String m_displayName;
-        private String m_standardDisplayName;
-        private String m_daylightDisplayName;
-        private TimeSpan m_baseUtcOffset;
-        private Boolean m_supportsDaylightSavingTime;
-        private AdjustmentRule[] m_adjustmentRules;
+        private readonly String m_id;
+        private readonly String m_displayName;
+        private readonly String m_standardDisplayName;
+        private readonly String m_daylightDisplayName;
+        private readonly TimeSpan m_baseUtcOffset;
+        private readonly Boolean m_supportsDaylightSavingTime;
+        private readonly AdjustmentRule[] m_adjustmentRules;
 
         // ---- SECTION:  members for internal support ---------*
         private enum TimeZoneInfoResult {
@@ -115,6 +111,8 @@ namespace System {
         private const long c_ticksPerDay         = c_ticksPerHour * 24;
         private const long c_ticksPerDayRange    = c_ticksPerDay - c_ticksPerMillisecond;
 
+        private static readonly TimeZoneInfo s_utcTimeZone = CreateCustomTimeZone(c_utcId, TimeSpan.Zero, c_utcId, c_utcId);
+
         //
         // All cached data are encapsulated in a helper class to allow consistent view even when the data are refreshed using ClearCachedData()
         //
@@ -125,7 +123,6 @@ namespace System {
         class CachedData
         {
             private volatile TimeZoneInfo m_localTimeZone;
-            private volatile TimeZoneInfo m_utcTimeZone;
 
             private TimeZoneInfo CreateLocal()
             {
@@ -163,31 +160,6 @@ namespace System {
                 }
             }
 
-            private TimeZoneInfo CreateUtc()
-            {
-                lock (this)
-                {
-                    TimeZoneInfo timeZone = m_utcTimeZone;
-                    if (timeZone == null) {
-                        timeZone = CreateCustomTimeZone(c_utcId, TimeSpan.Zero, c_utcId, c_utcId);
-                        m_utcTimeZone = timeZone;
-                    }
-                    return timeZone;
-                }
-            }
-
-            public TimeZoneInfo Utc {
-                get {
-                    Contract.Ensures(Contract.Result<TimeZoneInfo>() != null);
-
-                    TimeZoneInfo timeZone = m_utcTimeZone;
-                    if (timeZone == null) {
-                        timeZone = CreateUtc();
-                    }
-                    return timeZone;
-                }
-            }     
-
             //
             // GetCorrespondingKind-
             //
@@ -215,7 +187,7 @@ namespace System {
                 // in this example.  Only when the user passes in TimeZoneInfo.Local or
                 // TimeZoneInfo.Utc to the ConvertTime(...) methods will this check succeed.
                 //
-                if ((object)timeZone == (object)m_utcTimeZone) {
+                if ((object)timeZone == (object)s_utcTimeZone) {
                     kind = DateTimeKind.Utc;
                 }
                 else if ((object)timeZone == (object)m_localTimeZone) {
@@ -233,7 +205,6 @@ namespace System {
             public bool m_allSystemTimeZonesRead;
 
 #if FEATURE_WIN32_REGISTRY
-            [System.Security.SecuritySafeCritical]
             private static TimeZoneInfo GetCurrentOneYearLocal() {
                 // load the data from the OS
                 TimeZoneInfo match;
@@ -326,7 +297,7 @@ namespace System {
 
         private AdjustmentRule[] GetFilledRules()
         {
-            Contract.Assert(m_adjustmentRules != null, "m_adjustmentRules expected to be not null");
+            Debug.Assert(m_adjustmentRules != null, "m_adjustmentRules expected to be not null");
             AdjustmentRule[] rules = new AdjustmentRule[m_adjustmentRules.Length];
 
             for (int i = 0; i < m_adjustmentRules.Length; i++)
@@ -427,7 +398,7 @@ namespace System {
             }
             else if (dateTime.Kind == DateTimeKind.Utc) {
                 CachedData cachedData = s_cachedData;
-                adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Utc, this, TimeZoneInfoOptions.None, cachedData);
+                adjustedTime = TimeZoneInfo.ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData);
             }
             else {
                 adjustedTime = dateTime;
@@ -525,7 +496,7 @@ namespace System {
                     //
                     // normal case of converting from Local to Utc and then getting the offset from the UTC DateTime
                     //
-                    DateTime adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, cachedData.Utc, flags);
+                    DateTime adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags);
                     return GetUtcOffsetFromUtc(adjustedTime, this);
                 }
 
@@ -592,7 +563,7 @@ namespace System {
             }
             else if (dateTime.Kind == DateTimeKind.Utc) {
                 CachedData cachedData = s_cachedData;
-                adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Utc, this, flags, cachedData);
+                adjustedTime = TimeZoneInfo.ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData);
             }
             else {
                 adjustedTime = dateTime;
@@ -759,7 +730,7 @@ namespace System {
                 // be reference equal to the new TimeZoneInfo.Utc
                 //
                 CachedData cachedData = s_cachedData;
-                return ConvertTime(dateTime, cachedData.Utc, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
+                return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
             }
             else
             {
@@ -809,7 +780,7 @@ namespace System {
             }
             CachedData cachedData = s_cachedData;
             if (dateTime.Kind == DateTimeKind.Utc) {
-                return ConvertTime(dateTime, cachedData.Utc, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
+                return ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
             }
             else {
                 return ConvertTime(dateTime, cachedData.Local, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
@@ -903,7 +874,7 @@ namespace System {
         //
         static public DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) {
             CachedData cachedData = s_cachedData;
-            return ConvertTime(dateTime, cachedData.Utc, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
+            return ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
         }
 
 
@@ -917,7 +888,7 @@ namespace System {
                 return dateTime;
             }
             CachedData cachedData = s_cachedData;
-            return ConvertTime(dateTime, cachedData.Local, cachedData.Utc, TimeZoneInfoOptions.None, cachedData);
+            return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
         }
 
 
@@ -926,12 +897,12 @@ namespace System {
                 return dateTime;
             }
             CachedData cachedData = s_cachedData;
-            return ConvertTime(dateTime, cachedData.Local, cachedData.Utc, flags, cachedData);
+            return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags, cachedData);
         }
 
         static public DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) {
             CachedData cachedData = s_cachedData;
-            return ConvertTime(dateTime, sourceTimeZone, cachedData.Utc, TimeZoneInfoOptions.None, cachedData);
+            return ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
         }
 
 
@@ -946,11 +917,7 @@ namespace System {
         }
 
         public override bool Equals(object obj) {
-            TimeZoneInfo tzi = obj as TimeZoneInfo;            
-            if (null == tzi) {
-                return false;
-            }            
-            return Equals(tzi);
+            return Equals(obj as TimeZoneInfo);
         }
 
         //    
@@ -973,7 +940,7 @@ namespace System {
         // GetHashCode -
         //
         public override int GetHashCode() {
-            return m_id.ToUpper(CultureInfo.InvariantCulture).GetHashCode();
+            return StringComparer.OrdinalIgnoreCase.GetHashCode(m_id);
         }
 
         //
@@ -989,7 +956,6 @@ namespace System {
         // <SecurityKernel Critical="True" Ring="0">
         // <Asserts Name="Imperative: System.Security.PermissionSet" />
         // </SecurityKernel>
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static public ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones() {
 
             CachedData cachedData = s_cachedData;
@@ -1010,7 +976,12 @@ namespace System {
                     }
 
                     // sort and copy the TimeZoneInfo's into a ReadOnlyCollection for the user
-                    list.Sort(new TimeZoneInfoComparer());
+                    list.Sort((x, y) =>
+                    {
+                        // sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel
+                        int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset);
+                        return comparison == 0 ? string.CompareOrdinal(x.DisplayName, y.DisplayName) : comparison;
+                    });
 
                     cachedData.m_readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list);
                 }          
@@ -1018,26 +989,19 @@ namespace System {
             return cachedData.m_readOnlySystemTimeZones;
         }
 
-        [SecuritySafeCritical]
         private static void PopulateAllSystemTimeZones(CachedData cachedData)
         {
 #if FEATURE_WIN32_REGISTRY
             PermissionSet permSet = new PermissionSet(PermissionState.None);
             permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList));
             permSet.Assert();
-            
-            using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(
-                c_timeZonesRegistryHive,
-#if FEATURE_MACL
-                RegistryKeyPermissionCheck.Default,
-                System.Security.AccessControl.RegistryRights.ReadKey
-#else
-                false
-#endif
-                )) {
 
-                if (reg != null) {
-                    foreach (string keyName in reg.GetSubKeyNames()) {
+            using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(c_timeZonesRegistryHive, false))
+            {
+                if (reg != null)
+                {
+                    foreach (string keyName in reg.GetSubKeyNames())
+                    {
                         TimeZoneInfo value;
                         Exception ex;
                         TryGetTimeZone(keyName, false, out value, out ex, cachedData);  // populate the cache
@@ -1155,7 +1119,7 @@ namespace System {
         static public TimeZoneInfo Utc {
             get {
                 Contract.Ensures(Contract.Result<TimeZoneInfo>() != null);
-                return s_cachedData.Utc;
+                return s_utcTimeZone;
             }
         }
 
@@ -1167,7 +1131,6 @@ namespace System {
         // private ctor
         //
 #if FEATURE_WIN32_REGISTRY
-        [System.Security.SecurityCritical]  // auto-generated
         private TimeZoneInfo(Win32Native.TimeZoneInformation zone, Boolean dstDisabled) {
             
             if (String.IsNullOrEmpty(zone.StandardName)) {
@@ -1299,16 +1262,13 @@ namespace System {
             Boolean adjustmentRulesSupportDst;
             ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst);
 
-            if (!disableDaylightSavingTime && adjustmentRules != null && adjustmentRules.Length > 0) {
-                m_adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone();
-            }
-
             m_id = id;
             m_baseUtcOffset = baseUtcOffset;
             m_displayName = displayName;
             m_standardDisplayName = standardDisplayName;
             m_daylightDisplayName = (disableDaylightSavingTime ? null : daylightDisplayName);
             m_supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime;
+            m_adjustmentRules = adjustmentRules;
         }
 
         // -------- SECTION: factory methods -----------------*
@@ -1349,7 +1309,7 @@ namespace System {
                 String daylightDisplayName,
                 AdjustmentRule [] adjustmentRules) {
 
-            return new TimeZoneInfo(
+            return CreateCustomTimeZone(
                            id,
                            baseUtcOffset,
                            displayName,
@@ -1378,7 +1338,11 @@ namespace System {
                 AdjustmentRule [] adjustmentRules,
                 Boolean disableDaylightSavingTime) {
 
-           return new TimeZoneInfo(
+            if (!disableDaylightSavingTime && adjustmentRules?.Length > 0) {
+                adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone();
+            }
+
+            return new TimeZoneInfo(
                            id,
                            baseUtcOffset,
                            displayName,
@@ -1410,7 +1374,6 @@ namespace System {
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info == null) {
                 throw new ArgumentNullException(nameof(info));
@@ -1591,7 +1554,6 @@ namespace System {
         //
         // This check is only meant to be used for "Local".
         //
-        [System.Security.SecurityCritical]  // auto-generated
         static private Boolean CheckDaylightSavingTimeNotSupported(Win32Native.TimeZoneInformation timeZone) {
             return (   timeZone.DaylightDate.Year         == timeZone.StandardDate.Year
                     && timeZone.DaylightDate.Month        == timeZone.StandardDate.Month
@@ -1649,7 +1611,6 @@ namespace System {
         //
         // Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to an AdjustmentRule
         //
-        [System.Security.SecurityCritical]  // auto-generated
         static private AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset) {
             AdjustmentRule rule;
             bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
@@ -1707,7 +1668,6 @@ namespace System {
         // Helper function that searches the registry for a time zone entry
         // that matches the TimeZoneInformation struct
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static private String FindIdFromTimeZoneInformation(Win32Native.TimeZoneInformation timeZone, out Boolean dstDisabled) {
             dstDisabled = false;
 
@@ -1716,21 +1676,16 @@ namespace System {
                 permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList));
                 permSet.Assert();
 
-                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
-                                  c_timeZonesRegistryHive,
-#if FEATURE_MACL
-                                  RegistryKeyPermissionCheck.Default,
-                                  System.Security.AccessControl.RegistryRights.ReadKey
-#else
-                                  false
-#endif
-                                  )) {
-
-                    if (key == null) {
+                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(c_timeZonesRegistryHive, false))
+                {
+                    if (key == null)
+                    {
                         return null;
                     }
-                    foreach (string keyName in key.GetSubKeyNames()) {
-                        if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled)) {
+                    foreach (string keyName in key.GetSubKeyNames())
+                    {
+                        if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
+                        {
                             return keyName;
                         }
                     }
@@ -2149,7 +2104,6 @@ namespace System {
         // assumes cachedData lock is taken
         //
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static private TimeZoneInfo GetLocalTimeZone(CachedData cachedData) {
 
 
@@ -2317,7 +2271,6 @@ namespace System {
         /// 3. Look for the data in GetTimeZoneDirectory()/localtime.
         /// 4. Use UTC if all else fails.
         /// </summary>
-        [SecurityCritical]
         private static bool TryGetLocalTzFile(out byte[] rawData, out string id)
         {
             rawData = null;
@@ -2397,7 +2350,6 @@ namespace System {
         /// Finds the time zone id by using 'readlink' on the path to see if tzFilePath is
         /// a symlink to a file 
         /// </summary>
-        [SecuritySafeCritical]
         private static string FindTimeZoneIdUsingReadLink(string tzFilePath)
         {
             string id = null;
@@ -2513,7 +2465,6 @@ namespace System {
         //
         // The TryGetLocalTzFile() call returns a Byte[] containing the compiled tzfile.
         // 
-        [System.Security.SecurityCritical]
         static private TimeZoneInfo GetLocalTimeZoneFromTzFile()
         {
             byte[] rawData;
@@ -2576,7 +2527,6 @@ namespace System {
         // try/catch logic for handling the TimeZoneInfo private constructor that takes
         // a Win32Native.TimeZoneInformation structure.
         //
-        [System.Security.SecurityCritical]  // auto-generated
         static private TimeZoneInfo GetLocalTimeZoneFromWin32Data(Win32Native.TimeZoneInformation timeZoneInformation, Boolean dstDisabled) {
             // first try to create the TimeZoneInfo with the original 'dstDisabled' flag
             try {
@@ -2643,7 +2593,7 @@ namespace System {
 #if FEATURE_WIN32_REGISTRY
                 throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidRegistryData", id), e);
 #elif PLATFORM_UNIX
-                Contract.Assert(e is InvalidTimeZoneException,
+                Debug.Assert(e is InvalidTimeZoneException,
                     "TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException");
                 throw e;
 #endif
@@ -2782,7 +2732,6 @@ namespace System {
         // * when the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
         // * when the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
         //
-        [System.Security.SecurityCritical]  // auto-generated
         static private bool TransitionTimeFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, out TransitionTime transitionTime, bool readStartDate) {
             //
             // SYSTEMTIME - 
@@ -2988,33 +2937,27 @@ namespace System {
         //
         // This method expects that its caller has already Asserted RegistryPermission.Read
         //
-        [System.Security.SecurityCritical]  // auto-generated
         static private bool TryCreateAdjustmentRules(string id, Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset) {
             e = null;
 
             try {
                 using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(
-                                   String.Format(CultureInfo.InvariantCulture, "{0}\\{1}\\Dynamic DST",
-                                       c_timeZonesRegistryHive, id),
-#if FEATURE_MACL
-                                   RegistryKeyPermissionCheck.Default,
-                                   System.Security.AccessControl.RegistryRights.ReadKey
-#else
-                                   false
-#endif
-                                   )) {
+                    c_timeZonesRegistryHive + "\\" + id + "\\Dynamic DST",
+                    false)) {
                     if (dynamicKey == null) {
                         AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(
                                               defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
 
-                        if (rule == null) {
+                        if (rule == null)
+                        {
                             rules = null;
                         }
-                        else {
+                        else
+                        {
                             rules = new AdjustmentRule[1];
                             rules[0] = rule;
                         }
-                        
+
                         return true;
                     }
 
@@ -3029,7 +2972,8 @@ namespace System {
                     Int32 first = (Int32)dynamicKey.GetValue(c_firstEntryValue, -1, RegistryValueOptions.None);
                     Int32 last = (Int32)dynamicKey.GetValue(c_lastEntryValue, -1, RegistryValueOptions.None);
 
-                    if (first == -1 || last == -1 || first > last) {
+                    if (first == -1 || last == -1 || first > last)
+                    {
                         rules = null;
                         return false;
                     }
@@ -3037,20 +2981,24 @@ namespace System {
                     // read the first year entry
                     Win32Native.RegistryTimeZoneInformation dtzi;
                     Byte[] regValue = dynamicKey.GetValue(first.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as Byte[];
-                    if (regValue == null || regValue.Length != c_regByteLength) {
+                    if (regValue == null || regValue.Length != c_regByteLength)
+                    {
                         rules = null;
                         return false;
                     }
                     dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
 
-                    if (first == last) {
+                    if (first == last)
+                    {
                         // there is just 1 dynamic rule for this time zone.
-                        AdjustmentRule rule =  CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
+                        AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
 
-                        if (rule == null) {
+                        if (rule == null)
+                        {
                             rules = null;
                         }
-                        else {
+                        else
+                        {
                             rules = new AdjustmentRule[1];
                             rules[0] = rule;
                         }
@@ -3060,20 +3008,23 @@ namespace System {
 
                     List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
 
-                     // there are more than 1 dynamic rules for this time zone.
+                    // there are more than 1 dynamic rules for this time zone.
                     AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation(
                                               dtzi,
                                               DateTime.MinValue.Date,        // MinValue
                                               new DateTime(first, 12, 31),   // December 31, <FirstYear>
-                                              defaultBaseUtcOffset); 
-                    if (firstRule != null) {
+                                              defaultBaseUtcOffset);
+                    if (firstRule != null)
+                    {
                         rulesList.Add(firstRule);
                     }
 
                     // read the middle year entries
-                    for (Int32 i = first + 1; i < last; i++) {
+                    for (Int32 i = first + 1; i < last; i++)
+                    {
                         regValue = dynamicKey.GetValue(i.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as Byte[];
-                        if (regValue == null || regValue.Length != c_regByteLength) {
+                        if (regValue == null || regValue.Length != c_regByteLength)
+                        {
                             rules = null;
                             return false;
                         }
@@ -3083,14 +3034,16 @@ namespace System {
                                                   new DateTime(i, 1, 1),    // January  01, <Year>
                                                   new DateTime(i, 12, 31),  // December 31, <Year>
                                                   defaultBaseUtcOffset);
-                        if (middleRule != null) {
+                        if (middleRule != null)
+                        {
                             rulesList.Add(middleRule);
                         }
                     }
                     // read the last year entry
                     regValue = dynamicKey.GetValue(last.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as Byte[];
                     dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
-                    if (regValue == null || regValue.Length != c_regByteLength) {
+                    if (regValue == null || regValue.Length != c_regByteLength)
+                    {
                         rules = null;
                         return false;
                     }
@@ -3099,13 +3052,15 @@ namespace System {
                                               new DateTime(last, 1, 1),    // January  01, <LastYear>
                                               DateTime.MaxValue.Date,      // MaxValue
                                               defaultBaseUtcOffset);
-                    if (lastRule != null) {
+                    if (lastRule != null)
+                    {
                         rulesList.Add(lastRule);
                     }
 
                     // convert the ArrayList to an AdjustmentRule array
                     rules = rulesList.ToArray();
-                    if (rules != null && rules.Length == 0) {
+                    if (rules != null && rules.Length == 0)
+                    {
                         rules = null;
                     }
                 } // end of: using (RegistryKey dynamicKey...
@@ -3135,7 +3090,6 @@ namespace System {
         // Helper function that compares the StandardBias and StandardDate portion a
         // TimeZoneInformation struct to a time zone registry entry
         //
-        [System.Security.SecurityCritical]  // auto-generated
         static private Boolean TryCompareStandardDate(Win32Native.TimeZoneInformation timeZone, Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo) {
             return timeZone.Bias                         == registryTimeZoneInfo.Bias
                    && timeZone.StandardBias              == registryTimeZoneInfo.StandardBias
@@ -3154,9 +3108,8 @@ namespace System {
         //
         // Helper function that compares a TimeZoneInformation struct to a time zone registry entry
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
-        static private Boolean TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out Boolean dstDisabled) {
-
+        static private Boolean TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out Boolean dstDisabled)
+        {
             dstDisabled = false;
             try {
                 PermissionSet permSet = new PermissionSet(PermissionState.None);
@@ -3164,15 +3117,9 @@ namespace System {
                 permSet.Assert();
 
                 using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
-                                  String.Format(CultureInfo.InvariantCulture, "{0}\\{1}",
-                                      c_timeZonesRegistryHive, id),
-#if FEATURE_MACL
-                                  RegistryKeyPermissionCheck.Default,
-                                  System.Security.AccessControl.RegistryRights.ReadKey
-#else
-                                  false
-#endif
-                                  )) {
+                    c_timeZonesRegistryHive + "\\" + id,
+                    false))
+                {
 
                     if (key == null) {
                         return false;
@@ -3189,7 +3136,8 @@ namespace System {
                     //
                     Boolean result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
 
-                    if (!result) {
+                    if (!result)
+                    {
                         return false;
                     }
 
@@ -3198,14 +3146,14 @@ namespace System {
                              // since Daylight Saving Time is not "disabled", do a straight comparision between
                              // the Win32 API data and the registry data ...
                              //
-                             ||(   timeZone.DaylightBias              == registryTimeZoneInfo.DaylightBias
-                                && timeZone.DaylightDate.Year         == registryTimeZoneInfo.DaylightDate.Year
-                                && timeZone.DaylightDate.Month        == registryTimeZoneInfo.DaylightDate.Month
-                                && timeZone.DaylightDate.DayOfWeek    == registryTimeZoneInfo.DaylightDate.DayOfWeek
-                                && timeZone.DaylightDate.Day          == registryTimeZoneInfo.DaylightDate.Day
-                                && timeZone.DaylightDate.Hour         == registryTimeZoneInfo.DaylightDate.Hour
-                                && timeZone.DaylightDate.Minute       == registryTimeZoneInfo.DaylightDate.Minute
-                                && timeZone.DaylightDate.Second       == registryTimeZoneInfo.DaylightDate.Second
+                             || (timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias
+                                && timeZone.DaylightDate.Year == registryTimeZoneInfo.DaylightDate.Year
+                                && timeZone.DaylightDate.Month == registryTimeZoneInfo.DaylightDate.Month
+                                && timeZone.DaylightDate.DayOfWeek == registryTimeZoneInfo.DaylightDate.DayOfWeek
+                                && timeZone.DaylightDate.Day == registryTimeZoneInfo.DaylightDate.Day
+                                && timeZone.DaylightDate.Hour == registryTimeZoneInfo.DaylightDate.Hour
+                                && timeZone.DaylightDate.Minute == registryTimeZoneInfo.DaylightDate.Minute
+                                && timeZone.DaylightDate.Second == registryTimeZoneInfo.DaylightDate.Second
                                 && timeZone.DaylightDate.Milliseconds == registryTimeZoneInfo.DaylightDate.Milliseconds);
 
                     // Finally compare the "StandardName" string value...
@@ -3213,11 +3161,12 @@ namespace System {
                     // we do not compare "DaylightName" as this TimeZoneInformation field may contain
                     // either "StandardName" or "DaylightName" depending on the time of year and current machine settings
                     //
-                    if (result) {
+                    if (result)
+                    {
                         String registryStandardName = key.GetValue(c_standardValue, String.Empty, RegistryValueOptions.None) as String;
                         result = String.Compare(registryStandardName, timeZone.StandardName, StringComparison.Ordinal) == 0;
                     }
-                    return result;  
+                    return result;
                 }  
             }
             finally {
@@ -3241,10 +3190,6 @@ namespace System {
         // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.GetFileMUIPath(System.Int32,System.String,System.Text.StringBuilder,System.Int32&,System.Text.StringBuilder,System.Int32&,System.Int64&):System.Boolean" />
         // <ReferencesCritical Name="Method: TryGetLocalizedNameByNativeResource(String, Int32):String" Ring="1" />
         // </SecurityKernel>
-        [System.Security.SecuritySafeCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [FileIOPermissionAttribute(SecurityAction.Assert, AllLocalFiles = FileIOPermissionAccess.PathDiscovery)]
-#endif
         static private string TryGetLocalizedNameByMuiNativeResource(string resource) {
             if (String.IsNullOrEmpty(resource)) {
                 return String.Empty;
@@ -3314,7 +3259,6 @@ namespace System {
         // "resource.dll" is a language-specific resource DLL.
         // If the localized resource DLL exists, LoadString(resource) is returned.
         //
-        [SecurityCritical]
         static private string TryGetLocalizedNameByNativeResource(string filePath, int resource) {
             using (SafeLibraryHandle handle = 
                        UnsafeNativeMethods.LoadLibraryEx(filePath, IntPtr.Zero, Win32Native.LOAD_LIBRARY_AS_DATAFILE)) {
@@ -3345,9 +3289,6 @@ namespace System {
         //
         // This method expects that its caller has already Asserted RegistryPermission.Read
         //
-#if FEATURE_CORECLR
-        [System.Security.SecurityCritical] // auto-generated
-#endif
         static private Boolean TryGetLocalizedNamesByRegistryKey(RegistryKey key, out String displayName, out String standardName, out String daylightName) {
             displayName  = String.Empty;
             standardName = String.Empty;
@@ -3424,7 +3365,6 @@ namespace System {
         // * TZI,         REG_BINARY REG_TZI_FORMAT
         //                       See Win32Native.RegistryTimeZoneInformation
         //
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static private TimeZoneInfoResult TryGetTimeZoneByRegistryKey(string id, out TimeZoneInfo value, out Exception e) {
             e = null;
 
@@ -3434,15 +3374,8 @@ namespace System {
                 permSet.Assert();
 
                 using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
-                                  String.Format(CultureInfo.InvariantCulture, "{0}\\{1}",
-                                      c_timeZonesRegistryHive, id),
-#if FEATURE_MACL
-                                  RegistryKeyPermissionCheck.Default,
-                                  System.Security.AccessControl.RegistryRights.ReadKey
-#else
-                                  false
-#endif
-                                  )) {
+                    c_timeZonesRegistryHive + "\\" + id,
+                    false)) {
 
                     if (key == null) {
                         value = null;
@@ -4241,7 +4174,6 @@ namespace System {
 
         // Converts an array of bytes into an int - always using standard byte order (Big Endian)
         // per TZif file standard
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static private unsafe int TZif_ToInt32 (byte[]value, int startIndex) {
             fixed( byte * pbyte = &value[startIndex]) {
                 return (*pbyte << 24) | (*(pbyte + 1) << 16)  | (*(pbyte + 2) << 8) | (*(pbyte + 3));                        
@@ -4250,7 +4182,6 @@ namespace System {
 
         // Converts an array of bytes into a long - always using standard byte order (Big Endian)
         // per TZif file standard
-        [System.Security.SecuritySafeCritical]  // auto-generated
         static private unsafe long TZif_ToInt64(byte[] value, int startIndex)
         {
             fixed (byte* pbyte = &value[startIndex])
@@ -4491,20 +4422,17 @@ namespace System {
 ============================================================*/
         [Serializable]
         [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
-        [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
         sealed public class AdjustmentRule : IEquatable<AdjustmentRule>, ISerializable, IDeserializationCallback
             {
 
             // ---- SECTION:  members supporting exposed properties -------------*
-            private DateTime m_dateStart;
-            private DateTime m_dateEnd;
-            private TimeSpan m_daylightDelta;
-            private TransitionTime m_daylightTransitionStart;
-            private TransitionTime m_daylightTransitionEnd;
-            private TimeSpan m_baseUtcOffsetDelta;   // delta from the default Utc offset (utcOffset = defaultUtcOffset + m_baseUtcOffsetDelta)
-            private bool m_noDaylightTransitions;
+            private readonly DateTime m_dateStart;
+            private readonly DateTime m_dateEnd;
+            private readonly TimeSpan m_daylightDelta;
+            private readonly TransitionTime m_daylightTransitionStart;
+            private readonly TransitionTime m_daylightTransitionEnd;
+            private readonly TimeSpan m_baseUtcOffsetDelta;   // delta from the default Utc offset (utcOffset = defaultUtcOffset + m_baseUtcOffsetDelta)
+            private readonly bool m_noDaylightTransitions;
 
             // ---- SECTION: public properties --------------*
             public DateTime  DateStart {
@@ -4571,16 +4499,13 @@ namespace System {
 
             // IEquatable<AdjustmentRule>
             public bool Equals(AdjustmentRule other) {
-                bool equals = (other != null
-                     && this.m_dateStart == other.m_dateStart
-                     && this.m_dateEnd  == other.m_dateEnd
-                     && this.m_daylightDelta == other.m_daylightDelta
-                     && this.m_baseUtcOffsetDelta == other.m_baseUtcOffsetDelta);
-
-                equals = equals && this.m_daylightTransitionEnd.Equals(other.m_daylightTransitionEnd)
-                         && this.m_daylightTransitionStart.Equals(other.m_daylightTransitionStart);
-
-                return equals;
+                return other != null
+                    && m_dateStart == other.m_dateStart
+                    && m_dateEnd == other.m_dateEnd
+                    && m_daylightDelta == other.m_daylightDelta
+                    && m_baseUtcOffsetDelta == other.m_baseUtcOffsetDelta
+                    && m_daylightTransitionEnd.Equals(other.m_daylightTransitionEnd)
+                    && m_daylightTransitionStart.Equals(other.m_daylightTransitionStart);
             }
 
 
@@ -4592,33 +4517,29 @@ namespace System {
 
             // -------- SECTION: constructors -----------------*
 
-            private AdjustmentRule() { }
-
-
-            // -------- SECTION: factory methods -----------------*
-
-            static internal AdjustmentRule CreateAdjustmentRule(
-                             DateTime dateStart,
-                             DateTime dateEnd,
-                             TimeSpan daylightDelta,
-                             TransitionTime daylightTransitionStart,
-                             TransitionTime daylightTransitionEnd,
-                             bool noDaylightTransitions) {
+            private AdjustmentRule(
+                DateTime dateStart,
+                DateTime dateEnd,
+                TimeSpan daylightDelta,
+                TransitionTime daylightTransitionStart,
+                TransitionTime daylightTransitionEnd,
+                TimeSpan baseUtcOffsetDelta,
+                bool noDaylightTransitions)
+            {
                 ValidateAdjustmentRule(dateStart, dateEnd, daylightDelta,
                        daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions);
 
-                AdjustmentRule rule = new AdjustmentRule();
+                m_dateStart = dateStart;
+                m_dateEnd = dateEnd;
+                m_daylightDelta = daylightDelta;
+                m_daylightTransitionStart = daylightTransitionStart;
+                m_daylightTransitionEnd = daylightTransitionEnd;
+                m_baseUtcOffsetDelta = baseUtcOffsetDelta;
+                m_noDaylightTransitions = noDaylightTransitions;
+            }
 
-                rule.m_dateStart = dateStart;
-                rule.m_dateEnd   = dateEnd;
-                rule.m_daylightDelta = daylightDelta;
-                rule.m_daylightTransitionStart = daylightTransitionStart;
-                rule.m_daylightTransitionEnd = daylightTransitionEnd;
-                rule.m_baseUtcOffsetDelta = TimeSpan.Zero;
-                rule.m_noDaylightTransitions = noDaylightTransitions;
 
-                return rule;
-            }
+            // -------- SECTION: factory methods -----------------*
 
             static public AdjustmentRule CreateAdjustmentRule(
                              DateTime dateStart,
@@ -4627,8 +4548,14 @@ namespace System {
                              TransitionTime daylightTransitionStart,
                              TransitionTime daylightTransitionEnd)
             {
-                return CreateAdjustmentRule(dateStart, dateEnd, daylightDelta,
-                    daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions: false);
+                return new AdjustmentRule(
+                    dateStart,
+                    dateEnd,
+                    daylightDelta,
+                    daylightTransitionStart,
+                    daylightTransitionEnd,
+                    baseUtcOffsetDelta: TimeSpan.Zero,
+                    noDaylightTransitions: false);
             }
 
             static internal AdjustmentRule CreateAdjustmentRule(
@@ -4638,12 +4565,16 @@ namespace System {
                              TransitionTime daylightTransitionStart,
                              TransitionTime daylightTransitionEnd,
                              TimeSpan baseUtcOffsetDelta,
-                             bool noDaylightTransitions) {
-                AdjustmentRule rule = CreateAdjustmentRule(dateStart, dateEnd, daylightDelta,
-                    daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions);
-
-                rule.m_baseUtcOffsetDelta = baseUtcOffsetDelta;
-                return rule;
+                             bool noDaylightTransitions)
+            {
+                return new AdjustmentRule(
+                    dateStart,
+                    dateEnd,
+                    daylightDelta,
+                    daylightTransitionStart,
+                    daylightTransitionEnd,
+                    baseUtcOffsetDelta,
+                    noDaylightTransitions);
             }
 
             // ----- SECTION: internal utility methods ----------------*
@@ -4746,7 +4677,6 @@ namespace System {
                 }
             }
 
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
                 if (info == null) {
                     throw new ArgumentNullException(nameof(info));
@@ -4801,18 +4731,15 @@ namespace System {
 ============================================================*/
         [Serializable]
         [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
-        [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
         public struct TransitionTime : IEquatable<TransitionTime>, ISerializable, IDeserializationCallback
         {
             // ---- SECTION:  members supporting exposed properties -------------*
-            private DateTime m_timeOfDay;
-            private byte m_month;
-            private byte m_week;
-            private byte m_day;
-            private DayOfWeek m_dayOfWeek;
-            private Boolean m_isFixedDateRule;
+            private readonly DateTime m_timeOfDay;
+            private readonly byte m_month;
+            private readonly byte m_week;
+            private readonly byte m_day;
+            private readonly DayOfWeek m_dayOfWeek;
+            private readonly Boolean m_isFixedDateRule;
 
 
             // ---- SECTION: public properties --------------*
@@ -4896,16 +4823,24 @@ namespace System {
 
 
             // -------- SECTION: constructors -----------------*
-/*
-            private TransitionTime() {           
-                m_timeOfDay = new DateTime();
-                m_month = 0;
-                m_week  = 0;
-                m_day   = 0;
-                m_dayOfWeek = DayOfWeek.Sunday;
-                m_isFixedDateRule = false;
+
+            private TransitionTime(
+                DateTime timeOfDay,
+                Int32 month,
+                Int32 week,
+                Int32 day,
+                DayOfWeek dayOfWeek,
+                Boolean isFixedDateRule)
+            {
+                ValidateTransitionTime(timeOfDay, month, week, day, dayOfWeek);
+
+                m_timeOfDay = timeOfDay;
+                m_month = (byte)month;
+                m_week = (byte)week;
+                m_day = (byte)day;
+                m_dayOfWeek = dayOfWeek;
+                m_isFixedDateRule = isFixedDateRule;
             }
-*/
 
 
             // -------- SECTION: factory methods -----------------*
@@ -4916,7 +4851,7 @@ namespace System {
                     Int32 month,
                     Int32 day) {
 
-                return CreateTransitionTime(timeOfDay, month, 1, day, DayOfWeek.Sunday, true);
+                return new TransitionTime(timeOfDay, month, 1, day, DayOfWeek.Sunday, isFixedDateRule: true);
             }
 
 
@@ -4926,29 +4861,7 @@ namespace System {
                     Int32 week,
                     DayOfWeek dayOfWeek) {
 
-                return CreateTransitionTime(timeOfDay, month, week, 1, dayOfWeek, false);
-            }
-
-
-            static private TransitionTime CreateTransitionTime(
-                    DateTime timeOfDay,
-                    Int32 month,
-                    Int32 week,
-                    Int32 day,
-                    DayOfWeek dayOfWeek,
-                    Boolean isFixedDateRule) {
-
-                ValidateTransitionTime(timeOfDay, month, week, day, dayOfWeek);
-                
-                TransitionTime t = new TransitionTime();
-                t.m_isFixedDateRule = isFixedDateRule;
-                t.m_timeOfDay = timeOfDay;
-                t.m_dayOfWeek = dayOfWeek;
-                t.m_day = (byte)day;
-                t.m_week = (byte)week;
-                t.m_month = (byte)month;
-
-                return t;
+                return new TransitionTime(timeOfDay, month, week, 1, dayOfWeek, isFixedDateRule: false);
             }
 
 
@@ -5010,7 +4923,6 @@ namespace System {
             }
 
 
-            [System.Security.SecurityCritical]  // auto-generated_required
             void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
                 if (info == null) {
                     throw new ArgumentNullException(nameof(info));
@@ -5162,7 +5074,7 @@ namespace System {
                 AdjustmentRule[] rules = s.GetNextAdjustmentRuleArrayValue(false);
 
                 try { 
-                    return TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardName, daylightName, rules);
+                    return new TimeZoneInfo(id, baseUtcOffset, displayName, standardName, daylightName, rules, disableDaylightSavingTime: false);
                 }
                 catch (ArgumentException ex) {
                     throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), ex);
@@ -5690,14 +5602,6 @@ namespace System {
             }
         }
 
-        private class TimeZoneInfoComparer : System.Collections.Generic.IComparer<TimeZoneInfo> {
-            int System.Collections.Generic.IComparer<TimeZoneInfo>.Compare(TimeZoneInfo x, TimeZoneInfo y)  {
-                // sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel
-                int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset);
-                return comparison == 0 ? String.Compare(x.DisplayName, y.DisplayName, StringComparison.Ordinal) : comparison;
-            }
-        }
-
 #if PLATFORM_UNIX
         private struct TZifType
         {
index 5f8b919..cabcc15 100644 (file)
@@ -7,9 +7,6 @@ namespace System {
    using  System.Runtime.CompilerServices;
 
    [Serializable]
-#if !FEATURE_CORECLR
-   [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
    [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
    public class TimeZoneNotFoundException : Exception {
        public TimeZoneNotFoundException(String message)
index 6d41a8b..037b2ce 100644 (file)
@@ -5,6 +5,7 @@ using System;
 using System.Text;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 
 //
@@ -923,7 +924,7 @@ namespace System {
                 case 7:
                 return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
             }
-            Contract.Assert(false, "Missed all cases for computing Tuple hash code");
+            Debug.Assert(false, "Missed all cases for computing Tuple hash code");
             return -1;
         }
 
index 6583631..2d30c4c 100644 (file)
@@ -9,8 +9,8 @@
 //
 // ======================================================================================
 
-namespace System {
-
+namespace System
+{
     using System;
     using System.Reflection;
     using System.Threading;
@@ -154,7 +154,6 @@ namespace System {
         //   param progID:     the progID of the class to retrieve
         //   returns:          the class object associated to the progID
         ////
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Type GetTypeFromProgID(String progID)
         {
                 return RuntimeType.GetTypeFromProgIDImpl(progID, null, false);
@@ -169,19 +168,16 @@ namespace System {
         //   param progID:     the progID of the class to retrieve
         //   returns:          the class object associated to the progID
         ////
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Type GetTypeFromProgID(String progID, bool throwOnError)
         {
                 return RuntimeType.GetTypeFromProgIDImpl(progID, null, throwOnError);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Type GetTypeFromProgID(String progID, String server)
         {
                 return RuntimeType.GetTypeFromProgIDImpl(progID, server, false);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public static Type GetTypeFromProgID(String progID, String server, bool throwOnError)
         {
                 return RuntimeType.GetTypeFromProgIDImpl(progID, server, throwOnError);
@@ -194,25 +190,21 @@ namespace System {
         //   param CLSID:      the CLSID of the class to retrieve
         //   returns:          the class object associated to the CLSID
         ////
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Type GetTypeFromCLSID(Guid clsid)
         {
                 return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Type GetTypeFromCLSID(Guid clsid, bool throwOnError)
         {
                 return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, throwOnError);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Type GetTypeFromCLSID(Guid clsid, String server)
         {
                 return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, false);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public static Type GetTypeFromCLSID(Guid clsid, String server, bool throwOnError)
         {
                 return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, throwOnError);
@@ -338,12 +330,10 @@ namespace System {
         }
 
         // Given a class handle, this will return the class for that handle.
-        [System.Security.SecurityCritical]
         [MethodImpl(MethodImplOptions.InternalCall)]
         internal static extern RuntimeType GetTypeFromHandleUnsafe(IntPtr handle);
 
         [Pure]
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImpl(MethodImplOptions.InternalCall)]
         public static extern Type GetTypeFromHandle(RuntimeTypeHandle handle);
 
@@ -716,8 +706,7 @@ namespace System {
         {
             return GetProperties(Type.DefaultLookup);
         }
-#if    !FEATURE_CORECLR
-#endif 
+
         // GetNestedTypes()
         // This set of method will return any nested types that are found inside
         //  of the type.
@@ -728,9 +717,6 @@ namespace System {
 
         abstract public Type[] GetNestedTypes(BindingFlags bindingAttr);
 
-#if    !FEATURE_CORECLR
-        // GetNestedType()
-#endif
         public Type GetNestedType(String name)
         {
             return GetNestedType(name,Type.DefaultLookup);
@@ -1050,7 +1036,6 @@ namespace System {
 
         public bool IsInterface {
             [Pure]
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get
             {
                 RuntimeType rt = this as RuntimeType;
@@ -1301,21 +1286,15 @@ namespace System {
 
     
         // Protected routine to determine if this class is contextful
-        protected virtual bool IsContextfulImpl(){
-#if FEATURE_REMOTING
-            return typeof(ContextBoundObject).IsAssignableFrom(this);
-#else
+        protected virtual bool IsContextfulImpl()
+        {
             return false;
-#endif
         }
 
         // Protected routine to determine if this class is marshaled by ref
-        protected virtual bool IsMarshalByRefImpl(){
-#if FEATURE_REMOTING
-            return typeof(MarshalByRefObject).IsAssignableFrom(this);
-#else
+        protected virtual bool IsMarshalByRefImpl()
+        {
             return false;
-#endif
         }
 
         internal virtual bool HasProxyAttributeImpl()
@@ -1777,12 +1756,10 @@ namespace System {
             return (Object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType));
         }
 
-        [System.Security.SecuritySafeCritical]
         [Pure]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern bool operator ==(Type left, Type right);
 
-        [System.Security.SecuritySafeCritical]
         [Pure]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public static extern bool operator !=(Type left, Type right);
@@ -1813,30 +1790,6 @@ namespace System {
             return base.GetType();
         }
 
-#if !FEATURE_CORECLR
-        void _Type.GetTypeInfoCount(out uint pcTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Type.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
-        {
-            throw new NotImplementedException();
-        }
-
-        void _Type.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-        {
-            throw new NotImplementedException();
-        }
-
-        // If you implement this method, make sure to include _Type.Invoke in VM\DangerousAPIs.h and 
-        // include _Type in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
-        void _Type.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-        {
-            throw new NotImplementedException();
-        }
-#endif
-
         // private convenience data
         private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
         internal const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
index 62d189d..bcc1c3e 100644 (file)
@@ -56,7 +56,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             base.GetObjectData(info, context);
             info.AddValue("TypeName",TypeName,typeof(String));
index a1eae15..d73a97f 100644 (file)
@@ -44,14 +44,12 @@ namespace System {
     
         public override String Message
         {
-            [System.Security.SecuritySafeCritical]  // auto-generated
             get {
                 SetMessageField();
                 return _message;
             }
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         private void SetMessageField()
         {
             if (_message == null) {
@@ -83,7 +81,6 @@ namespace System {
         }
     
         // This is called from inside the EE. 
-        [System.Security.SecurityCritical]  // auto-generated
         private TypeLoadException(String className,
                                   String assemblyName,
                                   String messageArg,
@@ -112,14 +109,12 @@ namespace System {
             ResourceId = info.GetInt32("TypeLoadResourceID");
         }
     
-        [System.Security.SecurityCritical]  // auto-generated
         [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.
-        [System.Security.SecurityCritical]  // auto-generated_required
         public override void GetObjectData(SerializationInfo info, StreamingContext context) {
             if (info == null)
                 throw new ArgumentNullException(nameof(info));
index 0fadf39..8445782 100644 (file)
@@ -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;
+using System.Diagnostics;
 using System.Diagnostics.Contracts;
 using System.IO;
 using System.Reflection;
@@ -15,11 +16,9 @@ using Microsoft.Win32.SafeHandles;
 
 namespace System
 {
-    [SecurityCritical]
     internal class SafeTypeNameParserHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
         #region QCalls
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void _ReleaseTypeNameParser(IntPtr pTypeNameParser);
@@ -30,7 +29,6 @@ namespace System
         {
         }
 
-        [SecurityCritical]
         protected override bool ReleaseHandle()
         {
             _ReleaseTypeNameParser(handle);
@@ -42,34 +40,28 @@ namespace System
     internal sealed class TypeNameParser : IDisposable
     {
         #region QCalls
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void _CreateTypeNameParser(string typeName, ObjectHandleOnStack retHandle, bool throwOnError);
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void _GetNames(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray);
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void _GetTypeArguments(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray);
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void _GetModifiers(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray);
 
-        [SecurityCritical]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void _GetAssemblyName(SafeTypeNameParserHandle pTypeNameParser, StringHandleOnStack retString);
         #endregion
 
         #region Static Members
-        [SecuritySafeCritical]
         internal static Type GetType(
             string typeName,
             Func<AssemblyName, Assembly> assemblyResolver,
@@ -103,19 +95,16 @@ namespace System
         #endregion
 
         #region Private Data Members
-        [SecurityCritical]
         private SafeTypeNameParserHandle m_NativeParser;
         private static readonly char[] SPECIAL_CHARS = {',', '[', ']', '&', '*', '+', '\\'}; /* see typeparse.h */
         #endregion
 
         #region Constructor and Disposer
-        [SecuritySafeCritical]
         private TypeNameParser(SafeTypeNameParserHandle handle)
         {
             m_NativeParser = handle;
         }
 
-        [SecuritySafeCritical]
         public void Dispose()
         {
             m_NativeParser.Dispose();
@@ -123,7 +112,6 @@ namespace System
         #endregion
 
         #region private Members
-        [SecuritySafeCritical]
         private unsafe Type ConstructType(
             Func<AssemblyName, Assembly> assemblyResolver,
             Func<Assembly, string, bool, Type> typeResolver,
@@ -136,7 +124,7 @@ namespace System
             string asmName = GetAssemblyName();
 
             // GetAssemblyName never returns null
-            Contract.Assert(asmName != null);
+            Debug.Assert(asmName != null);
 
             if (asmName.Length > 0)
             {
@@ -164,7 +152,7 @@ namespace System
             if (baseType == null)
             {
                 // Cannot resolve the type. If throwOnError is true we should have already thrown.
-                Contract.Assert(throwOnError == false);
+                Debug.Assert(throwOnError == false);
                 return null;
             }
 
@@ -176,7 +164,7 @@ namespace System
                 types = new Type[typeArguments.Length];
                 for (int i = 0; i < typeArguments.Length; i++)
                 {
-                    Contract.Assert(typeArguments[i] != null);
+                    Debug.Assert(typeArguments[i] != null);
 
                     using (TypeNameParser argParser = new TypeNameParser(typeArguments[i]))
                     {
@@ -186,7 +174,7 @@ namespace System
                     if (types[i] == null)
                     {
                         // If throwOnError is true argParser.ConstructType should have already thrown.
-                        Contract.Assert(throwOnError == false);
+                        Debug.Assert(throwOnError == false);
                         return null;
                     }
                 }
@@ -201,7 +189,6 @@ namespace System
             }
         }
 
-        [SecuritySafeCritical]
         private static Assembly ResolveAssembly(string asmName, Func<AssemblyName, Assembly> assemblyResolver, bool throwOnError, ref StackCrawlMark stackMark)
         {
             Contract.Requires(asmName != null && asmName.Length > 0);
@@ -316,7 +303,6 @@ namespace System
             return StringBuilderCache.GetStringAndRelease(sb);
         }
 
-        [SecuritySafeCritical]
         private static SafeTypeNameParserHandle CreateTypeNameParser(string typeName, bool throwOnError)
         {
             SafeTypeNameParserHandle retHandle = null;
@@ -325,7 +311,6 @@ namespace System
             return retHandle;
         }
 
-        [SecuritySafeCritical]
         private string[] GetNames()
         {
             string[] names = null;
@@ -334,7 +319,6 @@ namespace System
             return names;
         }
 
-        [SecuritySafeCritical]
         private SafeTypeNameParserHandle[] GetTypeArguments()
         {
             SafeTypeNameParserHandle[] arguments = null;
@@ -343,7 +327,6 @@ namespace System
             return arguments;
         }
 
-        [SecuritySafeCritical]
         private int[] GetModifiers()
         {
             int[] modifiers = null;
@@ -352,7 +335,6 @@ namespace System
             return modifiers;
         }
 
-        [SecuritySafeCritical]
         private string GetAssemblyName()
         {
             string assemblyName = null;
index 9d3f36f..b65652e 100644 (file)
@@ -23,7 +23,6 @@ namespace System {
         private IntPtr Value;
         private IntPtr Type;
 
-        [System.Security.SecurityCritical]  // auto-generated_required
         [CLSCompliant(false)]
         public static TypedReference MakeTypedReference(Object target, FieldInfo[] flds) {
             if (target == null)
@@ -71,7 +70,6 @@ namespace System {
             return result;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         // reference to TypedReference is banned, so have to pass result as pointer
         private unsafe static extern void InternalMakeTypedReference(void* result, Object target, IntPtr[] flds, RuntimeType lastFieldType);
@@ -89,13 +87,11 @@ namespace System {
             throw new NotSupportedException(Environment.GetResourceString("NotSupported_NYI"));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe static Object ToObject(TypedReference value)
         {
             return InternalToObject(&value);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal unsafe extern static Object InternalToObject(void * value);
 
@@ -118,14 +114,12 @@ namespace System {
         }
 
         //  This may cause the type to be changed.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         public unsafe static void SetTypedReference(TypedReference target, Object value)
         {
             InternalSetTypedReference(&target, value);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal unsafe extern static void InternalSetTypedReference(void * target, Object value);
     }
index dba7f97..399ef02 100644 (file)
@@ -68,26 +68,22 @@ namespace System {
         }
 
         // Converts the current value to a String in base-10 with no extra padding.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format, IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
index 7010dae..f3d6009 100644 (file)
@@ -79,25 +79,21 @@ namespace System {
         }
     
         // The base 10 representation of the number with no extra padding.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format, IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
index 83549cf..b55cd7c 100644 (file)
@@ -75,25 +75,21 @@ namespace System {
             return ((int)m_value) ^ (int)(m_value >> 32);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt64(m_value, null, NumberFormatInfo.CurrentInfo);
         }
         
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
         }        
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt64(m_value, format, NumberFormatInfo.CurrentInfo);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public String ToString(String format, IFormatProvider provider) {
             Contract.Ensures(Contract.Result<String>() != null);
             return Number.FormatUInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
index 141eb4d..eab424f 100644 (file)
@@ -24,20 +24,17 @@ namespace System {
     [System.Runtime.InteropServices.ComVisible(true)]
     public struct UIntPtr : IEquatable<UIntPtr>, ISerializable
     {
-        [SecurityCritical]
         unsafe private void* m_value;
 
         public static readonly UIntPtr Zero;
 
                 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe UIntPtr(uint value)
         {
             m_value = (void *)value;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe UIntPtr(ulong value)
         {
@@ -48,7 +45,6 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecurityCritical]
         [CLSCompliant(false)]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe UIntPtr(void* value)
@@ -56,7 +52,6 @@ namespace System {
             m_value = value;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         private unsafe UIntPtr(SerializationInfo info, StreamingContext context) {
             ulong l = info.GetUInt64("value");
 
@@ -67,7 +62,6 @@ namespace System {
             m_value = (void *)l;
         }
 
-        [System.Security.SecurityCritical]
         unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info==null) {
@@ -77,7 +71,6 @@ namespace System {
             info.AddValue("value", (ulong)m_value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe override bool Equals(Object obj) {
             if (obj is UIntPtr) {
                 return (m_value == ((UIntPtr)obj).m_value);
@@ -85,27 +78,20 @@ namespace System {
             return false;
         }
 
-        [SecuritySafeCritical]
         unsafe bool IEquatable<UIntPtr>.Equals(UIntPtr other)
         {
             return m_value == other.m_value;
         }
     
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe override int GetHashCode() {
-#if FEATURE_CORECLR
 #if BIT64
             ulong l = (ulong)m_value;
             return (unchecked((int)l) ^ (int)(l >> 32));
 #else // 32
             return unchecked((int)m_value);
 #endif
-#else
-            return unchecked((int)((long)m_value)) & 0x7fffffff;
-#endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe uint ToUInt32() {
 #if BIT64
@@ -115,13 +101,11 @@ namespace System {
 #endif
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe ulong ToUInt64() {
             return (ulong)m_value;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public unsafe override String ToString() {
             Contract.Ensures(Contract.Result<String>() != null);
 
@@ -144,7 +128,6 @@ namespace System {
             return new UIntPtr(value);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static explicit operator uint(UIntPtr value)
         {
@@ -155,14 +138,12 @@ namespace System {
 #endif
         }   
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static explicit operator ulong (UIntPtr  value) 
         {
             return (ulong)value.m_value;
         }
 
-        [System.Security.SecurityCritical]
         [CLSCompliant(false)]
         [System.Runtime.Versioning.NonVersionable]
         public static unsafe explicit operator UIntPtr (void* value)
@@ -170,7 +151,6 @@ namespace System {
             return new UIntPtr(value);
         }
 
-        [System.Security.SecurityCritical]
         [CLSCompliant(false)]
         [System.Runtime.Versioning.NonVersionable]
         public static unsafe explicit operator void* (UIntPtr value)
@@ -179,7 +159,6 @@ namespace System {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool operator == (UIntPtr value1, UIntPtr value2) 
         {
@@ -187,7 +166,6 @@ namespace System {
         }
 
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [System.Runtime.Versioning.NonVersionable]
         public unsafe static bool operator != (UIntPtr value1, UIntPtr value2) 
         {
@@ -235,7 +213,6 @@ namespace System {
             }
         }
        
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [CLSCompliant(false)]
         [System.Runtime.Versioning.NonVersionable]
         public unsafe void* ToPointer()
index 7d65319..8c27982 100644 (file)
@@ -5,9 +5,6 @@
 namespace System {
    
     using System;
-#if FEATURE_CORECLR
-     [System.Security.SecurityCritical] // auto-generated
-#endif
     [Serializable]
     [System.Runtime.InteropServices.ComVisible(true)]
     public delegate void UnhandledExceptionEventHandler(Object sender, UnhandledExceptionEventArgs e);
index 2840004..712391a 100644 (file)
@@ -204,7 +204,6 @@ namespace System {
         #endregion
 
         #region ISerializable
-        [System.Security.SecurityCritical]  // auto-generated
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context) 
         {
             throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnitySerHolder"));
@@ -212,7 +211,6 @@ namespace System {
         #endregion
 
         #region IObjectReference
-        [System.Security.SecurityCritical]  // auto-generated
         public virtual Object GetRealObject(StreamingContext context) 
         {
             // GetRealObject uses the data we have in m_data and m_unityType to do a lookup on the correct 
index ae08b7d..102a0d2 100644 (file)
@@ -20,7 +20,6 @@ namespace System {
 [System.Runtime.InteropServices.ComVisible(true)]
     public abstract class ValueType {
 
-        [System.Security.SecuritySafeCritical]
         public override bool Equals (Object obj) {
             BCLDebug.Perf(false, "ValueType::Equals is not fast.  "+this.GetType().FullName+" should override Equals(Object)");
             if (null==obj) {
@@ -60,11 +59,9 @@ namespace System {
             return true;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool CanCompareBits(Object obj);
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern bool FastEqualsCheck(Object a, Object b);
 
@@ -78,7 +75,6 @@ namespace System {
         **Arguments: None.
         **Exceptions: None.
         ==============================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         public extern override int GetHashCode();
 
index c75f82f..2a9593c 100644 (file)
@@ -19,6 +19,7 @@ namespace System {
     using System.Globalization;
     using System.Runtime.CompilerServices;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     [Serializable]
@@ -118,19 +119,14 @@ namespace System {
         //
         // Native Methods
         //
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern double GetR8FromVar();
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern float  GetR4FromVar();
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void   SetFieldsR4(float val);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void   SetFieldsR8(double val);
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal extern void SetFieldsObject(Object val);
 
@@ -224,7 +220,6 @@ namespace System {
             m_data2 = (int)(val >> 32);
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Variant(float val) {
             m_objref=null;
             m_flags=CV_R4;
@@ -233,7 +228,6 @@ namespace System {
             SetFieldsR4(val);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         public Variant(double val) {
             m_objref=null;
             m_flags=CV_R8;
@@ -257,7 +251,6 @@ namespace System {
             m_data2=0;
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Variant(Object obj) {
             m_data1=0;
             m_data2=0;
@@ -317,13 +310,13 @@ namespace System {
             {
                 vt = VarEnum.VT_ERROR;
                 obj = (Object)(((ErrorWrapper)obj).ErrorCode);
-                Contract.Assert(obj != null, "obj != null");
+                Debug.Assert(obj != null, "obj != null");
             }
             else if (obj is CurrencyWrapper)
             {
                 vt = VarEnum.VT_CY;
                 obj = (Object)(((CurrencyWrapper)obj).WrappedObject);
-                Contract.Assert(obj != null, "obj != null");
+                Debug.Assert(obj != null, "obj != null");
             }
             else if (obj is BStrWrapper)
             {
@@ -342,7 +335,6 @@ namespace System {
         }
 
 
-        [System.Security.SecurityCritical]  // auto-generated
         unsafe public Variant(void* voidPointer,Type pointerType) {
             if (pointerType == null)
                 throw new ArgumentNullException(nameof(pointerType));
@@ -365,7 +357,6 @@ namespace System {
             }
         }
 
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public Object ToObject() {
             switch (CVType) {
             case CV_EMPTY:
@@ -413,21 +404,16 @@ namespace System {
         }
 
         // This routine will return an boxed enum.
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private extern Object BoxEnum();
 
 
         // Helper code for marshaling managed objects to VARIANT's (we use
         // managed variants as an intermediate type.
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal static void MarshalHelperConvertObjectToVariant(Object o, ref Variant v)
         {
-#if FEATURE_REMOTING
-            IConvertible ic = System.Runtime.Remoting.RemotingServices.IsTransparentProxy(o) ? null : o as IConvertible;
-#else
             IConvertible ic = o as IConvertible;
-#endif
+
             if (o == null)
             {
                 v = Empty;
@@ -532,7 +518,6 @@ namespace System {
         // Helper code: on the back propagation path where a VT_BYREF VARIANT*
         // is marshaled to a "ref Object", we use this helper to force the
         // updated object back to the original type.
-        [System.Security.SecurityCritical]  // auto-generated
         internal static void MarshalHelperCastVariant(Object pValue, int vt, ref Variant v)
         {
             IConvertible iv = pValue as IConvertible;
index fd5b295..f2ef5d4 100644 (file)
@@ -12,6 +12,7 @@
 ===========================================================*/
 namespace System {
 
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
     using System.Text;
     using CultureInfo = System.Globalization.CultureInfo;
@@ -100,7 +101,7 @@ namespace System {
 
         private Version(Version version)
         {
-            Contract.Assert(version != null);
+            Debug.Assert(version != null);
 
             _Major = version._Major;
             _Minor = version._Minor;
@@ -257,7 +258,7 @@ namespace System {
         private const int ZERO_CHAR_VALUE = (int) '0';
         private static void AppendPositiveNumber(int num, StringBuilder sb)
         {
-            Contract.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
+            Debug.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
 
             int index = sb.Length;
             int reminder;
@@ -436,10 +437,10 @@ namespace System {
                         } catch (OverflowException e) {
                             return e;
                         }
-                        Contract.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
+                        Debug.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
                         return new FormatException(Environment.GetResourceString("Format_InvalidString"));
                     default:
-                        Contract.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
+                        Debug.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
                         return new ArgumentException(Environment.GetResourceString("Arg_VersionString"));
                 }
             }
index 27a9ab7..d564852 100644 (file)
@@ -16,11 +16,10 @@ namespace System {
     using System.Security.Permissions;
     using System.Runtime.CompilerServices;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
+
     [System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CORECLR
-    [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] // Don't call Object::MemberwiseClone.
-#endif
     [Serializable]
     public class WeakReference : ISerializable 
     {
@@ -28,15 +27,12 @@ namespace System {
 
         // This field is not a regular GC handle. It can have a special values that are used to prevent a race condition between setting the target and finalization.
         internal IntPtr m_handle;
-    
-#if FEATURE_CORECLR
+
         // Migrating InheritanceDemands requires this default ctor, so we can mark it SafeCritical
-        [SecuritySafeCritical]
         protected WeakReference() {
-            Contract.Assert(false, "WeakReference's protected default ctor should never be used!");
+            Debug.Assert(false, "WeakReference's protected default ctor should never be used!");
             throw new NotImplementedException();
         }
-#endif
 
         // Creates a new WeakReference that keeps track of target.
         // Assumes a Short Weak Reference (ie TrackResurrection is false.)
@@ -68,7 +64,6 @@ namespace System {
         //
         public extern virtual bool IsAlive {
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
-            [SecuritySafeCritical]
             get;
          }
     
@@ -85,10 +80,8 @@ namespace System {
         //
         public extern virtual Object Target {
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
-            [SecuritySafeCritical]
             get;
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
-            [SecuritySafeCritical]
             set;
         }
     
@@ -99,10 +92,8 @@ namespace System {
         // This is needed for subclasses deriving from WeakReference, however.
         // Additionally, there may be some cases during shutdown when we run this finalizer.
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecuritySafeCritical]
         extern ~WeakReference();
 
-        [SecurityCritical]
         public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info==null) {
@@ -114,11 +105,9 @@ namespace System {
         }
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecuritySafeCritical]
         private extern void Create(Object target, bool trackResurrection);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecuritySafeCritical]
         private extern bool IsTrackResurrection();
     }
 
index da2999e..0972e5f 100644 (file)
@@ -81,10 +81,8 @@ namespace System
         private extern T Target
         {
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
-            [SecuritySafeCritical]
             get;
             [MethodImplAttribute(MethodImplOptions.InternalCall)]
-            [SecuritySafeCritical]
             set;
         }
 
@@ -95,10 +93,8 @@ namespace System
         // This is needed for subclasses deriving from WeakReference<T>, however.
         // Additionally, there may be some cases during shutdown when we run this finalizer.
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecuritySafeCritical]
         extern ~WeakReference();
 
-        [SecurityCritical]
         public void GetObjectData(SerializationInfo info, StreamingContext context)
         {
             if (info == null) {
@@ -111,11 +107,9 @@ namespace System
         }
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecuritySafeCritical]
         private extern void Create(T target, bool trackResurrection);
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
-        [SecuritySafeCritical]
         private extern bool IsTrackResurrection();
     }
 }
index a3a312f..a1fa488 100644 (file)
@@ -17,6 +17,7 @@ namespace System {
     using System;
     using System.Threading;
     using System.Runtime.CompilerServices;
+    using System.Diagnostics;
     using System.Diagnostics.Contracts;
 
     // Helper class to aid removal of LocalDataStore from the LocalDataStoreMgr
@@ -197,7 +198,6 @@ namespace System {
         /*=========================================================================
         ** Method used to expand the capacity of the local data store.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         private LocalDataStoreElement PopulateElement(LocalDataStoreSlot slot)
         {
             bool tookLock = false;
@@ -215,7 +215,7 @@ namespace System {
                     int capacity = m_Manager.GetSlotTableLength();
 
                     // Validate that the specified capacity is larger than the current one.
-                    Contract.Assert(capacity >= m_DataTable.Length, "LocalDataStore corrupted: capacity >= m_DataTable.Length");
+                    Debug.Assert(capacity >= m_DataTable.Length, "LocalDataStore corrupted: capacity >= m_DataTable.Length");
 
                     // Allocate the new data table.
                     LocalDataStoreElement[] NewDataTable = new LocalDataStoreElement[capacity];
@@ -228,7 +228,7 @@ namespace System {
                 }
 
                 // Validate that there is enough space in the local data store now
-                Contract.Assert(slotIdx < m_DataTable.Length, "LocalDataStore corrupted: slotIdx < m_DataTable.Length");
+                Debug.Assert(slotIdx < m_DataTable.Length, "LocalDataStore corrupted: slotIdx < m_DataTable.Length");
 
                 if (m_DataTable[slotIdx] == null)
                     m_DataTable[slotIdx] = new LocalDataStoreElement(slot.Cookie);
index 6078b2e..8f60d6f 100644 (file)
@@ -89,7 +89,6 @@ namespace System {
         ** list. The initial size of the new store matches the number of slots
         ** allocated in this manager.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public LocalDataStoreHolder CreateLocalDataStore()
         {
             // Create a new local data store.
@@ -115,7 +114,6 @@ namespace System {
         /*=========================================================================
          * Remove the specified store from the list of managed stores..
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void DeleteLocalDataStore(LocalDataStore store)
         {
             bool tookLock = false;
@@ -138,7 +136,6 @@ namespace System {
         ** an object to prevent clients from manipulating it directly, allowing us
         ** to make assumptions its integrity.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public LocalDataStoreSlot AllocateDataSlot()
         {
             bool tookLock = false;
@@ -208,7 +205,6 @@ namespace System {
         /*=========================================================================
         ** Allocate a slot and associate a name with it.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public LocalDataStoreSlot AllocateNamedDataSlot(String name)
         {
             bool tookLock = false;
@@ -235,7 +231,6 @@ namespace System {
         ** Retrieve the slot associated with a name, allocating it if no such
         ** association has been defined.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public LocalDataStoreSlot GetNamedDataSlot(String name)
         {
             bool tookLock = false;
@@ -264,7 +259,6 @@ namespace System {
         ** Eliminate the association of a name with a slot.  The actual slot will
         ** be reclaimed when the finalizer for the slot object runs.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         public void FreeNamedDataSlot(String name)
         {
             bool tookLock = false;
@@ -285,7 +279,6 @@ namespace System {
         /*=========================================================================
         ** Free's a previously allocated data slot on ALL the managed data stores.
         =========================================================================*/
-        [System.Security.SecuritySafeCritical]  // auto-generated
         internal void FreeDataSlot(int slot, long cookie)
         {
             bool tookLock = false;
index a592370..9f9bac6 100644 (file)
@@ -12,8 +12,8 @@
 **
 ** 
 ===========================================================*/
-namespace System {
-    
+namespace System
+{
     using System;
     using System.Collections;
     using System.Threading;
@@ -59,7 +59,6 @@ namespace System {
             return base.ToString();
         }
         
-        [System.Security.SecurityCritical]  // auto-generated
         internal IntPtr GetIUnknown(out bool fIsURTAggregated)
         {
             fIsURTAggregated = !GetType().IsDefined(typeof(ComImportAttribute), false);
@@ -118,7 +117,6 @@ namespace System {
         // This method is called from within the EE and releases all the 
         // cached data for the __ComObject.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated
         internal void ReleaseAllData()
         {
             // Synchronize access to the map.
@@ -154,7 +152,6 @@ namespace System {
         // This method is called from within the EE and is used to handle
         // calls on methods of event interfaces.
         //====================================================================
-        [System.Security.SecurityCritical]  // auto-generated
         internal Object GetEventProvider(RuntimeType t)
         {
             // Check to see if we already have a cached event provider for this type.
@@ -167,22 +164,16 @@ namespace System {
             return EvProvider;
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal int ReleaseSelf()
         {
             return Marshal.InternalReleaseComObject(this);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         internal void FinalReleaseSelf()
         {
             Marshal.InternalFinalReleaseComObject(this);
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
-#if !FEATURE_CORECLR
-        [ReflectionPermissionAttribute(SecurityAction.Assert, MemberAccess=true)]
-#endif
         private Object CreateEventProvider(RuntimeType t)
         {
             // Create the event provider for the specified type.
index 7d3620a..a83943d 100644 (file)
@@ -2,23 +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.
 
-
-using System;
-using System.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Security.Permissions;
-using System.Security.Policy;
-
 namespace System.Runtime.InteropServices
 {
     [GuidAttribute("03973551-57A1-3900-A2B5-9083E3FF2943")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Activator))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _Activator
     {
         void GetTypeInfoCount(out uint pcTInfo);
@@ -34,35 +24,17 @@ namespace System.Runtime.InteropServices
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Attribute))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _Attribute
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 
     [GuidAttribute("C281C7F1-4AA9-3517-961A-463CFED57E75")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     [CLSCompliant(false)]
     [TypeLibImportClassAttribute(typeof(System.Threading.Thread))]
-[System.Runtime.InteropServices.ComVisible(true)]
+    [System.Runtime.InteropServices.ComVisible(true)]
     public interface _Thread
     {
-#if !FEATURE_CORECLR
-        void GetTypeInfoCount(out uint pcTInfo);
-
-        void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
-        void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
-        void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
     }
 }
index 089039c..f750e99 100644 (file)
@@ -18,7 +18,6 @@ namespace System
             private static volatile int _captureAllocatedCallStackState;
 
             internal static bool Enabled {
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 get {
                     if (_enabledState == 0) {
                         if (Mda.IsStreamWriterBufferedDataLostEnabled())
@@ -32,7 +31,6 @@ namespace System
             }
 
             internal static bool CaptureAllocatedCallStack {
-                [System.Security.SecuritySafeCritical]  // auto-generated
                 get {
                     if (_captureAllocatedCallStackState == 0) {
                         if (Mda.IsStreamWriterBufferedDataLostCaptureAllocatedCallStack())
@@ -45,42 +43,33 @@ namespace System
                 }
             }
 
-            [System.Security.SecuritySafeCritical]  // auto-generated
             internal static void ReportError(String text) {
                 Mda.ReportStreamWriterBufferedDataLost(text);
             }
 
         }
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void ReportStreamWriterBufferedDataLost(String text);
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool IsStreamWriterBufferedDataLostEnabled();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool IsStreamWriterBufferedDataLostCaptureAllocatedCallStack();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void MemberInfoCacheCreation();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void DateTimeInvalidLocalFormat();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern bool IsInvalidGCHandleCookieProbeEnabled();
 
-        [System.Security.SecurityCritical]  // auto-generated
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void FireInvalidGCHandleCookieProbe(IntPtr cookie);
 
-        [System.Security.SecurityCritical]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         internal static extern void ReportErrorSafeHandleRelease(Exception ex);
     }
index fc8ed53..0e55301 100644 (file)
@@ -3,10 +3,8 @@
 // See the LICENSE file in the project root for more information.
 using System.Runtime.CompilerServices;
 
-#if FEATURE_CORECLR
 // We need this to be able to typeforward to internal types
 [assembly: InternalsVisibleTo("mscorlib, PublicKey=00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab", AllInternalsVisible=false)]
-#endif
 
 // For now we are only moving to using this file over AssemblyAttributes.cspp in CoreSys, ideally we would move away from the centralized 
 // AssemblyAttributes.cspp model for the other build types at a future point in time.
index ba3cb24..28c6278 100644 (file)
@@ -5679,9 +5679,7 @@ CoCreateGuid(OUT GUID * pguid);
 #define printf        PAL_printf
 #define vprintf       PAL_vprintf
 #define wprintf       PAL_wprintf
-#define sprintf       PAL_sprintf
 #define swprintf      PAL_swprintf
-#define sscanf        PAL_sscanf
 #define wcsspn        PAL_wcsspn
 #define wcstod        PAL_wcstod
 #define wcstol        PAL_wcstol
@@ -5850,9 +5848,7 @@ PALIMPORT char * __cdecl strstr(const char *, const char *);
 PALIMPORT char * __cdecl strtok(char *, const char *);
 PALIMPORT size_t __cdecl strspn(const char *, const char *);
 PALIMPORT size_t  __cdecl strcspn(const char *, const char *);
-PALIMPORT int __cdecl sprintf(char *, const char *, ...);
 PALIMPORT int __cdecl vsprintf(char *, const char *, va_list);
-PALIMPORT int __cdecl sscanf(const char *, const char *, ...);
 PALIMPORT int __cdecl atoi(const char *);
 PALIMPORT LONG __cdecl atol(const char *);
 PALIMPORT ULONG __cdecl strtoul(const char *, char **, int);
@@ -5898,6 +5894,7 @@ PALIMPORT int __cdecl sprintf_s(char *, size_t, const char *, ... );
 PALIMPORT int __cdecl swprintf_s(WCHAR *, size_t, const WCHAR *, ... );
 PALIMPORT int __cdecl _snwprintf_s(WCHAR *, size_t, size_t, const WCHAR *, ...);
 PALIMPORT int __cdecl vswprintf_s( WCHAR *, size_t, const WCHAR *, va_list);
+PALIMPORT int __cdecl sscanf_s(const char *, const char *, ...);
 PALIMPORT errno_t __cdecl _itow_s(int, WCHAR *, size_t, int);
 
 PALIMPORT size_t __cdecl PAL_wcslen(const WCHAR *);
index ab46f21..c181f38 100644 (file)
@@ -895,7 +895,6 @@ Remember to fix the errcode defintion in safecrt.h.
 #define _wcslwr_s _wcslwr_unsafe
 #define _snprintf_s _snprintf_unsafe
 #define swscanf_s swscanf
-#define sscanf_s sscanf
 
 #define _wfopen_s _wfopen_unsafe
 #define fopen_s _fopen_unsafe
index 2cff7d1..d7d5304 100644 (file)
@@ -35,3 +35,33 @@ C_FUNC(\Name\()_End):
         .global C_FUNC(\Name\()_End)
         LEAF_END \Name, \Section
 .endm
+
+.macro PROLOG_BEG
+        push ebp
+        .cfi_def_cfa_offset 8
+        .cfi_offset ebp, -8
+        mov ebp, esp
+.endm
+
+.macro PROLOG_PUSH Reg
+        push \Reg
+        .cfi_adjust_cfa_offset 4
+        .cfi_rel_offset \Reg, 0
+.endm
+
+.macro PROLOG_END
+        .cfi_def_cfa_register ebp
+        .cfi_def_cfa_offset 8
+.endm
+
+.macro EPILOG_BEG
+.endm
+
+.macro EPILOG_POP Reg
+        pop \Reg
+        .cfi_restore \Reg
+.endm
+
+.macro EPILOG_END
+        pop ebp
+.endm
index 0f91edb..28ee83a 100644 (file)
@@ -186,8 +186,8 @@ set(SOURCES
   safecrt/safecrt_winput_s.cpp
   safecrt/safecrt_woutput_s.cpp
   safecrt/splitpath_s.cpp
-  safecrt/sprintf.cpp
-  safecrt/sscanf.cpp
+  safecrt/sprintf_s.cpp
+  safecrt/sscanf_s.cpp
   safecrt/strcat_s.cpp
   safecrt/strcpy_s.cpp
   safecrt/strlen_s.cpp
index 543df1b..16cbcc8 100644 (file)
@@ -82,7 +82,7 @@ LOCAL_LABEL(Done_CONTEXT_EXTENDED_REGISTERS):
     // Restore
     pop   ebx
     pop   eax
-    ret
+    ret   4
 LEAF_END CONTEXT_CaptureContext, _TEXT
 
 LEAF_ENTRY RtlCaptureContext, _TEXT
@@ -91,7 +91,6 @@ LEAF_ENTRY RtlCaptureContext, _TEXT
     mov     DWORD PTR [eax + CONTEXT_ContextFlags], (CONTEXT_FLOATING_POINT)
     pop     eax
     jmp     C_FUNC(CONTEXT_CaptureContext)
-    ret
 LEAF_END RtlCaptureContext, _TEXT
 
 LEAF_ENTRY RtlRestoreContext, _TEXT
@@ -147,6 +146,6 @@ LOCAL_LABEL(Done_Restore_CONTEXT_EXTENDED_REGISTERS):
     pop   esi
     pop   edi
 
-    ret
+    ret   8
 LEAF_END RtlRestoreContext, _TEXT
 
index 8396418..c437b8e 100644 (file)
@@ -1365,63 +1365,6 @@ int PAL_wvsscanf(LPCWSTR Buffer, LPCWSTR Format, va_list ap)
 
 /*++
 Function:
-  PAL_sscanf
-
-See MSDN doc.
---*/
-int
-__cdecl
-PAL_sscanf(
-           const char *buffer,
-           const char *format,
-           ...)
-{
-    int Length;
-    va_list ap;
-
-    PERF_ENTRY(sscanf);
-    ENTRY("PAL_sscanf (buffer=%p (%s), format=%p (%s))\n", buffer, buffer, format, format);
-
-    va_start(ap, format);
-    Length = PAL_vsscanf(buffer, format, ap);
-    va_end(ap);
-
-    LOGEXIT("PAL_sscanf returns int %d\n", Length);
-    PERF_EXIT(sscanf);
-    return Length;
-}
-
-/*++
-Function:
-  PAL_sprintf
-
-See MSDN doc.
---*/
-int
-__cdecl
-PAL_sprintf(
-          char *buffer,
-          const char *format,
-          ...)
-{
-    LONG Length;
-    va_list ap;
-
-    PERF_ENTRY(sprintf);
-    ENTRY("PAL_sprintf (buffer=%p, format=%p (%s))\n", buffer, format, format);
-
-    va_start(ap, format);
-    Length = InternalVsnprintf(CorUnix::InternalGetCurrentThread(), buffer, 0x7fffffff, format, ap);
-    va_end(ap);
-
-    LOGEXIT("PAL_sprintf returns int %d\n", Length);
-    PERF_EXIT(sprintf);
-    return Length;
-}
-
-
-/*++
-Function:
   PAL_swprintf
 
 See MSDN doc.
index 5461ac6..756e615 100644 (file)
@@ -857,7 +857,7 @@ DBGDetachProcess(
     if (nbAttachLeft == 0)
     {
 #if HAVE_PROCFS_CTL
-        sprintf(ctlPath, sizeof(ctlPath), "/proc/%d/ctl", processId);
+        snprintf(ctlPath, sizeof(ctlPath), "/proc/%d/ctl", processId);
         fd = InternalOpen(pThread, ctlPath, O_WRONLY);
         if (fd == -1)
         {
index 46c09b8..abc583f 100644 (file)
@@ -36,7 +36,7 @@ using namespace CorUnix;
         if (machret != KERN_SUCCESS)                                        \
         {                                                                   \
             char _szError[1024];                                            \
-            sprintf(_szError, "%s: %u: %s", __FUNCTION__, __LINE__, _msg);  \
+            snprintf(_szError, _countof(_szError), "%s: %u: %s", __FUNCTION__, __LINE__, _msg);  \
             mach_error(_szError, machret);                                  \
             abort();                                                        \
         }                                                                   \
index 92e2d6f..6857c13 100644 (file)
@@ -504,6 +504,7 @@ Parameters :
 
 --*/
 void
+PALAPI
 CONTEXT_CaptureContext(
     LPCONTEXT lpContext
     );
index 44f2528..f7856be 100644 (file)
@@ -502,9 +502,7 @@ function_name() to call the system's implementation
 #undef vfwprintf
 #undef vprintf
 #undef wprintf
-#undef sprintf
 #undef swprintf
-#undef sscanf
 #undef wcstod
 #undef wcstol
 #undef wcstoul
index eaad174..25c4541 100644 (file)
@@ -671,7 +671,7 @@ scanit:
 #endif  /* _SECURE_SCANF */
 #ifndef _UNICODE
                                     if (fl_wchar_arg) {
-                                        wctemp = L'?';
+                                        wctemp = W('?');
                                         char temp[2];
                                         temp[0] = (char) ch;
 #if 0       // we are not supporting multibyte input strings
@@ -682,7 +682,7 @@ scanit:
 #endif  /* 0 */
                                         _MBTOWC(&wctemp, temp, MB_CUR_MAX);
                                         *(wchar_t UNALIGNED *)pointer = wctemp;
-                                        /* just copy L'?' if mbtowc fails, errno is set by mbtowc */
+                                        /* just copy W('?') if mbtowc fails, errno is set by mbtowc */
                                         pointer = (wchar_t *)pointer + 1;
 #ifdef _SECURE_SCANF
                                         --array_width;
index 9b3ffd5..4446f77 100644 (file)
@@ -147,7 +147,6 @@ int _ungetwc_nolock( wchar_t inChar, miniFILE* inStream )
 
 /***
 *   _safecrt_cfltcvt - convert a float to an ascii string.
-*       Uses sprintf - this usage is OK.
 ****/
 
 /* routine used for floating-point output */
@@ -197,14 +196,12 @@ void _safecrt_fassign(int flag, void* argument, char* number )
 {
     if ( flag != 0 )    // double
     {
-        double dblValue = 0.0;
-        (void)sscanf( number, "%lf", &dblValue );
+        double dblValue = strtod(number, NULL);
         *( ( double* )argument ) = dblValue;
     }
     else                // float
     {
-        float fltValue = 0.0;
-        (void)sscanf( number, "%f", &fltValue );
+        float fltValue = strtof(number, NULL);
         *( ( float* )argument ) = fltValue;
     }
 }
similarity index 98%
rename from src/pal/src/safecrt/sprintf.cpp
rename to src/pal/src/safecrt/sprintf_s.cpp
index 8a51d26..edfb768 100644 (file)
@@ -3,7 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 /***
-*sprintf.c - print formatted to string
+*sprintf_s.c - print formatted to string
 *
 
 *
similarity index 99%
rename from src/pal/src/safecrt/sscanf.cpp
rename to src/pal/src/safecrt/sscanf_s.cpp
index d6c21e8..4f548bc 100644 (file)
@@ -3,7 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 /***
-*sscanf.c - read formatted data from string
+*sscanf_s.c - read formatted data from string
 *
 
 *
index d051051..0449df5 100644 (file)
@@ -33,9 +33,6 @@ SET_DEFAULT_DEBUG_CHANNEL(THREAD); // some headers have code with asserts, so do
 
 extern PGET_GCMARKER_EXCEPTION_CODE g_getGcMarkerExceptionCode;
 
-// in context2.S
-extern void CONTEXT_CaptureContext(LPCONTEXT lpContext);
-
 #define CONTEXT_AREA_MASK 0xffff
 #ifdef _X86_
 #define CONTEXT_ALL_FLOATING (CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS)
index c57d604..a64bfb8 100644 (file)
@@ -2049,18 +2049,18 @@ GetProcessIdDisambiguationKey(DWORD processId, UINT64 *disambiguationKey)
 
     // According to `man proc`, the second field in the stat file is the filename of the executable,
     // in parentheses. Tokenizing the stat file using spaces as separators breaks when that name
-    // has spaces in it, so we start using sscanf after skipping everything up to and including the
+    // has spaces in it, so we start using sscanf_s after skipping everything up to and including the
     // last closing paren and the space after it.
     char *scanStartPosition = strrchr(line, ')') + 2;
 
     // All the format specifiers for the fields in the stat file are provided by 'man proc'.
-    int sscanfRet = sscanf(scanStartPosition, 
+    int sscanfRet = sscanf_s(scanStartPosition, 
         "%*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu %*lu %*ld %*ld %*ld %*ld %*ld %*ld %llu \n",
          &starttime);
 
     if (sscanfRet != 1)
     {
-        _ASSERTE(!"Failed to parse stat file contents with sscanf.");
+        _ASSERTE(!"Failed to parse stat file contents with sscanf_s.");
         return FALSE;
     }
 
@@ -2690,7 +2690,7 @@ CreateProcessModules(
         char moduleName[PATH_MAX];
         int size;
 
-        if (sscanf(line, "__TEXT %p-%p [ %dK] %*[-/rwxsp] SM=%*[A-Z] %s\n", &startAddress, &endAddress, &size, moduleName) == 4)
+        if (sscanf_s(line, "__TEXT %p-%p [ %dK] %*[-/rwxsp] SM=%*[A-Z] %s\n", &startAddress, &endAddress, &size, moduleName, _countof(moduleName)) == 4)
         {
             bool dup = false;
             for (ProcessModules *entry = listHead; entry != NULL; entry = entry->Next)
@@ -2768,7 +2768,7 @@ exit:
         int devHi, devLo, inode;
         char moduleName[PATH_MAX];
 
-        if (sscanf(line, "%p-%p %*[-rwxsp] %p %x:%x %d %s\n", &startAddress, &endAddress, &offset, &devHi, &devLo, &inode, moduleName) == 7)
+        if (sscanf_s(line, "%p-%p %*[-rwxsp] %p %x:%x %d %s\n", &startAddress, &endAddress, &offset, &devHi, &devLo, &inode, moduleName, _countof(moduleName)) == 7)
         {
             if (inode != 0)
             {
index d2da527..cf06253 100644 (file)
@@ -86,10 +86,10 @@ add_subdirectory(sin)
 add_subdirectory(sinf)
 add_subdirectory(sinh)
 add_subdirectory(sinhf)
-add_subdirectory(sprintf)
+add_subdirectory(sprintf_s)
 add_subdirectory(sqrt)
 add_subdirectory(sqrtf)
-add_subdirectory(sscanf)
+add_subdirectory(sscanf_s)
 add_subdirectory(strcat)
 add_subdirectory(strchr)
 add_subdirectory(strcmp)
diff --git a/src/pal/tests/palsuite/c_runtime/sprintf/test5/CMakeLists.txt b/src/pal/tests/palsuite/c_runtime/sprintf/test5/CMakeLists.txt
deleted file mode 100644 (file)
index 5d7ce6c..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-cmake_minimum_required(VERSION 2.8.12.2)
-
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
-set(SOURCES
-  test5.cpp
-)
-
-add_executable(paltest_sprintf_test5
-  ${SOURCES}
-)
-
-add_dependencies(paltest_sprintf_test5 coreclrpal)
-
-target_link_libraries(paltest_sprintf_test5
-  pthread
-  m
-  coreclrpal
-)
diff --git a/src/pal/tests/palsuite/c_runtime/sprintf/test5/test5.cpp b/src/pal/tests/palsuite/c_runtime/sprintf/test5/test5.cpp
deleted file mode 100644 (file)
index 1b52da7..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================================
-**
-** Source:  test5.c
-**
-** Purpose: Test #5 for the sprintf function. Tests the count specifier (%n).
-**
-**
-**==========================================================================*/
-
-
-
-#include <palsuite.h>
-#include "../sprintf.h"
-
-/* 
- * Depends on memcmp and strlen
- */
-
-
-int __cdecl main(int argc, char *argv[])
-{    
-    char *longStr =
- "really-long-string-that-just-keeps-going-on-and-on-and-on.."
-        "..................useless-filler.................................."
-        "..................useless-filler.................................."
-        "..................useless-filler.................................."
-        "%n bar";
-    char *longResult =
- "really-long-string-that-just-keeps-going-on-and-on-and-on.."
-        "..................useless-filler.................................."
-        "..................useless-filler.................................."
-        "..................useless-filler.................................."
-        " bar";
-
-    if (PAL_Initialize(argc, argv)!= 0)
-    {
-        return FAIL;
-    }
-
-    DoCountTest("foo %n bar", 4, "foo  bar");
-    DoCountTest(longStr, 257, longResult);
-    DoCountTest("fo%n bar", 2, "fo bar");
-    DoCountTest("%n", 0, "");
-    DoCountTest("foo %#n bar", 4, "foo  bar");
-    DoCountTest("foo % n bar", 4, "foo  bar");
-    DoCountTest("foo %+n bar", 4, "foo  bar");
-    DoCountTest("foo %-n bar", 4, "foo  bar");
-    DoCountTest("foo %0n bar", 4, "foo  bar");
-    DoShortCountTest("foo %hn bar", 4, "foo  bar");
-    DoCountTest("foo %ln bar", 4, "foo  bar");
-    DoCountTest("foo %Ln bar", 4, "foo  bar");
-    DoCountTest("foo %I64n bar", 4, "foo  bar");
-    DoCountTest("foo %20.3n bar", 4, "foo  bar");
-
-    PAL_Terminate();
-   
-    return PASS;
-}
diff --git a/src/pal/tests/palsuite/c_runtime/sprintf/test5/testinfo.dat b/src/pal/tests/palsuite/c_runtime/sprintf/test5/testinfo.dat
deleted file mode 100644 (file)
index 31e0537..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-# Licensed to the .NET Foundation under one or more agreements.
-# The .NET Foundation licenses this file to you under the MIT license.
-# See the LICENSE file in the project root for more information.
-
-Version = 1.0
-Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
-TYPE = DEFAULT
-EXE1 = test5
-Description
-= Tests sprintf with the count specifier
@@ -14,7 +14,6 @@ add_subdirectory(test19)
 add_subdirectory(test2)
 add_subdirectory(test3)
 add_subdirectory(test4)
-add_subdirectory(test5)
 add_subdirectory(test6)
 add_subdirectory(test7)
 add_subdirectory(test8)
@@ -4,21 +4,21 @@
 
 /*============================================================================
 **
-** Source:  sprintf.h
+** Source:  sprintf_s.h
 **
-** Purpose: Containts common testing functions for sprintf
+** Purpose: Containts common testing functions for sprintf_s
 **
 **
 **==========================================================================*/
 
-#ifndef __SPRINTF_H__
-#define __SPRINTF_H__
+#ifndef __SPRINTF_S_H__
+#define __SPRINTF_S_H__
 
 void DoStrTest(const char *formatstr, char* param, const char *checkstr)
 {
     char buf[256] = { 0 };
 
-    sprintf(buf, formatstr, param);
+    sprintf_s(buf, _countof(buf), formatstr, param);
     if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
     {
         Fail("ERROR: failed to insert string \"%s\" into \"%s\"\n"
@@ -31,7 +31,7 @@ void DoWStrTest(const char *formatstr, WCHAR* param, const char *checkstr)
 {
     char buf[256] = { 0 };
 
-    sprintf(buf, formatstr, param);
+    sprintf_s(buf, _countof(buf), formatstr, param);
     if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
     {
         Fail("ERROR: failed to insert wide string \"%s\" into \"%s\"\n"
@@ -45,7 +45,7 @@ void DoPointerTest(const char *formatstr, void* param, char* paramstr,
 {
     char buf[256] = { 0 };
 
-    sprintf(buf, formatstr, param);
+    sprintf_s(buf, _countof(buf), formatstr, param);
     if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0)
     {
         Fail("ERROR: failed to insert %s into \"%s\"\n"
@@ -59,7 +59,7 @@ void DoCountTest(const char *formatstr, int param, const char *checkstr)
     char buf[512] = { 0 };
     int n = -1;
     
-    sprintf(buf, formatstr, &n);
+    sprintf_s(buf, _countof(buf), formatstr, &n);
 
     if (n != param)
     {
@@ -77,7 +77,7 @@ void DoShortCountTest(const char *formatstr, int param, const char *checkstr)
     char buf[256] = { 0 };
     short int n = -1;
 
-    sprintf(buf, formatstr, &n);
+    sprintf_s(buf, _countof(buf), formatstr, &n);
 
     if (n != param)
     {
@@ -95,7 +95,7 @@ void DoCharTest(const char *formatstr, char param, const char *checkstr)
 {
     char buf[256] = { 0 };
 
-    sprintf(buf, formatstr, param);
+    sprintf_s(buf, _countof(buf), formatstr, param);
     if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
     {
         Fail("ERROR: failed to insert char \'%c\' (%d) into \"%s\"\n"
@@ -108,7 +108,7 @@ void DoWCharTest(const char *formatstr, WCHAR param, const char *checkstr)
 {
     char buf[256] = { 0 };
 
-    sprintf(buf, formatstr, param);
+    sprintf_s(buf, _countof(buf), formatstr, param);
     if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
     {
         Fail("ERROR: failed to insert wide char \'%c\' (%d) into \"%s\"\n"
@@ -121,7 +121,7 @@ void DoNumTest(const char *formatstr, int value, const char *checkstr)
 {
     char buf[256] = { 0 };
 
-    sprintf(buf, formatstr, value);
+    sprintf_s(buf, _countof(buf), formatstr, value);
     if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
     {
         Fail("ERROR: failed to insert %#x into \"%s\"\n"
@@ -134,7 +134,7 @@ void DoI64Test(const char *formatstr, INT64 value, char *valuestr, const char *c
 {
     char buf[256] = { 0 };
 
-    sprintf(buf, formatstr, value);
+    sprintf_s(buf, _countof(buf), formatstr, value);
     if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0)
     {
         Fail("ERROR: failed to insert %s into \"%s\"\n"
@@ -148,7 +148,7 @@ void DoDoubleTest(const char *formatstr, double value, const char *checkstr1,
 {
     char buf[256] = { 0 };
 
-    sprintf(buf, formatstr, value);
+    sprintf_s(buf, _countof(buf), formatstr, value);
     if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 &&
         memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0)
     {
@@ -163,7 +163,7 @@ void DoArgumentPrecTest(const char *formatstr, int precision, void *param,
 {
     char buf[256];
 
-    sprintf(buf, formatstr, precision, param);
+    sprintf_s(buf, _countof(buf), formatstr, precision, param);
     if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 &&
         memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0)
     {
@@ -179,7 +179,7 @@ void DoArgumentPrecDoubleTest(const char *formatstr, int precision, double param
 {
     char buf[256];
 
-    sprintf(buf, formatstr, precision, param);
+    sprintf_s(buf, _countof(buf), formatstr, precision, param);
     if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 &&
         memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0)
     {
@@ -6,7 +6,7 @@
 **
 ** Source:  test1.c
 **
-** Purpose: Test #1 for the sprintf function. A single, basic, test
+** Purpose: Test #1 for the sprintf_s function. A single, basic, test
 **          case with no formatting.
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -32,7 +32,7 @@ int __cdecl main(int argc, char *argv[])
     }
 
 
-    sprintf(buf, "hello world");
+    sprintf_s(buf, _countof(buf), "hello world");
 
     if (memcmp(checkstr, buf, strlen(checkstr)+1) != 0)
     {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test1
 Description
-= General test to see if sprintf works correctly
+= General test to see if sprintf_s works correctly
@@ -6,7 +6,7 @@
 **
 ** Source:  test10.c
 **
-** Purpose: Test #10 for the sprintf function. Tests the octal specifier
+** Purpose: Test #10 for the sprintf_s function. Tests the octal specifier
 **          (%o).
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test10
 Description
-= Tests sscanf with wide characters
+= Tests sprintf_s with octal numbers
@@ -6,7 +6,7 @@
 **
 ** Source:  test11.c
 **
-** Purpose: Test #11 for the sprintf function. Test the unsigned int
+** Purpose: Test #11 for the sprintf_s function. Test the unsigned int
 **          specifier (%u).
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test11
 Description
-= Tests sprintf with unsigned numbers
+= Tests sprintf_s with unsigned numbers
@@ -6,7 +6,7 @@
 **
 ** Source:  test12.c
 **
-** Purpose: Test #12 for the sprintf function. Tests the (lowercase)
+** Purpose: Test #12 for the sprintf_s function. Tests the (lowercase)
 **          hexadecimal specifier (%x)
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test12
 Description
-= Tests sprintf with hex numbers (lowercase)
+= Tests sprintf_s with hex numbers (lowercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test13.c
 **
-** Purpose: Test #13 for the sprintf function. Tests the (uppercase)
+** Purpose: Test #13 for the sprintf_s function. Tests the (uppercase)
 **          hexadecimal specifier (%X)
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test13
 Description
-= Tests sscanf with floats (decimal notation)
+= Tests sprintf_s with hex numbers (uppercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test14.c
 **
-** Purpose: Test #14 for the sprintf function. Tests the lowercase
+** Purpose: Test #14 for the sprintf_s function. Tests the lowercase
 **          exponential notation double specifier (%e)
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test14
 Description
-= Tests sscanf with floats (exponential notation, lowercase)
+= Tests sprintf_s with exponential format doubles (lowercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test15.c
 **
-** Purpose: Test #15 for the sprintf function. Tests the uppercase
+** Purpose: Test #15 for the sprintf_s function. Tests the uppercase
 **          exponential notation double specifier (%E)
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test15
 Description
-= Tests sscanf with floats (exponential notation, uppercase)
+= Tests sprintf_s with exponential format doubles (uppercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test16.c
 **
-** Purpose: Test #16 for the sprintf function. Tests the decimal notation
+** Purpose: Test #16 for the sprintf_s function. Tests the decimal notation
 **          double specifier (%f)
 **
 **
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test16
 Description
-= Tests sprintf with decimal point format doubles
+= Tests sprintf_s with decimal point format doubles
@@ -6,7 +6,7 @@
 **
 ** Source:  test17.c
 **
-** Purpose: Test #17 for the sprintf function. Tests the lowercase
+** Purpose: Test #17 for the sprintf_s function. Tests the lowercase
 **          shorthand notation double specifier (%g)
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test17
 Description
-= Tests sscanf with floats (compact notation, uppercase)
+= Tests sprintf_s with compact format doubles (lowercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test18.c
 **
-** Purpose: Test #18 for the sprintf function. Tests the uppercase
+** Purpose: Test #18 for the sprintf_s function. Tests the uppercase
 **          shorthand notation double specifier (%G)
 **
 **
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test18
 Description
-= Tests sprintf with compact format doubles (uppercase)
+= Tests sprintf_s with compact format doubles (uppercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test19.c
 **
-** Purpose: Test #19 for the sprintf function. Tests the variable length
+** Purpose: Test #19 for the sprintf_s function. Tests the variable length
 **          precision argument.
 **
 **
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -33,13 +33,6 @@ int __cdecl main(int argc, char *argv[])
     DoArgumentPrecTest("%.*s", 2, (void*)"bar", "bar", "ba", "ba");
     DoArgumentPrecTest("%.*S", 2, (void*)convert("bar"), "bar", "ba", "ba");
 
-    DoArgumentPrecTest("%.*n", 3, (void*)&n, "pointer to int", "", "");
-    if (n != 0)
-    {
-        Fail("ERROR: Expected count parameter to resolve to %d, got %X\n",
-              0, n);
-    }
-
     DoArgumentPrecTest("%.*c", 0, (void*)'a', "a", "a", "a");
     DoArgumentPrecTest("%.*c", 4, (void*)'a', "a", "a", "a");
     DoArgumentPrecTest("%.*C", 0, (void*)'a', "a", "a", "a");
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test19
 Description
-= Tests sprintf with argument specified precision
+= Tests sprintf_s with argument specified precision
@@ -6,7 +6,7 @@
 **
 ** Source:  test2.c
 **
-** Purpose: Test #2 for the sprintf function. Tests the string specifier
+** Purpose: Test #2 for the sprintf_s function. Tests the string specifier
 **          (%s).
 **
 **
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test2
 Description
-= Tests sprintf with strings
+= Tests sprintf_s with strings
@@ -6,7 +6,7 @@
 **
 ** Source:  test3.c
 **
-** Purpose: Test #3 for the sprintf function. Tests the wide string
+** Purpose: Test #3 for the sprintf_s function. Tests the wide string
 **          specifier (%S).
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test3
 Description
-= Tests sscanf with bracketed set strings
+= Tests sprintf_s with wide strings
@@ -6,7 +6,7 @@
 **
 ** Source:  test4.c
 **
-** Purpose: Test #4 for the sprintf function. Tests the pointer
+** Purpose: Test #4 for the sprintf_s function. Tests the pointer
 **          specifier (%p).
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 /* 
  * Depends on memcmp and strlen
  */
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test4
 Description
-= Tests sscanf with decimal numbers
+= Tests sprintf_s with pointers
@@ -6,7 +6,7 @@
 **
 ** Source:  test6.c
 **
-** Purpose: Test #6 for the sprintf function. Tests the char specifier (%c).
+** Purpose: Test #6 for the sprintf_s function. Tests the char specifier (%c).
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test6
 Description
-= Tests sprintf with characters
+= Tests sprintf_s with characters
@@ -6,7 +6,7 @@
 **
 ** Source:  test7.c
 **
-** Purpose: Test #7 for the sprintf function. Tests the wide char
+** Purpose: Test #7 for the sprintf_s function. Tests the wide char
 **          specifier (%C).
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test7
 Description
-= Tests sprintf with wide characters
+= Tests sprintf_s with wide characters
@@ -6,7 +6,7 @@
 **
 ** Source:  test8.c
 **
-** Purpose: Test #8 for the sprintf function. Tests the decimal
+** Purpose: Test #8 for the sprintf_s function. Tests the decimal
 **          specifier (%d).
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test8
 Description
-= Tests sscanf with unsigned numbers
+= Tests sprintf_s with decimal numbers
@@ -6,7 +6,7 @@
 **
 ** Source:  test9.c
 **
-** Purpose: Test #9 for the sprintf function. Tests the integer
+** Purpose: Test #9 for the sprintf_s function. Tests the integer
 **          specifier (%i).
 **
 **
@@ -15,7 +15,7 @@
 
 
 #include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
 
 /* 
  * Depends on memcmp and strlen
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
 TYPE = DEFAULT
 EXE1 = test9
 Description
-= Tests sprintf with integer numbers
+= Tests sprintf_s with integer numbers
@@ -4,15 +4,15 @@
 
 /*============================================================================
 **
-** Source:  sscanf.h
+** Source:  sscanf_s.h
 **
-** Purpose: Contains common testing functions for sscanf.h
+** Purpose: Contains common testing functions for sscanf_s
 **
 **
 **==========================================================================*/
 
-#ifndef __SSCANF_H__
-#define __SSCANF_H__
+#ifndef __SSCANF_S_H__
+#define __SSCANF_S_H__
 
 void DoVoidTest(char *inputstr, const char *formatstr)
 {
@@ -20,10 +20,10 @@ void DoVoidTest(char *inputstr, const char *formatstr)
     int i;
     int ret;
 
-    ret = sscanf(inputstr, formatstr, buf);
+    ret = sscanf_s(inputstr, formatstr, buf);
     if (ret != 0)
     {
-        Fail("ERROR: Expected sscanf to return 0, got %d.\n"
+        Fail("ERROR: Expected sscanf_s to return 0, got %d.\n"
             "Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
     }
 
@@ -43,10 +43,10 @@ void DoStrTest(char *inputstr, const char *formatstr, const char *checkstr)
     char buf[256] = { 0 };
     int ret;
 
-    ret = sscanf(inputstr, formatstr, buf);
+    ret = sscanf_s(inputstr, formatstr, buf, _countof(buf));
     if (ret != 1)
     {
-        Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+        Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
             "Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
     }
 
@@ -64,10 +64,10 @@ void DoWStrTest(char *inputstr, const char *formatstr, const WCHAR *checkstr)
     WCHAR buf[256] = { 0 };
     int ret;
 
-    ret = sscanf(inputstr, formatstr, buf);
+    ret = sscanf_s(inputstr, formatstr, buf, _countof(buf));
     if (ret != 1)
     {
-        Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+        Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
             "Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
     }
 
@@ -85,10 +85,10 @@ void DoNumTest(char *inputstr, const char *formatstr, int checknum)
     int num;
     int ret;
 
-    ret = sscanf(inputstr, formatstr, &num);
+    ret = sscanf_s(inputstr, formatstr, &num);
     if (ret != 1)
     {
-        Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+        Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
             "Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
     }
 
@@ -104,10 +104,10 @@ void DoShortNumTest(char *inputstr, const char *formatstr, short checknum)
     short num;
     int ret;
 
-    ret = sscanf(inputstr, formatstr, &num);
+    ret = sscanf_s(inputstr, formatstr, &num);
     if (ret != 1)
     {
-        Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+        Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
             "Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
     }
 
@@ -125,17 +125,17 @@ void DoI64NumTest(char *inputstr, const char *formatstr, INT64 checknum)
     INT64 num;
     int ret;
 
-    ret = sscanf(inputstr, formatstr, &num);
+    ret = sscanf_s(inputstr, formatstr, &num);
     if (ret != 1)
     {
-        Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+        Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
             "Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
     }
 
     if (checknum != num)
     {
-        sprintf(buf, "%I64d", num);
-        sprintf(check, "%I64d", checknum);
+        sprintf_s(buf, _countof(buf), "%I64d", num);
+        sprintf_s(check, _countof(check), "%I64d", checknum);
         Fail("ERROR: scanned I64 number incorrectly from \"%s\" using \"%s\".\n"
             "Expected %s, got %s.\n", inputstr, formatstr, check, buf);
     }
@@ -150,10 +150,10 @@ void DoCharTest(char *inputstr, const char *formatstr, char* checkchars, int num
     for (i=0; i<256; i++)
         buf[i] = (char)-1;
 
-    ret = sscanf(inputstr, formatstr, buf);
+    ret = sscanf_s(inputstr, formatstr, buf, _countof(buf));
     if (ret != 1)
     {
-        Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+        Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
             "Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
     }
 
@@ -183,10 +183,10 @@ void DoWCharTest(char *inputstr, const char *formatstr, WCHAR* checkchars, int n
     for (i=0; i<256; i++)
         buf[i] = (WCHAR)-1;
 
-    ret = sscanf(inputstr, formatstr, buf);
+    ret = sscanf_s(inputstr, formatstr, buf, _countof(buf));
     if (ret != 1)
     {
-        Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+        Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
             "Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
     }
 
@@ -218,12 +218,12 @@ void DoFloatTest(char *inputstr, const char *formatstr, float checkval)
     for (i=0; i<256; i++)
         buf[i] = (char)-1;
 
-    ret = sscanf(inputstr, formatstr, buf);
+    ret = sscanf_s(inputstr, formatstr, buf);
     val = *(float*)buf;
 
     if (ret != 1)
     {
-        Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+        Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
             "Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
     }
 
@@ -6,7 +6,7 @@
 **
 ** Source:  test1.c
 **
-** Purpose: General test of sscanf
+** Purpose: General test of sscanf_s
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 
 int __cdecl main(int argc, char *argv[])
@@ -38,7 +38,7 @@ int __cdecl main(int argc, char *argv[])
     DoVoidTest("foo bar baz", "foo % bar %s");
     DoVoidTest("foo baz bar", "foo% baz %s");
 
-    ret = sscanf("foo bar baz", "foo bar %n", &num);
+    ret = sscanf_s("foo bar baz", "foo bar %n", &num);
     if (ret != 0 || num != 8)
     {
         Fail("ERROR: Got incorrect values in scanning \"%s\" using \"%s\".\n"
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test1
 Description
-= General test of sscanf
+= General test of sscanf_s
@@ -6,7 +6,7 @@
 **
 ** Source:  test10.c
 **
-** Purpose:  Tests sscanf with wide charactersn
+** Purpose:  Tests sscanf_s with wide characters
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test10
 Description
-= Tests sprintf with octal numbers
+= Tests sscanf_s with wide characters
@@ -6,7 +6,7 @@
 **
 ** Source:  test11.c
 **
-** Purpose: Tests sscanf with strings
+** Purpose: Tests sscanf_s with strings
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test11
 Description
-= Tests sscanf with strings
+= Tests sscanf_s with strings
@@ -6,7 +6,7 @@
 **
 ** Source:  test12.c
 **
-** Purpose:  Tests sscanf with wide strings
+** Purpose:  Tests sscanf_s with wide strings
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test12
 Description
-= Tests sscanf with wide strings
+= Tests sscanf_s with wide strings
@@ -6,7 +6,7 @@
 **
 ** Source:  test13.c
 **
-** Purpose: Tests sscanf with floats (decimal notation)
+** Purpose: Tests sscanf_s with floats (decimal notation)
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test13
 Description
-= Tests sprintf with hex numbers (uppercase)
+= Tests sscanf_s with floats (decimal notation)
@@ -6,7 +6,7 @@
 **
 ** Source:  test14.c
 **
-** Purpose: Tests sscanf with floats (exponential notation, lowercase)
+** Purpose: Tests sscanf_s with floats (exponential notation, lowercase)
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test14
 Description
-= Tests sprintf with exponential format doubles (lowercase)
+= Tests sscanf_s with floats (exponential notation, lowercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test15.c
 **
-** Purpose: Tests sscanf with floats (exponential notation, uppercase
+** Purpose: Tests sscanf_s with floats (exponential notation, uppercase
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test15
 Description
-= Tests sprintf with exponential format doubles (uppercase)
+= Tests sscanf_s with floats (exponential notation, uppercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test16.c
 **
-** Purpose:Tests sscanf with floats (compact notation, lowercase) 
+** Purpose:Tests sscanf_s with floats (compact notation, lowercase) 
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test16
 Description
-= Tests sscanf with floats (compact notation, lowercase)
+= Tests sscanf_s with floats (compact notation, lowercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test17.c
 **
-** Purpose: Tests sscanf with floats (compact notation, uppercase)
+** Purpose: Tests sscanf_s with floats (compact notation, uppercase)
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test17
 Description
-= Tests sprintf with compact format doubles (lowercase)
+= Tests sscanf_s with floats (compact notation, uppercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test2.c
 **
-** Purpose: Test to see if sscanf handles whitespace correctly
+** Purpose: Test to see if sscanf_s handles whitespace correctly
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 
 /* 
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test2
 Description
-= Test to see if sscanf handles whitespace correctly
+= Test to see if sscanf_s handles whitespace correctly
@@ -6,7 +6,7 @@
 **
 ** Source:  test3.c
 **
-** Purpose: Tests sscanf with bracketed set strings
+** Purpose: Tests sscanf_s with bracketed set strings
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test3
 Description
-= Tests sprintf with wide strings
+= Tests sscanf_s with bracketed set strings
@@ -6,7 +6,7 @@
 **
 ** Source:  test4.c
 **
-** Purpose: Tests sscanf with decimal numbers
+** Purpose: Tests sscanf_s with decimal numbers
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 
 int __cdecl main(int argc, char *argv[])
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test4
 Description
-= Tests sprintf with pointers
+= Tests sscanf_s with decimal numbers
@@ -6,7 +6,7 @@
 **
 ** Source:  test5.c
 **
-** Purpose: Tests sscanf with integer numbers
+** Purpose: Tests sscanf_s with integer numbers
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test5
 Description
-= Tests sscanf with integer numbers
+= Tests sscanf_s with integer numbers
@@ -6,7 +6,7 @@
 **
 ** Source:  test6.c
 **
-** Purpose: Tests sscanf with octal numbers
+** Purpose: Tests sscanf_s with octal numbers
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test6
 Description
-= Tests sscanf with octal numbers
+= Tests sscanf_s with octal numbers
@@ -6,7 +6,7 @@
 **
 ** Source:  test7.c
 **
-** Purpose:  Tests sscanf with hex numbers (lowercase)
+** Purpose:  Tests sscanf_s with hex numbers (lowercase)
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test7
 Description
-= Tests sscanf with hex numbers (lowercase)
+= Tests sscanf_s with hex numbers (lowercase)
@@ -6,7 +6,7 @@
 **
 ** Source:  test8.c
 **
-** Purpose:Tests sscanf with unsigned number 
+** Purpose:Tests sscanf_s with unsigned number 
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 int __cdecl main(int argc, char *argv[])
 {
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test8
 Description
-= Tests sprintf with decimal numbers
+= Tests sscanf_s with unsigned numbers
@@ -6,7 +6,7 @@
 **
 ** Source:  test9.c
 **
-** Purpose: Tests sscanf with characters
+** Purpose: Tests sscanf_s with characters
 **
 **
 **==========================================================================*/
@@ -14,7 +14,7 @@
 
 
 #include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
 
 
 int __cdecl main(int argc, char *argv[])
@@ -4,9 +4,9 @@
 
 Version = 1.0
 Section =C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
 TYPE = DEFAULT
 EXE1 = test9
 Description
-= Tests sscanf with characters
+= Tests sscanf_s with characters
index 6e40332..6349b7d 100644 (file)
@@ -145,8 +145,8 @@ void DoI64NumTest(WCHAR *inputstr, const WCHAR *formatstr, INT64 checknum)
 
     if (checknum != num)
     {
-        sprintf(buf, "%I64d", num);
-        sprintf(check, "%I64d", checknum);
+        sprintf_s(buf, _countof(buf), "%I64d", num);
+        sprintf_s(check, _countof(check), "%I64d", checknum);
         Fail("ERROR: scanned I64 number incorrectly from \"%s\" using \"%s\".\n"
             "Expected %s, got %s.\n", convertC(inputstr), 
             convertC(formatstr), check, buf);
index 789eebf..e9a79d3 100644 (file)
@@ -18,7 +18,7 @@
 #include <palsuite.h>
 
 /*
- * Notes: uses memcmp and the (pal) sprintf
+ * Notes: uses memcmp and the (pal) sprintf_s
  */
 
 int __cdecl main(int argc, char *argv[])
@@ -60,7 +60,7 @@ int __cdecl main(int argc, char *argv[])
 
     if (memcmp(dest, test, sizeof(test)) != 0)
     {
-        sprintf(buffer, "%S", dest);
+        sprintf_s(buffer, _countof(buffer), "%S", dest);
         Fail("ERROR: Expected wcscat to give \"%s\", got \"%s\"\n", 
             "foo bar baz", buffer);
     }
index 4e45c86..2ecafa8 100644 (file)
@@ -15,7 +15,7 @@
 #include <palsuite.h>
 
 /*
- * Notes: uses memcmp and sprintf.
+ * Notes: uses memcmp and sprintf_s.
  */
 
 int __cdecl main(int argc, char *argv[])
@@ -37,7 +37,7 @@ int __cdecl main(int argc, char *argv[])
     
     if (ret != dest || memcmp(dest, result, sizeof(result)) != 0)
     {
-        sprintf(buffer, "%S", dest);
+        sprintf_s(buffer, _countof(buffer), "%S", dest);
         Fail("Expected wcscpy to give \"%s\" with a return value of %p, got \"%s\" "
             "with a return value of %p.\n", "foo", dest, buffer, ret);
     }
index 459a730..b77ca2e 100644 (file)
@@ -133,7 +133,7 @@ inline ULONG   VAL32(ULONG x)
 #define th_htons(w)  (((w) >> 8) | ((w) << 8))
 #endif  // BIGENDIAN
 
-
+#define _countof(_array) (sizeof(_array)/sizeof(_array[0]))
 
 WCHAR* convert(const char * aString) 
 {
index 060945f..f390c10 100644 (file)
@@ -67,7 +67,7 @@ int __cdecl main(int argc, char *argv[])
     ResetEvent(hEvFromHelper);
     ResetEvent(hEvToHelper);
     
-    if (!sprintf(cmdComposeBuf, "helper %s", commsFileName)) 
+    if (!sprintf_s(cmdComposeBuf, _countof(cmdComposeBuf), "helper %s", commsFileName)) 
     {
         Fail("Could not convert command line\n");
     }
index e0218f3..15b4b3f 100644 (file)
@@ -67,7 +67,7 @@ int __cdecl main(int argc, char *argv[])
              "(already exists!)\n", szcFromHelperEvName);
     }
     
-    if (!sprintf(cmdComposeBuf, "helper %s", commsFileName)) 
+    if (!sprintf_s(cmdComposeBuf, _countof(cmdComposeBuf), "helper %s", commsFileName)) 
     {
         Fail("Could not convert command line\n");
     }
index 2bb441e..4082d38 100644 (file)
@@ -254,7 +254,7 @@ int __cdecl main(int argc, char *argv[])
 
     /* directories with dots  */
     memset(szDirName, 0, buf_size);
-    sprintf(szDirName, szDotDir);
+    sprintf_s(szDirName, _countof(szDirName), szDotDir);
     bRc = CreateDirectoryA(szDirName, NULL);
     if (bRc == FALSE)
     {
index 9b020cc..bbaedda 100644 (file)
@@ -289,7 +289,7 @@ int __cdecl main(int argc, char *argv[])
 
     /* directories with dots */
     memset(szDirName, 0, 252);
-    sprintf(szDirName, ".dotDirectory");
+    sprintf_s(szDirName, _countof(szDirName), ".dotDirectory");
     pTemp = convert(szDirName);
     bRc = CreateDirectoryW(pTemp, NULL);
     if (bRc == FALSE)
index a70867a..f98fc5b 100644 (file)
@@ -21,7 +21,7 @@ BOOL Cleanup(void)
 
     // loop through all accesses, modes, dispositions and flags
     for (i=0; i<4*8*4*5; ++i) {
-        sprintf(FileName, "test%03d.txt", i);
+        sprintf_s(FileName, _countof(FileName), "test%03d.txt", i);
        if (DeleteFileA(FileName) == FALSE) {
            if (GetLastError() != ERROR_FILE_NOT_FOUND) {
                bRet = FALSE;
@@ -98,7 +98,7 @@ int __cdecl main(int argc, char *argv[])
                 // creation disp loop
                 for (l = 0; l < 5; l++)
                 {
-                    sprintf(lpFileName, "test%03d.txt", nCounter);
+                    sprintf_s(lpFileName, _countof(lpFileName), "test%03d.txt", nCounter);
                     hFile = CreateFile(lpFileName,
                         dwDesiredAccess[i],
                         dwShareMode[j],
index 4d7d20a..0619f5b 100644 (file)
@@ -21,7 +21,7 @@ BOOL Cleanup(void)
 
     // loop through all accesses, modes, dispositions and flags
     for (i=0; i<4*8*4*5; ++i) {
-        sprintf(FileName, "test%03d.txt", i);
+        sprintf_s(FileName, _countof(FileName), "test%03d.txt", i);
        if (DeleteFileA(FileName) == FALSE) {
            if (GetLastError() != ERROR_FILE_NOT_FOUND) {
                bRet = FALSE;
@@ -99,7 +99,7 @@ int __cdecl main(int argc, char *argv[])
                 // creation disp loop
                 for (l = 0; l < 5; l++)
                 {
-                    sprintf(string, "test%03d.txt", nCounter);
+                    sprintf_s(string, _countof(string), "test%03d.txt", nCounter);
                     lpFileName = convert(string);
                     hFile = CreateFileW(lpFileName,
                                         dwDesiredAccess[i],
index 8ede8ba..bea8e27 100644 (file)
@@ -104,7 +104,7 @@ int __cdecl main(int argc, char *argv[])
         }
 
         /* now verify that it only used the first 3 characters of the prefix */
-        sprintf(szTempString, "%s\\%s", szDot, szLongValidPrefix);
+        sprintf_s(szTempString, _countof(szTempString), "%s\\%s", szDot, szLongValidPrefix);
         if (strncmp(szTempString, szReturnedName, 6) == 0)
         {
             Fail("GetTempFileNameA: ERROR -> It appears that an improper prefix "
index 8d1bc0e..6d1337a 100644 (file)
@@ -56,7 +56,7 @@ int createExisting(void)
     }
 
     memset(szBuffer, 0, 100);
-    sprintf(szBuffer, "%s/test01.txt", lpSource[2]);
+    sprintf_s(szBuffer, _countof(szBuffer), "%s/test01.txt", lpSource[2]);
     tempFile = fopen(szBuffer, "w");
     if (tempFile != NULL)
     {
@@ -70,7 +70,7 @@ int createExisting(void)
     }
 
     memset(szBuffer, 0, 100);
-    sprintf(szBuffer, "%s/test02.txt", lpSource[2]);
+    sprintf_s(szBuffer, _countof(szBuffer), "%s/test02.txt", lpSource[2]);
     tempFile = fopen(szBuffer, "w");
     if (tempFile != NULL)
     {
@@ -184,10 +184,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpSource[2]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpSource[2]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[2]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpSource[2]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[2]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpSource[2], 103);
     }
@@ -200,10 +200,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpSource[3]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpSource[3]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[3]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpSource[3]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[3]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpSource[3], 103);
     }
@@ -216,10 +216,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpDestination[0]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpDestination[0]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[0]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpDestination[0]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[0]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpDestination[0], 103);
     }
@@ -231,10 +231,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpDestination[1]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpDestination[1]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[1]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpDestination[1]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[1]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpDestination[1], 103);
     }
@@ -246,10 +246,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpDestination[2]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpDestination[2]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[2]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpDestination[2]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[2]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpDestination[2], 103);
     }
@@ -261,10 +261,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpDestination[3]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpDestination[3]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[3]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpDestination[3]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[3]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpDestination[3], 103);
     }
index 5899930..8a7fae5 100644 (file)
@@ -59,7 +59,7 @@ int createExisting(void)
     }
 
     memset(szBuffer, 0, 100);
-    sprintf(szBuffer, "%s/test01.txt", lpSource[2]);
+    sprintf_s(szBuffer, _countof(szBuffer), "%s/test01.txt", lpSource[2]);
     tempFile = fopen(szBuffer, "w");
     if (tempFile != NULL)
     {
@@ -73,7 +73,7 @@ int createExisting(void)
     }
 
     memset(szBuffer, 0, 100);
-    sprintf(szBuffer, "%s/test02.txt", lpSource[2]);
+    sprintf_s(szBuffer, _countof(szBuffer), "%s/test02.txt", lpSource[2]);
     tempFile = fopen(szBuffer, "w");
     if (tempFile != NULL)
     {
@@ -186,10 +186,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpSource[2]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpSource[2]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[2]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpSource[2]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[2]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpSource[2], 103);
     }
@@ -202,10 +202,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpSource[3]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpSource[3]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[3]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpSource[3]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[3]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpSource[3], 103);
     }
@@ -218,10 +218,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpDestination[0]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpDestination[0]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[0]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpDestination[0]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[0]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpDestination[0], 103);
     }
@@ -233,10 +233,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpDestination[1]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpDestination[1]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[1]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpDestination[1]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[1]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpDestination[1], 103);
     }
@@ -248,10 +248,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpDestination[2]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpDestination[2]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[2]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpDestination[2]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[2]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpDestination[2], 103);
     }
@@ -263,10 +263,10 @@ void removeAll(void)
     dwAtt = GetFileAttributesA(lpDestination[3]);
     if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
     {
-        sprintf(szTemp, "%s/test01.txt", lpDestination[3]);
+        sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[3]);
         removeFileHelper(szTemp, 18);
     
-        sprintf(szTemp, "%s/test02.txt", lpDestination[3]);    
+        sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[3]);    
         removeFileHelper(szTemp, 19);
         removeDirectoryHelper(lpDestination[3], 103);
     }
index 167af58..4eb53d0 100644 (file)
@@ -48,7 +48,7 @@ int __cdecl main(int argc, char *argv[])
      * remove a directory that does not exist 
      */
     szTemp = (char *) malloc (sizeof("test_directory"));
-    sprintf(szTemp, "test_directory");
+    sprintf_s(szTemp, sizeof("test_directory"), "test_directory");
     bRc = RemoveDirectoryA(szTemp);
     if (bRc != FALSE)
     {
@@ -69,7 +69,7 @@ int __cdecl main(int argc, char *argv[])
     }
 
     char *szSymlinkName = (char *) malloc (sizeof("test_directory_symlink"));
-    sprintf(szSymlinkName, "test_directory_symlink");
+    sprintf_s(szSymlinkName, sizeof("test_directory_symlink"), "test_directory_symlink");
     if (symlink(szTemp, szSymlinkName) != 0)
     {
         Fail("Error:RemoveDirectoryA: Failed to create a symlink to the directory \"test_directory\".\n");
@@ -140,7 +140,7 @@ int __cdecl main(int argc, char *argv[])
      * directories with dots 
      */
     memset(szDirName, 0, 252);
-    sprintf(szDirName, ".dotDirectory");
+    sprintf_s(szDirName, _countof(szDirName), ".dotDirectory");
     szTemp = (char *) malloc (sizeof(szDirName));
     szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);
 
@@ -170,7 +170,7 @@ int __cdecl main(int argc, char *argv[])
      * Try calling RemoveDirectory with a file name
      */
     memset(szDirName, 0, 252);
-    sprintf(szDirName, "removedirectoryw.c");
+    sprintf_s(szDirName, _countof(szDirName), "removedirectoryw.c");
     szTemp = (char *) malloc (sizeof(szDirName));
     szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);
 
@@ -201,7 +201,7 @@ int __cdecl main(int argc, char *argv[])
     }
 
     /* Create non_empty_dir */
-    sprintf( szDirName, "non_empty_dir");
+    sprintf_s(szDirName, _countof(szDirName), "non_empty_dir");
     szTemp = (char *) malloc (sizeof(szDirName));
     szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);
     bRc = CreateDirectoryA(szTemp, NULL);
@@ -229,7 +229,7 @@ int __cdecl main(int argc, char *argv[])
     }
 
     /* Create sub_dir */
-    sprintf (szDirName, "sub_dir");
+    sprintf_s(szDirName, _countof(szDirName), "sub_dir");
     szTemp2 = (char *) malloc (sizeof(szDirName));
     szTemp2 = strncpy(szTemp2, szDirName, strlen(szDirName) + 1);
     bRc = CreateDirectoryA(szTemp2, NULL);
index ae1dd0f..ec90528 100644 (file)
@@ -114,7 +114,7 @@ int __cdecl main(int argc, char *argv[])
      * directories with dots 
      */
     memset(szDirName, 0, 252);
-    sprintf(szDirName, ".dotDirectory");
+    sprintf_s(szDirName, _countof(szDirName), ".dotDirectory");
     szwTemp = convert(szDirName);
     bRc = CreateDirectoryW(szwTemp, NULL);
     if (bRc == FALSE)
@@ -142,7 +142,7 @@ int __cdecl main(int argc, char *argv[])
      * Try calling RemoveDirectory with a file name
      */
     memset(szDirName, 0, 252);
-    sprintf(szDirName, "removedirectoryw.c");
+    sprintf_s(szDirName, _countof(szDirName), "removedirectoryw.c");
     szwTemp = convert(szDirName);
 
     bRc = RemoveDirectoryW(szwTemp);
index 8422683..57afdef 100644 (file)
@@ -90,7 +90,7 @@ int __cdecl main(int argc, char *argv[]) {
     }
 
     memset(fileloc, 0, _MAX_PATH);
-    sprintf(fileloc, "%s%s", fullPath, szFileNameExistsWithExt);
+    sprintf_s(fileloc, _countof(fileloc), "%s%s", fullPath, szFileNameExistsWithExt);
 
     RemoveAll();
 
index 1c8adba..6880a86 100644 (file)
@@ -133,7 +133,7 @@ int __cdecl main(int argc, char *argv[]) {
     }
 
     memset(fileloc, 0, _MAX_PATH);
-    sprintf(fileloc, "%s%s", fullPath, szFileNameExistsWithExt);
+    sprintf_s(fileloc, _countof(fileloc), "%s%s", fullPath, szFileNameExistsWithExt);
 
     RemoveAll();
 
index c07a624..f227aa3 100644 (file)
@@ -118,9 +118,9 @@ int __cdecl main(int argc, char *argv[])
     /* append the temp name to the "home" directory */
     memset(szBuiltDir, 0, (_MAX_DIR+1));
 #if WIN32
-    sprintf(szBuiltDir,"%s%s\\", szHomeDir, szDirName);
+    sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s%s\\", szHomeDir, szDirName);
 #else
-    sprintf(szBuiltDir,"%s%s/", szHomeDir, szDirName);
+    sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s%s/", szHomeDir, szDirName);
 #endif
 
     /* get the new current directory */
index 415dbbf..4b1c1c8 100644 (file)
@@ -62,9 +62,9 @@ int __cdecl main(int argc, char *argv[])
      /* append the temp name to the "home" directory */
     memset(szBuiltDir, 0, (_MAX_DIR+1));
 #if WIN32
-    sprintf(szBuiltDir,"%s\\..\\", szDirName);
+    sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s\\..\\", szDirName);
 #else
-    sprintf(szBuiltDir,"%s/../", szDirName);
+    sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s/../", szDirName);
 #endif
 
 
index 7e3d7b7..7f833ba 100644 (file)
@@ -63,9 +63,9 @@ int __cdecl main(int argc, char *argv[])
      /* append the temp name to the "home" directory */
     memset(szBuiltDir, 0, MAX_PATH);
 #if WIN32
-    sprintf(szBuiltDir,"%s\\..\\", szDirName);
+    sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s\\..\\", szDirName);
 #else
-    sprintf(szBuiltDir,"%s/../", szDirName);
+    sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s/../", szDirName);
 #endif
 
     szwBuiltDir = convert(szBuiltDir);
index 11ff967..5cc6d77 100644 (file)
@@ -34,9 +34,9 @@ int __cdecl main(int argc, char *argv[])
     }
 
 #if WIN32
-    sprintf(executableFileName,"%s","executable.exe");
+    sprintf_s(executableFileName, _countof(executableFileName),"%s","executable.exe");
 #else
-    sprintf(executableFileName,"%s","executable");
+    sprintf_s(executableFileName, _countof(executableFileName),"%s","executable");
 #endif
 
     //conver string to a unicode one
index 91172be..3aea80e 100644 (file)
@@ -73,7 +73,7 @@ int __cdecl main(int argc, char *argv[])
     ResetEvent(hEvFromHelper);
     ResetEvent(hEvToHelper);
     
-    if (!sprintf(cmdComposeBuf, "helper %s", commsFileName)) 
+    if (!sprintf_s(cmdComposeBuf, _countof(cmdComposeBuf), "helper %s", commsFileName)) 
     {
         Fail("Could not convert command line\n");
     }
@@ -138,7 +138,7 @@ int __cdecl main(int argc, char *argv[])
                   errno, GetLastError());
         }
         PEDANTIC1(fclose,(commsFile));
-        sscanf(incomingCMDBuffer, LLFORMAT " " LLFORMAT, &pDestMemory, &Count);
+        sscanf_s(incomingCMDBuffer, LLFORMAT " " LLFORMAT, &pDestMemory, &Count);
         if (argc > 1) 
         {
             Trace("Preparing to write to " LLFORMAT " bytes @ " LLFORMAT "('%s')\n", 
index d1e6b6d..ab38d1a 100644 (file)
@@ -31,10 +31,10 @@ int __cdecl main(int argc, char *argv[])
 
     /*Module name without extension but with a trailing dot*/
 #if WIN32
-    sprintf(ModuleName, "%s", "rotor_pal.");
+    sprintf_s(ModuleName, _countof(ModuleName), "%s", "rotor_pal.");
 #else
     /* Under FreeBSD */
-    sprintf(ModuleName, "%s", "librotor_pal.");
+    sprintf_s(ModuleName, _countof(ModuleName), "%s", "librotor_pal.");
 #endif
 
     /* load a module which does not have the file extension, 
index acaa200..6d92f02 100644 (file)
@@ -33,9 +33,9 @@ int __cdecl main(int argc, char *argv[])
 
     /*Module name without extension but with a trailing dot*/
 #if WIN32
-    sprintf(ModuleName,"%s","rotor_pal.");
+    sprintf_s(ModuleName, _countof(ModuleName),"%s","rotor_pal.");
 #else
-    sprintf(ModuleName,"%s","librotor_pal.");
+    sprintf_s(ModuleName, _countof(ModuleName),"%s","librotor_pal.");
 #endif
 
     /* convert a normal string to a wide one */
index ff0d338..8eb8776 100644 (file)
@@ -33,7 +33,7 @@ int __cdecl main(int argc, char *argv[])
 
     /*zero the buffer*/
     memset(ModuleName,0,64);
-    sprintf(ModuleName, "%s", "rotor_pal");
+    sprintf_s(ModuleName, _countof(ModuleName), "%s", "rotor_pal");
 
     /*convert a normal string to a wide one*/
     wpModuleName = convert(ModuleName);
index a15ff57..c6fa4ad 100644 (file)
@@ -30,7 +30,7 @@ int __cdecl main(int argc, char *argv[])
     }
 
     memset(ModuleName, 0, 64);
-    sprintf(ModuleName, "%s", "not_exist_module_name");
+    sprintf_s(ModuleName, _countof(ModuleName), "%s", "not_exist_module_name");
 
     /*convert a normal string to a wide one*/
     wpModuleName = convert(ModuleName);
index d9af111..a5e241d 100644 (file)
@@ -143,44 +143,43 @@ c_runtime/sin/test1/paltest_sin_test1
 c_runtime/sinf/test1/paltest_sinf_test1
 c_runtime/sinh/test1/paltest_sinh_test1
 c_runtime/sinhf/test1/paltest_sinhf_test1
-c_runtime/sprintf/test1/paltest_sprintf_test1
-c_runtime/sprintf/test10/paltest_sprintf_test10
-c_runtime/sprintf/test11/paltest_sprintf_test11
-c_runtime/sprintf/test12/paltest_sprintf_test12
-c_runtime/sprintf/test13/paltest_sprintf_test13
-c_runtime/sprintf/test14/paltest_sprintf_test14
-c_runtime/sprintf/test15/paltest_sprintf_test15
-c_runtime/sprintf/test16/paltest_sprintf_test16
-c_runtime/sprintf/test17/paltest_sprintf_test17
-c_runtime/sprintf/test18/paltest_sprintf_test18
-c_runtime/sprintf/test19/paltest_sprintf_test19
-c_runtime/sprintf/test2/paltest_sprintf_test2
-c_runtime/sprintf/test3/paltest_sprintf_test3
-c_runtime/sprintf/test4/paltest_sprintf_test4
-c_runtime/sprintf/test5/paltest_sprintf_test5
-c_runtime/sprintf/test6/paltest_sprintf_test6
-c_runtime/sprintf/test7/paltest_sprintf_test7
-c_runtime/sprintf/test8/paltest_sprintf_test8
-c_runtime/sprintf/test9/paltest_sprintf_test9
+c_runtime/sprintf_s/test1/paltest_sprintf_test1
+c_runtime/sprintf_s/test10/paltest_sprintf_test10
+c_runtime/sprintf_s/test11/paltest_sprintf_test11
+c_runtime/sprintf_s/test12/paltest_sprintf_test12
+c_runtime/sprintf_s/test13/paltest_sprintf_test13
+c_runtime/sprintf_s/test14/paltest_sprintf_test14
+c_runtime/sprintf_s/test15/paltest_sprintf_test15
+c_runtime/sprintf_s/test16/paltest_sprintf_test16
+c_runtime/sprintf_s/test17/paltest_sprintf_test17
+c_runtime/sprintf_s/test18/paltest_sprintf_test18
+c_runtime/sprintf_s/test19/paltest_sprintf_test19
+c_runtime/sprintf_s/test2/paltest_sprintf_test2
+c_runtime/sprintf_s/test3/paltest_sprintf_test3
+c_runtime/sprintf_s/test4/paltest_sprintf_test4
+c_runtime/sprintf_s/test6/paltest_sprintf_test6
+c_runtime/sprintf_s/test7/paltest_sprintf_test7
+c_runtime/sprintf_s/test8/paltest_sprintf_test8
+c_runtime/sprintf_s/test9/paltest_sprintf_test9
 c_runtime/sqrt/test1/paltest_sqrt_test1
 c_runtime/sqrtf/test1/paltest_sqrtf_test1
-c_runtime/sscanf/test1/paltest_sscanf_test1
-c_runtime/sscanf/test10/paltest_sscanf_test10
-c_runtime/sscanf/test11/paltest_sscanf_test11
-c_runtime/sscanf/test12/paltest_sscanf_test12
-c_runtime/sscanf/test13/paltest_sscanf_test13
-c_runtime/sscanf/test14/paltest_sscanf_test14
-c_runtime/sscanf/test15/paltest_sscanf_test15
-c_runtime/sscanf/test16/paltest_sscanf_test16
-c_runtime/sscanf/test17/paltest_sscanf_test17
-c_runtime/sscanf/test2/paltest_sscanf_test2
-c_runtime/sscanf/test3/paltest_sscanf_test3
-c_runtime/sscanf/test4/paltest_sscanf_test4
-c_runtime/sscanf/test5/paltest_sscanf_test5
-c_runtime/sscanf/test6/paltest_sscanf_test6
-c_runtime/sscanf/test7/paltest_sscanf_test7
-c_runtime/sscanf/test8/paltest_sscanf_test8
-c_runtime/sscanf/test9/paltest_sscanf_test9
+c_runtime/sscanf_s/test1/paltest_sscanf_test1
+c_runtime/sscanf_s/test10/paltest_sscanf_test10
+c_runtime/sscanf_s/test11/paltest_sscanf_test11
+c_runtime/sscanf_s/test12/paltest_sscanf_test12
+c_runtime/sscanf_s/test13/paltest_sscanf_test13
+c_runtime/sscanf_s/test14/paltest_sscanf_test14
+c_runtime/sscanf_s/test15/paltest_sscanf_test15
+c_runtime/sscanf_s/test16/paltest_sscanf_test16
+c_runtime/sscanf_s/test17/paltest_sscanf_test17
+c_runtime/sscanf_s/test2/paltest_sscanf_test2
+c_runtime/sscanf_s/test3/paltest_sscanf_test3
+c_runtime/sscanf_s/test4/paltest_sscanf_test4
+c_runtime/sscanf_s/test5/paltest_sscanf_test5
+c_runtime/sscanf_s/test6/paltest_sscanf_test6
+c_runtime/sscanf_s/test7/paltest_sscanf_test7
+c_runtime/sscanf_s/test8/paltest_sscanf_test8
+c_runtime/sscanf_s/test9/paltest_sscanf_test9
 c_runtime/strcat/test1/paltest_strcat_test1
 c_runtime/strchr/test1/paltest_strchr_test1
 c_runtime/strcmp/test1/paltest_strcmp_test1
index e7bfd60..d6e113b 100644 (file)
@@ -271,44 +271,43 @@ c_runtime/sin/test1,1
 c_runtime/sinf/test1,1
 c_runtime/sinh/test1,1
 c_runtime/sinhf/test1,1
-c_runtime/sprintf/test1,1
-c_runtime/sprintf/test2,1
-c_runtime/sprintf/test3,1
-c_runtime/sprintf/test4,1
-c_runtime/sprintf/test5,1
-c_runtime/sprintf/test6,1
-c_runtime/sprintf/test7,1
-c_runtime/sprintf/test8,1
-c_runtime/sprintf/test9,1
-c_runtime/sprintf/test10,1
-c_runtime/sprintf/test11,1
-c_runtime/sprintf/test12,1
-c_runtime/sprintf/test13,1
-c_runtime/sprintf/test14,1
-c_runtime/sprintf/test15,1
-c_runtime/sprintf/test16,1
-c_runtime/sprintf/test17,1
-c_runtime/sprintf/test18,1
-c_runtime/sprintf/test19,1
+c_runtime/sprintf_s/test1,1
+c_runtime/sprintf_s/test2,1
+c_runtime/sprintf_s/test3,1
+c_runtime/sprintf_s/test4,1
+c_runtime/sprintf_s/test6,1
+c_runtime/sprintf_s/test7,1
+c_runtime/sprintf_s/test8,1
+c_runtime/sprintf_s/test9,1
+c_runtime/sprintf_s/test10,1
+c_runtime/sprintf_s/test11,1
+c_runtime/sprintf_s/test12,1
+c_runtime/sprintf_s/test13,1
+c_runtime/sprintf_s/test14,1
+c_runtime/sprintf_s/test15,1
+c_runtime/sprintf_s/test16,1
+c_runtime/sprintf_s/test17,1
+c_runtime/sprintf_s/test18,1
+c_runtime/sprintf_s/test19,1
 c_runtime/sqrt/test1,1
 c_runtime/sqrtf/test1,1
-c_runtime/sscanf/test1,1
-c_runtime/sscanf/test2,1
-c_runtime/sscanf/test3,1
-c_runtime/sscanf/test4,1
-c_runtime/sscanf/test5,1
-c_runtime/sscanf/test6,1
-c_runtime/sscanf/test7,1
-c_runtime/sscanf/test8,1
-c_runtime/sscanf/test9,1
-c_runtime/sscanf/test10,1
-c_runtime/sscanf/test11,1
-c_runtime/sscanf/test12,1
-c_runtime/sscanf/test13,1
-c_runtime/sscanf/test14,1
-c_runtime/sscanf/test15,1
-c_runtime/sscanf/test16,1
-c_runtime/sscanf/test17,1
+c_runtime/sscanf_s/test1,1
+c_runtime/sscanf_s/test2,1
+c_runtime/sscanf_s/test3,1
+c_runtime/sscanf_s/test4,1
+c_runtime/sscanf_s/test5,1
+c_runtime/sscanf_s/test6,1
+c_runtime/sscanf_s/test7,1
+c_runtime/sscanf_s/test8,1
+c_runtime/sscanf_s/test9,1
+c_runtime/sscanf_s/test10,1
+c_runtime/sscanf_s/test11,1
+c_runtime/sscanf_s/test12,1
+c_runtime/sscanf_s/test13,1
+c_runtime/sscanf_s/test14,1
+c_runtime/sscanf_s/test15,1
+c_runtime/sscanf_s/test16,1
+c_runtime/sscanf_s/test17,1
 c_runtime/strcat/test1,1
 c_runtime/strchr/test1,1
 c_runtime/strcmp/test1,1
index 960bcf5..a3e66e6 100644 (file)
@@ -122,20 +122,21 @@ void PrintUsageHelper()
        W("    /in <file>           - Specifies input filename (optional)\n")
        W("    /out <file>          - Specifies output filename (optional)\n")
 #ifdef FEATURE_CORECLR
-       W("    /Trusted_Platform_Assemblies <path[;path]>\n")
+       W("    /Trusted_Platform_Assemblies <path[") PATH_SEPARATOR_STR_W W("path]>\n")
        W("                         - List of assemblies treated as trusted platform\n")
        W("                         - Cannot be used with Platform_Assemblies_Paths\n")
-       W("    /Platform_Resource_Roots <path[;path]>\n")
+       W("    /Platform_Resource_Roots <path[") PATH_SEPARATOR_STR_W W("path]>\n")
        W("                         - List of paths containing localized assembly directories\n")
-       W("    /App_Paths <path>    - List of paths containing user-application assemblies and resources\n")
+       W("    /App_Paths <path[") PATH_SEPARATOR_STR_W W("path]>\n")
+       W("                         - List of paths containing user-application assemblies and resources\n")
 #ifndef NO_NGENPDB
-       W("    /App_Ni_Paths <path[;path]>\n")
+       W("    /App_Ni_Paths <path[") PATH_SEPARATOR_STR_W W("path]>\n")
        W("                         - List of paths containing user-application native images\n")
        W("                         - Must be used with /CreatePDB switch\n")
 #endif // NO_NGENPDB
 #endif // FEATURE_CORECLR
 
-       W("    /Platform_Assemblies_Paths\n")
+       W("    /Platform_Assemblies_Paths <path[") PATH_SEPARATOR_STR_W W("path]>\n")
        W("                         - List of paths containing target platform assemblies\n")
 #ifdef FEATURE_CORECLR
        // If Platform_Assemblies_Paths, we will use it to build the TPA list and thus,
@@ -144,7 +145,7 @@ void PrintUsageHelper()
 #endif // FEATURE_CORECLR
        
 #ifdef FEATURE_COMINTEROP
-       W("    /Platform_Winmd_Paths\n")
+       W("    /Platform_Winmd_Paths <path[") PATH_SEPARATOR_STR_W W("path]>\n")
        W("                         - List of paths containing target platform WinMDs used\n")
        W("                           for emulating RoResolveNamespace\n")
 #endif
@@ -156,7 +157,7 @@ void PrintUsageHelper()
        W("                           scenario traces, which can be used with ibcmerge.exe\n")
 #endif
 #if defined(FEATURE_CORECLR) && !defined(FEATURE_MERGE_JIT_AND_ENGINE)
-       W("    /JITPath\n")
+       W("    /JITPath <path>\n")
        W("                         - Specifies the absolute file path to JIT compiler to be used.\n")
 #endif // defined(FEATURE_CORECLR) && !defined(FEATURE_MERGE_JIT_AND_ENGINE)
 #ifdef FEATURE_READYTORUN_COMPILER
index c61ba34..0c7966b 100644 (file)
@@ -379,6 +379,7 @@ else(WIN32)
         set(VM_SOURCES_WKS_ARCH_ASM
             ${ARCH_SOURCES_DIR}/asmhelpers.S
             ${ARCH_SOURCES_DIR}/gmsasm.S
+            ${ARCH_SOURCES_DIR}/umthunkstub.S
         )
     elseif(CLR_CMAKE_TARGET_ARCH_ARM)
         set(VM_SOURCES_WKS_ARCH_ASM
index b7fc67c..34da344 100644 (file)
@@ -11144,14 +11144,14 @@ void AppDomain::Unload(BOOL fForceUnload)
     if (takeSnapShot)
     {
         char buffer[1024];
-        sprintf(buffer, "vadump -p %d -o > vadump.%d", GetCurrentProcessId(), unloadCount);
+        sprintf_s(buffer, _countof(buffer), "vadump -p %d -o > vadump.%d", GetCurrentProcessId(), unloadCount);
         system(buffer);
-        sprintf(buffer, "umdh -p:%d -d -i:1 -f:umdh.%d", GetCurrentProcessId(), unloadCount);
+        sprintf_s(buffer, _countof(buffer), "umdh -p:%d -d -i:1 -f:umdh.%d", GetCurrentProcessId(), unloadCount);
         system(buffer);
         int takeDHSnapShot = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADTakeDHSnapShot);
         if (takeDHSnapShot)
         {
-            sprintf(buffer, "dh -p %d -s -g -h -b -f dh.%d", GetCurrentProcessId(), unloadCount);
+            sprintf_s(buffer, _countof(buffer), "dh -p %d -s -g -h -b -f dh.%d", GetCurrentProcessId(), unloadCount);
             system(buffer);
         }
     }
index fb5c087..4dd1ee4 100644 (file)
@@ -105,6 +105,7 @@ inline void GetSpecificCpuInfo(CORINFO_CPU * cpuInfo)
 
 #if (defined(_TARGET_X86_) || defined(_TARGET_AMD64_)) && !defined(CROSSGEN_COMPILE)
 extern "C" DWORD __stdcall getcpuid(DWORD arg, unsigned char result[16]);
+extern "C" DWORD __stdcall xmmYmmStateSupport();
 #endif
 
 inline bool TargetHasAVXSupport()
index 74fde49..a73cb53 100644 (file)
@@ -1216,8 +1216,6 @@ EEJitManager::EEJitManager()
 }
 
 #if defined(_TARGET_X86_) || defined(_TARGET_AMD64_)
-extern "C" DWORD __stdcall getcpuid(DWORD arg, unsigned char result[16]);
-extern "C" DWORD __stdcall xmmYmmStateSupport();
 
 bool DoesOSSupportAVX()
 {
index 4e3523e..0246611 100644 (file)
@@ -1249,7 +1249,7 @@ PCODE COMDelegate::ConvertToCallback(MethodDesc* pMD)
     // Get UMEntryThunk from appdomain thunkcache cache.
     UMEntryThunk *pUMEntryThunk = GetAppDomain()->GetUMEntryThunkCache()->GetUMEntryThunk(pMD);
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
 
     // System.Runtime.InteropServices.NativeCallableAttribute
     BYTE* pData = NULL;
@@ -1281,7 +1281,7 @@ PCODE COMDelegate::ConvertToCallback(MethodDesc* pMD)
             pUMThunkMarshalInfo->SetCallingConvention(callConv);
         }
 }
-#endif  //_TARGET_X86_
+#endif  //_TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
     pCode = (PCODE)pUMEntryThunk->GetCode();
     _ASSERTE(pCode != NULL);
index 0d2cac5..6535a80 100644 (file)
@@ -74,3 +74,24 @@ FCIMPL3(VOID, DependentHandle::nGetPrimaryAndSecondary, OBJECTHANDLE handle, Obj
 }
 FCIMPLEND
 
+FCIMPL2(VOID, DependentHandle::nSetPrimary, OBJECTHANDLE handle, Object *_primary)
+{
+    FCALL_CONTRACT;
+
+    _ASSERTE(handle != NULL);
+
+    OBJECTREF primary(_primary);
+    StoreObjectInHandle(handle, primary);
+}
+FCIMPLEND
+
+FCIMPL2(VOID, DependentHandle::nSetSecondary, OBJECTHANDLE handle, Object *_secondary)
+{
+    FCALL_CONTRACT;
+
+    _ASSERTE(handle != NULL);
+
+    OBJECTREF secondary(_secondary);
+    SetDependentHandleSecondary(handle, secondary);
+}
+FCIMPLEND
index 7cf5a1e..7192a4b 100644 (file)
@@ -45,6 +45,8 @@ public:
     static FCDECL2(VOID,   nGetPrimary, OBJECTHANDLE handle, Object **outPrimary);
     static FCDECL3(VOID,   nGetPrimaryAndSecondary, OBJECTHANDLE handle, Object **outPrimary, Object **outSecondary);
     static FCDECL1(VOID,   nFree, OBJECTHANDLE handle);
+    static FCDECL2(VOID,   nSetPrimary, OBJECTHANDLE handle, Object *primary);
+    static FCDECL2(VOID,   nSetSecondary, OBJECTHANDLE handle, Object *secondary);
 };
 
 #endif
index 721005e..8710715 100644 (file)
@@ -5453,7 +5453,7 @@ static BOOL CanSatisfyConstraints(Instantiation typicalInst, Instantiation candi
             StackScratchBuffer buffer;
             thArg.GetName(candidateInstName);
             char output[1024];
-            sprintf(output, "Generics TypeDependencyAttribute processing: Couldn't satisfy a constraint.  Class with Attribute: %s  Bad candidate instantiated type: %s\r\n", pMT->GetDebugClassName(), candidateInstName.GetANSI(buffer));
+            _snprintf_s(output, _countof(output), _TRUNCATE, "Generics TypeDependencyAttribute processing: Couldn't satisfy a constraint.  Class with Attribute: %s  Bad candidate instantiated type: %s\r\n", pMT->GetDebugClassName(), candidateInstName.GetANSI(buffer));
             OutputDebugStringA(output);
             */
 #endif
index ef195bf..e62ec13 100644 (file)
@@ -1604,7 +1604,7 @@ FCIMPL0(Object*, ThreadNative::GetDomain)
 }
 FCIMPLEND
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && defined(_MSC_VER)
 __declspec(naked) LPVOID __fastcall ThreadNative::FastGetDomain()
 {
     STATIC_CONTRACT_MODE_COOPERATIVE;
@@ -1624,7 +1624,7 @@ done:
         ret
     }
 }
-#else // _TARGET_X86_
+#else // _TARGET_X86_ && _MSC_VER
 LPVOID F_CALL_CONV ThreadNative::FastGetDomain()
 {
     CONTRACTL
@@ -1650,7 +1650,7 @@ LPVOID F_CALL_CONV ThreadNative::FastGetDomain()
     }
     return NULL;
 }
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && _MSC_VER
 
 #ifdef FEATURE_REMOTING
 // This is just a helper method that lets BCL get to the managed context
index 31949a6..12613cb 100644 (file)
@@ -164,7 +164,7 @@ EXTERN_C void STDCALL UM2MDoADCallBack(UMEntryThunk *pEntryThunk,
     UNINSTALL_MANAGED_EXCEPTION_DISPATCHER;
 }
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
 
 EXTERN_C VOID __cdecl UMThunkStubRareDisable();
 EXTERN_C Thread* __stdcall CreateThreadBlockThrow();
@@ -1010,7 +1010,7 @@ Stub *UMThunkMarshInfo::CompileNExportThunk(LoaderHeap *pLoaderHeap, PInvokeStat
     return pcpusl->Link(pLoaderHeap);
 }
 
-#else // _TARGET_X86_
+#else // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
 PCODE UMThunkMarshInfo::GetExecStubEntryPoint()
 {
@@ -1019,7 +1019,7 @@ PCODE UMThunkMarshInfo::GetExecStubEntryPoint()
     return GetEEFuncEntryPoint(UMThunkStub);
 }
 
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
 UMEntryThunkCache::UMEntryThunkCache(AppDomain *pDomain) :
     m_crst(CrstUMEntryThunkCache),
@@ -1302,7 +1302,7 @@ UMThunkMarshInfo::~UMThunkMarshInfo()
     }
     CONTRACTL_END;
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
     if (m_pExecStub)
         m_pExecStub->DecRef();
 #endif
@@ -1364,7 +1364,7 @@ VOID UMThunkMarshInfo::LoadTimeInit(Signature sig, Module * pModule, MethodDesc
     m_pModule = pModule;
     m_sig = sig;
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
     INDEBUG(m_cbRetPop = 0xcccc;)
 #endif
 }
@@ -1407,7 +1407,7 @@ VOID UMThunkMarshInfo::RunTimeInit()
         pFinalILStub = GetStubForInteropMethod(pMD, dwStubFlags, &pStubMD);
     }
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
     PInvokeStaticSigInfo sigInfo;
 
     if (pMD != NULL)
@@ -1458,7 +1458,7 @@ VOID UMThunkMarshInfo::RunTimeInit()
             pFinalExecStub->DecRef();
     }
 
-#else // _TARGET_X86_
+#else // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
     if (pFinalILStub == NULL)
     {
@@ -1499,7 +1499,7 @@ VOID UMThunkMarshInfo::RunTimeInit()
     //
     m_cbActualArgSize = (pStubMD != NULL) ? pStubMD->AsDynamicMethodDesc()->GetNativeStackArgSize() : pMD->SizeOfArgStack();
 
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
     // Must be the last thing we set!
     InterlockedCompareExchangeT<PCODE>(&m_pILStub, pFinalILStub, (PCODE)1);
index 9369168..c2ed6d0 100644 (file)
@@ -110,7 +110,7 @@ public:
         return m_pMD;
     }
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
     PCODE GetExecStubEntryPoint()
     {
         WRAPPER_NO_CONTRACT;
@@ -199,18 +199,18 @@ public:
         return (UINT32)offsetof(UMThunkMarshInfo, m_pILStub);
     }
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
     // Compiles an unmanaged to managed thunk for the given signature. The thunk
     // will call the stub or, if fNoStub == TRUE, directly the managed target.
     Stub *CompileNExportThunk(LoaderHeap *pLoaderHeap, PInvokeStaticSigInfo* pSigInfo, MetaSig *pMetaSig, BOOL fNoStub);
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
 private:
     PCODE             m_pILStub;            // IL stub for marshaling 
                                             // On x86, NULL for no-marshal signatures
                                             // On non-x86, the managed entrypoint for no-delegate no-marshal signatures
     UINT32            m_cbActualArgSize;    // caches m_pSig.SizeOfFrameArgumentArray()
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
     Stub*             m_pExecStub;          // UMEntryThunk jumps directly here
     UINT16            m_cbRetPop;           // stack bytes popped by callee (for UpdateRegDisplay)
     UINT16            m_callConv;           // unmanaged calling convention and flags (CorPinvokeMap)
@@ -248,7 +248,7 @@ public:
     static UMEntryThunk* CreateUMEntryThunk();
     static VOID FreeUMEntryThunk(UMEntryThunk* p);
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
     // Compiles an unmanaged to managed thunk with the given calling convention adaptation.
     // - psrcofsregs are stack offsets that should be loaded to argument registers (ECX, EDX)
     // - psrcofs are stack offsets that should be repushed for the managed target
@@ -263,7 +263,7 @@ public:
                                      UINT *psrcofsregs,
                                      UINT *psrcofs,
                                      UINT retbufofs);
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
 #ifndef DACCESS_COMPILE
     VOID LoadTimeInit(PCODE                   pManagedTarget,
@@ -569,12 +569,12 @@ private:
     AppDomain *m_pDomain;
 };
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
 //-------------------------------------------------------------------------
 // One-time creation of special prestub to initialize UMEntryThunks.
 //-------------------------------------------------------------------------
 Stub *GenerateUMThunkPrestub();
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
 //-------------------------------------------------------------------------
 // NExport stub
index f87fafc..b110d0e 100644 (file)
@@ -108,6 +108,8 @@ FCFuncStart(gDependentHandleFuncs)
     FCFuncElement("nGetPrimary",             DependentHandle::nGetPrimary)
     FCFuncElement("nGetPrimaryAndSecondary", DependentHandle::nGetPrimaryAndSecondary)
     FCFuncElement("nFree",                   DependentHandle::nFree)
+    FCFuncElement("nSetPrimary",             DependentHandle::nSetPrimary)
+    FCFuncElement("nSetSecondary",           DependentHandle::nSetSecondary)
 FCFuncEnd()
 
 #ifndef FEATURE_CORECLR
index 604ac29..3be8384 100644 (file)
@@ -1214,3 +1214,57 @@ void GCToEEInterface::DiagWalkBGCSurvivors(void* gcContext)
 #endif //GC_PROFILING || FEATURE_EVENT_TRACE
 }
 
+void GCToEEInterface::StompWriteBarrier(WriteBarrierParameters* args)
+{
+    assert(args != nullptr);
+    switch (args->operation)
+    {
+    case WriteBarrierOp::StompResize:
+        // StompResize requires a new card table, a new lowest address, and
+        // a new highest address
+        assert(args->card_table != nullptr);
+        assert(args->lowest_address != nullptr);
+        assert(args->highest_address != nullptr);
+        g_card_table = args->card_table;
+        ::StompWriteBarrierResize(args->is_runtime_suspended, args->requires_upper_bounds_check);
+
+        // We need to make sure that other threads executing checked write barriers
+        // will see the g_card_table update before g_lowest/highest_address updates.
+        // Otherwise, the checked write barrier may AV accessing the old card table
+        // with address that it does not cover. Write barriers access card table
+        // without memory barriers for performance reasons, so we need to flush
+        // the store buffers here.
+        FlushProcessWriteBuffers();
+
+        g_lowest_address = args->lowest_address;
+        VolatileStore(&g_highest_address, args->highest_address);
+        return;
+    case WriteBarrierOp::StompEphemeral:
+        // StompEphemeral requires a new ephemeral low and a new ephemeral high
+        assert(args->ephemeral_lo != nullptr);
+        assert(args->ephemeral_hi != nullptr);
+        g_ephemeral_low = args->ephemeral_lo;
+        g_ephemeral_high = args->ephemeral_hi;
+        ::StompWriteBarrierEphemeral(args->is_runtime_suspended);
+        return;
+    case WriteBarrierOp::Initialize:
+        // This operation should only be invoked once, upon initialization.
+        assert(g_card_table == nullptr);
+        assert(g_lowest_address == nullptr);
+        assert(g_highest_address == nullptr);
+        assert(args->card_table != nullptr);
+        assert(args->lowest_address != nullptr);
+        assert(args->highest_address != nullptr);
+        assert(args->is_runtime_suspended && "the runtime must be suspended here!");
+        assert(!args->requires_upper_bounds_check && "the ephemeral generation must be at the top of the heap!");
+
+        g_card_table = args->card_table;
+        FlushProcessWriteBuffers();
+        g_lowest_address = args->lowest_address;
+        VolatileStore(&g_highest_address, args->highest_address);
+        ::StompWriteBarrierResize(true, false);
+        return;
+    default:
+        assert(!"unknown WriteBarrierOp enum");
+    }
+}
index 7511a7c..f431221 100644 (file)
@@ -41,6 +41,7 @@ public:
     void DiagWalkSurvivors(void* gcContext);
     void DiagWalkLOHSurvivors(void* gcContext);
     void DiagWalkBGCSurvivors(void* gcContext);
+    void StompWriteBarrier(WriteBarrierParameters* args);
 };
 
 #endif // FEATURE_STANDALONE_GC
index ceadb9e..ac24fa3 100644 (file)
@@ -5,5 +5,15 @@
 #include "common.h"
 #include "gcheaputilities.h"
 
+// These globals are variables used within the GC and maintained
+// by the EE for use in write barriers. It is the responsibility
+// of the GC to communicate updates to these globals to the EE through
+// GCToEEInterface::StompWriteBarrierResize and GCToEEInterface::StompWriteBarrierEphemeral.
+GPTR_IMPL_INIT(uint32_t, g_card_table,      nullptr);
+GPTR_IMPL_INIT(uint8_t,  g_lowest_address,  nullptr);
+GPTR_IMPL_INIT(uint8_t,  g_highest_address, nullptr);
+uint8_t* g_ephemeral_low  = (uint8_t*)1;
+uint8_t* g_ephemeral_high = (uint8_t*)~0;
+
 // This is the global GC heap, maintained by the VM.
 GPTR_IMPL(IGCHeap, g_pGCHeap);
\ No newline at end of file
index e8f6f0a..e5883fc 100644 (file)
@@ -113,4 +113,17 @@ private:
     GCHeapUtilities() = delete;
 };
 
+#ifndef DACCESS_COMPILE
+extern "C" {
+#endif // !DACCESS_COMPILE
+GPTR_DECL(uint8_t,g_lowest_address);
+GPTR_DECL(uint8_t,g_highest_address);
+GPTR_DECL(uint32_t,g_card_table);
+#ifndef DACCESS_COMPILE
+} 
+#endif // !DACCESS_COMPILE
+
+extern "C" uint8_t* g_ephemeral_low;
+extern "C" uint8_t* g_ephemeral_high;
+
 #endif // _GCHEAPUTILITIES_H_
\ No newline at end of file
index 9a16026..3dae848 100644 (file)
@@ -1471,11 +1471,12 @@ void NotifyGdb::MethodCompiled(MethodDesc* MethodDescPtr)
         method[method_index]->GetLocalsDebugInfo(pTypeMap, locals, symInfo[firstLineIndex].nativeOffset);
         method[method_index]->m_sub_low_pc = pCode + method_start;
         method[method_index]->m_sub_high_pc = method_size;
-        method[method_index]->m_member_name = new char[strlen(methodName) + 10];
+        size_t methodNameSize = strlen(methodName) + 10;
+        method[method_index]->m_member_name = new char[methodNameSize];
         if (method_index == 0)
-            sprintf(method[method_index]->m_member_name, "%s", methodName);
+            sprintf_s(method[method_index]->m_member_name, methodNameSize, "%s", methodName);
         else
-            sprintf(method[method_index]->m_member_name, "%s_%i", methodName, method_index);
+            sprintf_s(method[method_index]->m_member_name, methodNameSize, "%s_%i", methodName, method_index);
 
         // method's class
         GetTypeInfoFromTypeHandle(TypeHandle(method[method_index]->md->GetMethodTable()), pTypeMap);
@@ -2168,7 +2169,7 @@ bool NotifyGdb::CollectCalledMethods(CalledMethod* pCalledMethods)
             int symbolNameLength = strlen(methodName) + sizeof("__thunk_");
             SymbolNames[i].m_name = new char[symbolNameLength];
             SymbolNames[i].m_releaseName = true;
-            sprintf((char*)SymbolNames[i].m_name, "__thunk_%s", methodName);
+            sprintf_s((char*)SymbolNames[i].m_name, symbolNameLength, "__thunk_%s", methodName);
             SymbolNames[i].m_value = callAddr;
             ++i;
             codeAddrs.Add(callAddr);
@@ -2300,7 +2301,7 @@ bool NotifyGdb::BuildSectionTables(MemBuf& sectBuf, MemBuf& strBuf)
         bool isThunkSection = i >= SectionNamesCount;
         if (isThunkSection)
         {
-            sprintf(thunkSectNameBuf, ".thunk_%i", i);
+            sprintf_s(thunkSectNameBuf, _countof(thunkSectNameBuf), ".thunk_%i", i);
             sectName = thunkSectNameBuf;
         }
         else
index 3ca95b6..4a44c2c 100644 (file)
 //
 .macro STUB_PROLOG
     // push ebp-frame
-    push        ebp
-    mov         ebp, esp
+    PROLOG_BEG
 
     // save CalleeSavedRegisters
-    push        ebx
-    push        esi
-    push        edi
+    PROLOG_PUSH ebx
+    PROLOG_PUSH esi
+    PROLOG_PUSH edi
 
     // push ArgumentRegisters
-    push        ecx
-    push        edx
+    PROLOG_PUSH ecx
+    PROLOG_PUSH edx
+
+    // set frame pointer
+    PROLOG_END
 .endm
 
 //
 // FramedMethodFrame epilog
 //
 .macro STUB_EPILOG
+    // restore stack pointer
+    EPILOG_BEG
+
     // pop ArgumentRegisters
-    pop     edx
-    pop     ecx
+    EPILOG_POP edx
+    EPILOG_POP ecx
 
     // pop CalleeSavedRegisters
-    pop edi
-    pop esi
-    pop ebx
-    pop ebp
+    EPILOG_POP edi
+    EPILOG_POP esi
+    EPILOG_POP ebx
+
+    // pop ebp-frame
+    EPILOG_END
 .endm
 
 //
@@ -392,8 +399,11 @@ LEAF_END ArrayOpStubTypeMismatchException, _TEXT
 // ------------------------------------------------------------------------------
 //  void STDCALL CallDescrWorkerInternal(CallDescrWorkerParams *  pParams)
 NESTED_ENTRY CallDescrWorkerInternal, _TEXT, NoHandler
+    PROLOG_BEG
+    PROLOG_PUSH ebx
+    PROLOG_END
 
-    mov     ebx, [esp + 4] // pParams = esp + 4
+    mov     ebx, [esp + ((2 + 1) * 4)]
 
     // copy the stack
     mov     ecx, [ebx +CallDescrData__numStackSlots]
@@ -445,6 +455,9 @@ LOCAL_LABEL(ReturnsInt):
     mov     [ebx + CallDescrData__returnValue + 4], edx
 
 LOCAL_LABEL(Epilog):
+    EPILOG_BEG
+    EPILOG_POP ebx
+    EPILOG_END
     ret     4
 
 LOCAL_LABEL(ReturnsFloat):
@@ -944,23 +957,28 @@ NESTED_ENTRY VirtualMethodFixupStub, _TEXT, NoHandler
     sub     eax, 5
 
     // Push ebp frame to get good callstack under debugger
-    push    ebp
-    mov     ebp, esp
+    PROLOG_BEG
 
     // Preserve argument registers
-    push    ecx
-    push    edx
+    PROLOG_PUSH ecx
+    PROLOG_PUSH edx
+
+    // Set frame pointer
+    PROLOG_END
 
     push    eax         // address of the thunk
     push    ecx         // this ptr
     call    C_FUNC(VirtualMethodFixupWorker)
 
+    // Restore stack pointer
+    EPILOG_BEG
+
     // Restore argument registers
-    pop     edx
-    pop     ecx
+    EPILOG_POP edx
+    EPILOG_POP ecx
 
     // Pop ebp frame
-    pop     ebp
+    EPILOG_END
 
 PATCH_LABEL VirtualMethodFixupPatchLabel
     // Proceed to execute the actual method.
@@ -1048,3 +1066,52 @@ DYNAMICHELPER DynamicHelperFrameFlags_ObjectArg, _Obj
 DYNAMICHELPER (DynamicHelperFrameFlags_ObjectArg | DynamicHelperFrameFlags_ObjectArg2), _ObjObj
 
 #endif // FEATURE_READYTORUN
+
+NESTED_ENTRY ResolveWorkerAsmStub, _TEXT, NoHandler
+    //
+    // The stub arguments are where we want to setup the TransitionBlock. We will
+    // setup the TransitionBlock later once we can trash them
+    //
+    // push ebp-frame
+    // push      ebp
+    // mov       ebp,esp
+
+    // save CalleeSavedRegisters
+    // push      ebx
+
+    push        esi
+    push        edi
+
+    // push ArgumentRegisters
+    push        ecx
+    push        edx
+
+    mov         esi, esp
+
+    push        [esi + 4*4]     // dispatch token
+    push        [esi + 5*4]     // siteAddrForRegisterIndirect
+    push        esi             // pTransitionBlock
+
+    // Setup up proper EBP frame now that the stub arguments can be trashed
+    mov         [esi + 4*4],ebx
+    mov         [esi + 5*4],ebp
+    lea         ebp, [esi + 5*4]
+
+    // Make the call
+    call        C_FUNC(VSD_ResolveWorker)
+
+    // From here on, mustn't trash eax
+
+    // pop ArgumentRegisters
+    pop     edx
+    pop     ecx
+
+    // pop CalleeSavedRegisters
+    pop edi
+    pop esi
+    pop ebx
+    pop ebp
+
+    // Now jump to the target
+    jmp     eax             // continue on into the method
+NESTED_END ResolveWorkerAsmStub, _TEXT
index 3774ac4..08ccd01 100644 (file)
@@ -760,6 +760,7 @@ WORD GetUnpatchedCodeData(LPCBYTE pAddr)
 
 #ifndef DACCESS_COMPILE
 
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
 //-------------------------------------------------------------------------
 // One-time creation of special prestub to initialize UMEntryThunks.
 //-------------------------------------------------------------------------
@@ -772,7 +773,6 @@ Stub *GenerateUMThunkPrestub()
     }
     CONTRACT_END;
 
-#ifndef FEATURE_STUBS_AS_IL
     CPUSTUBLINKER sl;
     CPUSTUBLINKER *psl = &sl;
 
@@ -809,11 +809,8 @@ Stub *GenerateUMThunkPrestub()
     psl->EmitComMethodStubEpilog(UMThkCallFrame::GetMethodFrameVPtr(), rgRareLabels, rgRejoinLabels, FALSE /*Don't profile*/);
 
     RETURN psl->Link(SystemDomain::GetGlobalLoaderAllocator()->GetExecutableHeap());
-#else  // FEATURE_STUBS_AS_IL
-    PORTABILITY_ASSERT("GenerateUMThunkPrestub");
-    return NULL;
-#endif // FEATURE_STUBS_AS_IL
 }
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
 Stub *GenerateInitPInvokeFrameHelper()
 {
@@ -1761,7 +1758,52 @@ extern "C" DWORD __stdcall xmmYmmStateSupport()
 
 #pragma warning(pop)
 
-#endif
+#else // !FEATURE_PAL
+
+extern "C" DWORD __stdcall getcpuid(DWORD arg, unsigned char result[16])
+{
+    DWORD eax;
+    __asm("  xor %%ecx, %%ecx\n" \
+            "  cpuid\n" \
+            "  mov %%eax, 0(%[result])\n" \
+            "  mov %%ebx, 4(%[result])\n" \
+            "  mov %%ecx, 8(%[result])\n" \
+            "  mov %%edx, 12(%[result])\n" \
+        : "=a"(eax) /*output in eax*/\
+        : "a"(arg), [result]"r"(result) /*inputs - arg in eax, result in any register*/\
+        : "eax", "rbx", "ecx", "edx", "memory" /* registers that are clobbered, *result is clobbered */
+        );
+    return eax;
+}
+
+extern "C" DWORD __stdcall getextcpuid(DWORD arg1, DWORD arg2, unsigned char result[16])
+{
+    DWORD eax;
+    __asm("  cpuid\n" \
+            "  mov %%eax, 0(%[result])\n" \
+            "  mov %%ebx, 4(%[result])\n" \
+            "  mov %%ecx, 8(%[result])\n" \
+            "  mov %%edx, 12(%[result])\n" \
+        : "=a"(eax) /*output in eax*/\
+        : "c"(arg1), "a"(arg2), [result]"r"(result) /*inputs - arg1 in ecx, arg2 in eax, result in any register*/\
+        : "eax", "rbx", "ecx", "edx", "memory" /* registers that are clobbered, *result is clobbered */
+        );
+    return eax;
+}
+
+extern "C" DWORD __stdcall xmmYmmStateSupport()
+{
+    DWORD eax;
+    __asm("  xgetbv\n" \
+        : "=a"(eax) /*output in eax*/\
+        : "c"(0) /*inputs - 0 in ecx*/\
+        : "eax", "edx" /* registers that are clobbered*/
+        );
+    // check OS has enabled both XMM and YMM state support
+    return ((eax & 0x06) == 0x06) ? 1 : 0;
+}
+
+#endif // !FEATURE_PAL
 
 // This function returns the number of logical processors on a given physical chip.  If it cannot
 // determine the number of logical cpus, or the machine is not populated uniformly with the same
diff --git a/src/vm/i386/umthunkstub.S b/src/vm/i386/umthunkstub.S
new file mode 100644 (file)
index 0000000..2bc6fb7
--- /dev/null
@@ -0,0 +1,32 @@
+// 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.
+
+.intel_syntax noprefix
+#include "unixasmmacros.inc"
+#include "asmconstants.h"
+
+//
+// eax = UMEntryThunk*
+//
+NESTED_ENTRY TheUMEntryPrestub, _TEXT, UnhandledExceptionHandlerUnix
+    // Preserve argument registers
+    push    ecx
+    push    edx
+
+    push    eax
+    call    C_FUNC(TheUMEntryPrestubWorker)
+    pop     edx
+
+    // Restore argument registers
+    pop     edx
+    pop     ecx
+
+    jmp     eax     // Tail Jmp
+NESTED_END TheUMEntryPrestub, _TEXT
+
+
+NESTED_ENTRY UMThunkStub, _TEXT, UnhandledExceptionHandlerUnix
+    int     3       // implement here
+    ret
+NESTED_END UMThunkStub, _TEXT
index a6aa41f..5f098c1 100644 (file)
@@ -41,49 +41,6 @@ extern "C"
         PORTABILITY_ASSERT("Implement for PAL");
     }
 
-    DWORD getcpuid(DWORD arg, unsigned char result[16])
-    {
-        DWORD eax;
-        __asm("  xor %%ecx, %%ecx\n" \
-              "  cpuid\n" \
-              "  mov %%eax, 0(%[result])\n" \
-              "  mov %%ebx, 4(%[result])\n" \
-              "  mov %%ecx, 8(%[result])\n" \
-              "  mov %%edx, 12(%[result])\n" \
-            : "=a"(eax) /*output in eax*/\
-            : "a"(arg), [result]"r"(result) /*inputs - arg in eax, result in any register*/\
-            : "eax", "rbx", "ecx", "edx", "memory" /* registers that are clobbered, *result is clobbered */
-          );
-        return eax;
-    }
-    
-    DWORD getextcpuid(DWORD arg1, DWORD arg2, unsigned char result[16])
-    {
-        DWORD eax;
-        __asm("  cpuid\n" \
-              "  mov %%eax, 0(%[result])\n" \
-              "  mov %%ebx, 4(%[result])\n" \
-              "  mov %%ecx, 8(%[result])\n" \
-              "  mov %%edx, 12(%[result])\n" \
-            : "=a"(eax) /*output in eax*/\
-            : "c"(arg1), "a"(arg2), [result]"r"(result) /*inputs - arg1 in ecx, arg2 in eax, result in any register*/\
-            : "eax", "rbx", "ecx", "edx", "memory" /* registers that are clobbered, *result is clobbered */
-          );
-        return eax;
-    }
-
-    DWORD xmmYmmStateSupport()
-    {
-        DWORD eax;
-        __asm("  xgetbv\n" \
-            : "=a"(eax) /*output in eax*/\
-            : "c"(0) /*inputs - 0 in ecx*/\
-            : "eax", "edx" /* registers that are clobbered*/
-          );
-        // check OS has enabled both XMM and YMM state support
-        return ((eax & 0x06) == 0x06) ? 1 : 0;
-    }
-    
     void STDCALL JIT_ProfilerEnterLeaveTailcallStub(UINT_PTR ProfilerHandle)
     {
     }
@@ -112,3 +69,18 @@ VOID __cdecl PopSEHRecords(LPVOID pTargetSP)
 {
     PORTABILITY_ASSERT("Implement for PAL");
 }
+
+EXTERN_C VOID SinglecastDelegateInvokeStub()
+{
+    PORTABILITY_ASSERT("SinglecastDelegateInvokeStub");
+}
+
+EXTERN_C VOID ResolveWorkerChainLookupAsmStub()
+{
+    PORTABILITY_ASSERT("ResolveWorkerChainLookupAsmStub");
+}
+
+EXTERN_C VOID BackPatchWorkerAsmStub()
+{
+    PORTABILITY_ASSERT("BackPatchWorkerAsmStub");
+}
index 812baa2..e0d4096 100644 (file)
@@ -1647,9 +1647,9 @@ PCODE MethodDesc::DoPrestub(MethodTable *pDispatchingMT)
 // use the prestub.
 //==========================================================================
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
 static PCODE g_UMThunkPreStub;
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
 #ifndef DACCESS_COMPILE 
 
@@ -1676,9 +1676,9 @@ void InitPreStubManager(void)
         return;
     }
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
     g_UMThunkPreStub = GenerateUMThunkPrestub()->GetEntryPoint();
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 
     ThePreStubManager::Init();
 }
@@ -1687,11 +1687,11 @@ PCODE TheUMThunkPreStub()
 {
     LIMITED_METHOD_CONTRACT;
 
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
     return g_UMThunkPreStub;
-#else  // _TARGET_X86_
+#else  // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
     return GetEEFuncEntryPoint(TheUMEntryPrestub);
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
 }
 
 PCODE TheVarargNDirectStub(BOOL hasRetBuffArg)
index cd5259f..9c6e468 100644 (file)
@@ -1,10 +1,10 @@
 {
   "dependencies": {
-    "Microsoft.NETCore.ILAsm": "1.2.0-beta-24801-03",
-    "Microsoft.NETCore.ILDAsm": "1.2.0-beta-24801-03",
-    "Microsoft.NETCore.Jit": "1.2.0-beta-24801-03",
-    "Microsoft.NETCore.Runtime.CoreCLR": "1.2.0-beta-24801-03",
-    "Microsoft.NETCore.TestHost": "1.2.0-beta-24801-03"
+    "Microsoft.NETCore.ILAsm": "1.2.0-beta-24810-01",
+    "Microsoft.NETCore.ILDAsm": "1.2.0-beta-24810-01",
+    "Microsoft.NETCore.Jit": "1.2.0-beta-24810-01",
+    "Microsoft.NETCore.Runtime.CoreCLR": "1.2.0-beta-24810-01",
+    "Microsoft.NETCore.TestHost": "1.2.0-beta-24810-01"
   },
   "frameworks": {
     "netcoreapp1.1": {
index fc656a5..ff06e8e 100644 (file)
@@ -5,66 +5,66 @@
     "emitEntryPoint": true
   },
   "dependencies": {
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
-    "Microsoft.NETCore.Targets": "1.2.0-beta-24721-02",
-    "System.Threading.Thread": "4.4.0-beta-24721-02",
-    "System.Collections": "4.4.0-beta-24721-02",
-    "System.Xml.XmlSerializer": "4.4.0-beta-24721-02",
-    "System.Collections.Concurrent": "4.4.0-beta-24721-02",
-    "System.ObjectModel": "4.4.0-beta-24721-02",
-    "System.Runtime.Numerics": "4.4.0-beta-24721-02",
-    "System.Collections.NonGeneric": "4.4.0-beta-24721-02",
-    "System.Collections.Specialized": "4.4.0-beta-24721-02",
-    "System.ComponentModel": "4.4.0-beta-24721-02",
-    "System.Reflection.Emit.Lightweight": "4.4.0-beta-24721-02",
-    "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Contracts": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Debug": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Process": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Tools": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Tracing": "4.4.0-beta-24721-02",
-    "System.Dynamic.Runtime": "4.4.0-beta-24721-02",
-    "System.Globalization": "4.4.0-beta-24721-02",
-    "System.Globalization.Calendars": "4.4.0-beta-24721-02",
-    "System.IO": "4.4.0-beta-24721-02",
-    "System.IO.FileSystem": "4.4.0-beta-24721-02",
-    "System.IO.FileSystem.Primitives": "4.4.0-beta-24721-02",
-    "System.Linq": "4.4.0-beta-24721-02",
-    "System.Linq.Queryable": "4.4.0-beta-24721-02",
-    "System.Linq.Expressions": "4.4.0-beta-24721-02",
-    "System.Reflection": "4.4.0-beta-24721-02",
-    "System.Reflection.Extensions": "4.4.0-beta-24721-02",
-    "System.Resources.ResourceManager": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24721-02",
-    "System.Runtime.Extensions": "4.4.0-beta-24721-02",
-    "System.Runtime.Handles": "4.4.0-beta-24721-02",
-    "System.Runtime.InteropServices": "4.4.0-beta-24721-02",
-    "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24721-02",
-    "System.Runtime.Loader": "4.4.0-beta-24721-02",
-    "System.Security.Cryptography.Algorithms": "4.4.0-beta-24721-02",
-    "System.Text.Encoding": "4.4.0-beta-24721-02",
-    "System.Text.Encoding.Extensions": "4.4.0-beta-24721-02",
-    "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
-    "System.Threading": "4.4.0-beta-24721-02",
-    "System.Threading.AccessControl": "4.4.0-beta-24721-02",
-    "System.Threading.Overlapped": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
-    "System.Threading.ThreadPool": "4.4.0-beta-24721-02",
-    "System.Threading.Timer": "4.4.0-beta-24721-02",
-    "System.Xml.ReaderWriter": "4.4.0-beta-24721-02",
-    "System.Xml.XDocument": "4.4.0-beta-24721-02",
-    "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
-    "System.Xml.XPath": "4.4.0-beta-24721-02",
-    "System.Xml.XPath.XmlDocument": "4.4.0-beta-24721-02",
-    "System.Numerics.Vectors": "4.4.0-beta-24721-02"
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+    "Microsoft.NETCore.Targets": "1.2.0-beta-24810-02",
+    "System.Threading.Thread": "4.4.0-beta-24810-02",
+    "System.Collections": "4.4.0-beta-24810-02",
+    "System.Xml.XmlSerializer": "4.4.0-beta-24810-02",
+    "System.Collections.Concurrent": "4.4.0-beta-24810-02",
+    "System.ObjectModel": "4.4.0-beta-24810-02",
+    "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+    "System.Collections.NonGeneric": "4.4.0-beta-24810-02",
+    "System.Collections.Specialized": "4.4.0-beta-24810-02",
+    "System.ComponentModel": "4.4.0-beta-24810-02",
+    "System.Reflection.Emit.Lightweight": "4.4.0-beta-24810-02",
+    "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Contracts": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Debug": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Tools": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Tracing": "4.4.0-beta-24810-02",
+    "System.Dynamic.Runtime": "4.4.0-beta-24810-02",
+    "System.Globalization": "4.4.0-beta-24810-02",
+    "System.Globalization.Calendars": "4.4.0-beta-24810-02",
+    "System.IO": "4.4.0-beta-24810-02",
+    "System.IO.FileSystem": "4.4.0-beta-24810-02",
+    "System.IO.FileSystem.Primitives": "4.4.0-beta-24810-02",
+    "System.Linq": "4.4.0-beta-24810-02",
+    "System.Linq.Queryable": "4.4.0-beta-24810-02",
+    "System.Linq.Expressions": "4.4.0-beta-24810-02",
+    "System.Reflection": "4.4.0-beta-24810-02",
+    "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+    "System.Resources.ResourceManager": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24810-02",
+    "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+    "System.Runtime.Handles": "4.4.0-beta-24810-02",
+    "System.Runtime.InteropServices": "4.4.0-beta-24810-02",
+    "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24810-02",
+    "System.Runtime.Loader": "4.4.0-beta-24810-02",
+    "System.Security.Cryptography.Algorithms": "4.4.0-beta-24810-02",
+    "System.Text.Encoding": "4.4.0-beta-24810-02",
+    "System.Text.Encoding.Extensions": "4.4.0-beta-24810-02",
+    "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+    "System.Threading": "4.4.0-beta-24810-02",
+    "System.Threading.AccessControl": "4.4.0-beta-24810-02",
+    "System.Threading.Overlapped": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+    "System.Threading.ThreadPool": "4.4.0-beta-24810-02",
+    "System.Threading.Timer": "4.4.0-beta-24810-02",
+    "System.Xml.ReaderWriter": "4.4.0-beta-24810-02",
+    "System.Xml.XDocument": "4.4.0-beta-24810-02",
+    "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+    "System.Xml.XPath": "4.4.0-beta-24810-02",
+    "System.Xml.XPath.XmlDocument": "4.4.0-beta-24810-02",
+    "System.Numerics.Vectors": "4.4.0-beta-24810-02"
   },
   "frameworks": {
     "netcoreapp1.1": {
       "dependencies": {
-        "Microsoft.NETCore.Runtime.CoreCLR": "1.2.0-beta-24801-03"
+        "Microsoft.NETCore.Runtime.CoreCLR": "1.2.0-beta-24810-01"
       }
     }
   },
index 9eda1b0..4961805 100644 (file)
@@ -1,6 +1,6 @@
 {
   "dependencies": {
-    "Microsoft.TargetingPack.Private.CoreCLR": "1.2.0-beta-24801-03"
+    "Microsoft.TargetingPack.Private.CoreCLR": "1.2.0-beta-24810-01"
   },
   "frameworks": {
     "netcoreapp1.1": {
index 2848465..5460b77 100644 (file)
@@ -7,67 +7,67 @@
     "Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
-    "Microsoft.Win32.Primitives": "4.4.0-beta-24721-02",
+    "Microsoft.Win32.Primitives": "4.4.0-beta-24810-02",
     "Newtonsoft.Json": "8.0.3",
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
-    "Microsoft.NETCore.Targets": "1.2.0-beta-24721-02",
-    "System.Collections.Immutable": "1.4.0-beta-24721-02",
-    "System.Threading.Thread": "4.4.0-beta-24721-02",
-    "System.Collections": "4.4.0-beta-24721-02",
-    "System.Xml.XmlSerializer": "4.4.0-beta-24721-02",
-    "System.Collections.Concurrent": "4.4.0-beta-24721-02",
-    "System.ObjectModel": "4.4.0-beta-24721-02",
-    "System.Runtime.Numerics": "4.4.0-beta-24721-02",
-    "System.Collections.NonGeneric": "4.4.0-beta-24721-02",
-    "System.Collections.Specialized": "4.4.0-beta-24721-02",
-    "System.ComponentModel": "4.4.0-beta-24721-02",
-    "System.Reflection.Emit.Lightweight": "4.4.0-beta-24721-02",
-    "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Contracts": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Debug": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Process": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Tools": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Tracing": "4.4.0-beta-24721-02",
-    "System.Dynamic.Runtime": "4.4.0-beta-24721-02",
-    "System.Globalization": "4.4.0-beta-24721-02",
-    "System.Globalization.Calendars": "4.4.0-beta-24721-02",
-    "System.IO": "4.4.0-beta-24721-02",
-    "System.IO.FileSystem": "4.4.0-beta-24721-02",
-    "System.IO.FileSystem.Primitives": "4.4.0-beta-24721-02",
-    "System.Linq": "4.4.0-beta-24721-02",
-    "System.Linq.Queryable": "4.4.0-beta-24721-02",
-    "System.Linq.Expressions": "4.4.0-beta-24721-02",
-    "System.Reflection": "4.4.0-beta-24721-02",
-    "System.Reflection.Extensions": "4.4.0-beta-24721-02",
-    "System.Resources.ResourceManager": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24721-02",
-    "System.Runtime.Extensions": "4.4.0-beta-24721-02",
-    "System.Runtime.Handles": "4.4.0-beta-24721-02",
-    "System.Runtime.InteropServices": "4.4.0-beta-24721-02",
-    "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24721-02",
-    "System.Runtime.Loader": "4.4.0-beta-24721-02",
-    "System.Runtime.Serialization.Json": "4.4.0-beta-24721-02",
-    "System.Runtime.Serialization.Primitives": "4.4.0-beta-24721-02",
-    "System.Runtime.Serialization.Xml": "4.4.0-beta-24721-02",
-    "System.Security.Cryptography.Algorithms": "4.4.0-beta-24721-02",
-    "System.Text.Encoding": "4.4.0-beta-24721-02",
-    "System.Text.Encoding.Extensions": "4.4.0-beta-24721-02",
-    "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
-    "System.Threading": "4.4.0-beta-24721-02",
-    "System.Threading.AccessControl": "4.4.0-beta-24721-02",
-    "System.Threading.Overlapped": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
-    "System.Threading.ThreadPool": "4.4.0-beta-24721-02",
-    "System.Threading.Timer": "4.4.0-beta-24721-02",
-    "System.Xml.ReaderWriter": "4.4.0-beta-24721-02",
-    "System.Xml.XDocument": "4.4.0-beta-24721-02",
-    "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
-    "System.Xml.XPath": "4.4.0-beta-24721-02",
-    "System.Xml.XPath.XmlDocument": "4.4.0-beta-24721-02",
-    "System.Numerics.Vectors": "4.4.0-beta-24721-02"
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+    "Microsoft.NETCore.Targets": "1.2.0-beta-24810-02",
+    "System.Collections.Immutable": "1.4.0-beta-24810-02",
+    "System.Threading.Thread": "4.4.0-beta-24810-02",
+    "System.Collections": "4.4.0-beta-24810-02",
+    "System.Xml.XmlSerializer": "4.4.0-beta-24810-02",
+    "System.Collections.Concurrent": "4.4.0-beta-24810-02",
+    "System.ObjectModel": "4.4.0-beta-24810-02",
+    "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+    "System.Collections.NonGeneric": "4.4.0-beta-24810-02",
+    "System.Collections.Specialized": "4.4.0-beta-24810-02",
+    "System.ComponentModel": "4.4.0-beta-24810-02",
+    "System.Reflection.Emit.Lightweight": "4.4.0-beta-24810-02",
+    "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Contracts": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Debug": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Tools": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Tracing": "4.4.0-beta-24810-02",
+    "System.Dynamic.Runtime": "4.4.0-beta-24810-02",
+    "System.Globalization": "4.4.0-beta-24810-02",
+    "System.Globalization.Calendars": "4.4.0-beta-24810-02",
+    "System.IO": "4.4.0-beta-24810-02",
+    "System.IO.FileSystem": "4.4.0-beta-24810-02",
+    "System.IO.FileSystem.Primitives": "4.4.0-beta-24810-02",
+    "System.Linq": "4.4.0-beta-24810-02",
+    "System.Linq.Queryable": "4.4.0-beta-24810-02",
+    "System.Linq.Expressions": "4.4.0-beta-24810-02",
+    "System.Reflection": "4.4.0-beta-24810-02",
+    "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+    "System.Resources.ResourceManager": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24810-02",
+    "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+    "System.Runtime.Handles": "4.4.0-beta-24810-02",
+    "System.Runtime.InteropServices": "4.4.0-beta-24810-02",
+    "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24810-02",
+    "System.Runtime.Loader": "4.4.0-beta-24810-02",
+    "System.Runtime.Serialization.Json": "4.4.0-beta-24810-02",
+    "System.Runtime.Serialization.Primitives": "4.4.0-beta-24810-02",
+    "System.Runtime.Serialization.Xml": "4.4.0-beta-24810-02",
+    "System.Security.Cryptography.Algorithms": "4.4.0-beta-24810-02",
+    "System.Text.Encoding": "4.4.0-beta-24810-02",
+    "System.Text.Encoding.Extensions": "4.4.0-beta-24810-02",
+    "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+    "System.Threading": "4.4.0-beta-24810-02",
+    "System.Threading.AccessControl": "4.4.0-beta-24810-02",
+    "System.Threading.Overlapped": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+    "System.Threading.ThreadPool": "4.4.0-beta-24810-02",
+    "System.Threading.Timer": "4.4.0-beta-24810-02",
+    "System.Xml.ReaderWriter": "4.4.0-beta-24810-02",
+    "System.Xml.XDocument": "4.4.0-beta-24810-02",
+    "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+    "System.Xml.XPath": "4.4.0-beta-24810-02",
+    "System.Xml.XPath.XmlDocument": "4.4.0-beta-24810-02",
+    "System.Numerics.Vectors": "4.4.0-beta-24810-02"
   },
   "frameworks": {
     "netcoreapp1.1": {
index 35a05a6..6b109e9 100644 (file)
@@ -13,6 +13,7 @@
     <ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
     <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\11.0\UITestExtensionPackages</ReferencePath>
     <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
+    <GCStressIncompatible Condition="'$(Platform)' == 'x86'">true</GCStressIncompatible>
     
     <NuGetPackageImportStamp>7a9bfb7d</NuGetPackageImportStamp>
     <CLRTestExecutionArguments></CLRTestExecutionArguments>
diff --git a/tests/src/JIT/Regression/JitBlue/GitHub_8599/GitHub_8599.cs b/tests/src/JIT/Regression/JitBlue/GitHub_8599/GitHub_8599.cs
new file mode 100644 (file)
index 0000000..95ff457
--- /dev/null
@@ -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;
+using System.Runtime.CompilerServices;
+
+// TreeNodeInfoInitCmp attempts to eliminate the cast from cmp(cast<ubyte>(x), icon)
+// by narrowing the compare to ubyte. This should only happen if the constant fits in
+// a byte so it can be narrowed too, otherwise codegen produces an int sized compare.
+
+class Program
+{
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    static int GetValue() => 301;
+
+    static void Escape(ref int x)
+    {
+    }
+
+    static int Main()
+    {
+        if ((byte)GetValue() > 300)
+        {
+            return -1;
+        }
+
+        int x = GetValue();
+        Escape(ref x);
+        if ((byte)x > 300)
+        {
+            return -2;
+        }
+
+        if ((byte)(GetValue() | 2) > 300)
+        {
+            return -3;
+        }
+
+        return 100;
+    }
+}
diff --git a/tests/src/JIT/Regression/JitBlue/GitHub_8599/GitHub_8599.csproj b/tests/src/JIT/Regression/JitBlue/GitHub_8599/GitHub_8599.csproj
new file mode 100644 (file)
index 0000000..b174dea
--- /dev/null
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <AssemblyName>$(MSBuildProjectName)</AssemblyName>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{95DFC527-4DC1-495E-97D7-E94EE1F7140D}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <FileAlignment>512</FileAlignment>
+    <ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+    <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\11.0\UITestExtensionPackages</ReferencePath>
+    <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
+
+    <NuGetPackageImportStamp>7a9bfb7d</NuGetPackageImportStamp>
+  </PropertyGroup>
+  <!-- Default configurations to help VS understand the configurations -->
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+  </PropertyGroup>
+  <ItemGroup>
+    <CodeAnalysisDependentAssemblyPaths Condition=" '$(VS100COMNTOOLS)' != '' " Include="$(VS100COMNTOOLS)..\IDE\PrivateAssemblies">
+      <Visible>False</Visible>
+    </CodeAnalysisDependentAssemblyPaths>
+  </ItemGroup>
+  <PropertyGroup>
+    <DebugType></DebugType>
+    <Optimize>True</Optimize>
+  </PropertyGroup>
+  <ItemGroup>
+    <Compile Include="$(MSBuildProjectName).cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
+  </ItemGroup>
+  <PropertyGroup>
+    <ProjectJson>$(JitPackagesConfigFileDirectory)minimal\project.json</ProjectJson>
+    <ProjectLockJson>$(JitPackagesConfigFileDirectory)minimal\project.lock.json</ProjectLockJson>
+  </PropertyGroup>
+  <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+  <PropertyGroup Condition=" '$(MsBuildProjectDirOverride)' != '' ">
+  </PropertyGroup> 
+</Project>
index 63da40b..ad11fd2 100644 (file)
@@ -4,23 +4,23 @@
     "Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.Dynamic.Runtime": "4.4.0-beta-24721-02",
-    "System.Linq": "4.4.0-beta-24721-02",
-    "System.IO.FileSystem": "4.4.0-beta-24721-02",
-    "System.Numerics.Vectors": "4.4.0-beta-24721-02",
-    "System.Reflection": "4.4.0-beta-24721-02",
-    "System.Reflection.Extensions": "4.4.0-beta-24721-02",
-    "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.Extensions": "4.4.0-beta-24721-02",
-    "System.Runtime.Numerics": "4.4.0-beta-24721-02",
-    "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
-    "System.Threading": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
-    "System.Security.Cryptography.Algorithms": "4.4.0-beta-24721-02",
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.Dynamic.Runtime": "4.4.0-beta-24810-02",
+    "System.Linq": "4.4.0-beta-24810-02",
+    "System.IO.FileSystem": "4.4.0-beta-24810-02",
+    "System.Numerics.Vectors": "4.4.0-beta-24810-02",
+    "System.Reflection": "4.4.0-beta-24810-02",
+    "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+    "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+    "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+    "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+    "System.Threading": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+    "System.Security.Cryptography.Algorithms": "4.4.0-beta-24810-02",
     "xunit": "2.2.0-beta2-build3300",
     "xunit.console.netcore": "1.0.2-prerelease-00177",
     "xunit.runner.utility": "2.2.0-beta2-build3300"
index 2c1ee11..617bfc9 100644 (file)
@@ -3,24 +3,24 @@
     "Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
     "Newtonsoft.Json": "7.0.1",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.IO": "4.4.0-beta-24721-02",
-    "System.IO.FileSystem": "4.4.0-beta-24721-02",
-    "System.Linq": "4.4.0-beta-24721-02",
-    "System.ObjectModel": "4.4.0-beta-24721-02",
-    "System.Dynamic.Runtime": "4.4.0-beta-24721-02",
-    "System.Reflection": "4.4.0-beta-24721-02",
-    "System.Reflection.Extensions": "4.4.0-beta-24721-02",
-    "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.Serialization.Json": "4.4.0-beta-24721-02",
-    "System.Runtime.Serialization.Primitives": "4.4.0-beta-24721-02",
-    "System.Runtime.Serialization.Xml": "4.4.0-beta-24721-02",
-    "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
-    "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
-    "System.Xml.XmlSerializer": "4.4.0-beta-24721-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.IO": "4.4.0-beta-24810-02",
+    "System.IO.FileSystem": "4.4.0-beta-24810-02",
+    "System.Linq": "4.4.0-beta-24810-02",
+    "System.ObjectModel": "4.4.0-beta-24810-02",
+    "System.Dynamic.Runtime": "4.4.0-beta-24810-02",
+    "System.Reflection": "4.4.0-beta-24810-02",
+    "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+    "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.Serialization.Json": "4.4.0-beta-24810-02",
+    "System.Runtime.Serialization.Primitives": "4.4.0-beta-24810-02",
+    "System.Runtime.Serialization.Xml": "4.4.0-beta-24810-02",
+    "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+    "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+    "System.Xml.XmlSerializer": "4.4.0-beta-24810-02",
     "xunit": "2.2.0-beta2-build3300",
     "xunit.console.netcore": "1.0.2-prerelease-00177",
     "xunit.runner.utility": "2.2.0-beta2-build3300"
index 90b80d0..d2a00fd 100644 (file)
@@ -3,27 +3,27 @@
     "Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
-    "System.Collections.NonGeneric": "4.4.0-beta-24721-02",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.IO.FileSystem": "4.4.0-beta-24721-02",
-    "System.Linq": "4.4.0-beta-24721-02",
-    "System.Linq.Expressions": "4.4.0-beta-24721-02",
-    "System.Numerics.Vectors": "4.4.0-beta-24721-02",
-    "System.Reflection": "4.4.0-beta-24721-02",
-    "System.Reflection.Extensions": "4.4.0-beta-24721-02",
-    "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.Extensions": "4.4.0-beta-24721-02",
-    "System.Runtime.Numerics": "4.4.0-beta-24721-02",
-    "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
-    "System.Threading": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Process": "4.4.0-beta-24721-02",
-    "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
-    "System.Xml.XPath": "4.4.0-beta-24721-02",
-    "System.Xml.XPath.XmlDocument": "4.4.0-beta-24721-02",
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+    "System.Collections.NonGeneric": "4.4.0-beta-24810-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.IO.FileSystem": "4.4.0-beta-24810-02",
+    "System.Linq": "4.4.0-beta-24810-02",
+    "System.Linq.Expressions": "4.4.0-beta-24810-02",
+    "System.Numerics.Vectors": "4.4.0-beta-24810-02",
+    "System.Reflection": "4.4.0-beta-24810-02",
+    "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+    "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+    "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+    "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+    "System.Threading": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+    "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+    "System.Xml.XPath": "4.4.0-beta-24810-02",
+    "System.Xml.XPath.XmlDocument": "4.4.0-beta-24810-02",
     "xunit": "2.2.0-beta2-build3300",
     "xunit.console.netcore": "1.0.2-prerelease-00177",
     "xunit.runner.utility": "2.2.0-beta2-build3300"
index dd99676..57ef7b1 100644 (file)
@@ -1,21 +1,21 @@
 {
   "dependencies": {
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
-    "System.Collections": "4.4.0-beta-24721-02",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Debug": "4.4.0-beta-24721-02",
-    "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Process": "4.4.0-beta-24721-02",
-    "System.Globalization": "4.4.0-beta-24721-02",
-    "System.IO": "4.4.0-beta-24721-02",
-    "System.IO.FileSystem": "4.4.0-beta-24721-02",
-    "System.Reflection": "4.4.0-beta-24721-02",
-    "System.Reflection.Extensions": "4.4.0-beta-24721-02",
-    "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.Extensions": "4.4.0-beta-24721-02",
-    "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24721-02",
-    "System.Runtime.InteropServices": "4.4.0-beta-24721-02"
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+    "System.Collections": "4.4.0-beta-24810-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Debug": "4.4.0-beta-24810-02",
+    "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+    "System.Globalization": "4.4.0-beta-24810-02",
+    "System.IO": "4.4.0-beta-24810-02",
+    "System.IO.FileSystem": "4.4.0-beta-24810-02",
+    "System.Reflection": "4.4.0-beta-24810-02",
+    "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+    "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+    "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24810-02",
+    "System.Runtime.InteropServices": "4.4.0-beta-24810-02"
   },
   "frameworks": {
     "netcoreapp1.1": {}
index 35e0516..0d4c358 100644 (file)
@@ -1,10 +1,10 @@
 {
   "dependencies": {
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.Extensions": "4.4.0-beta-24721-02",
-    "System.Runtime.InteropServices": "4.4.0-beta-24721-02"
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+    "System.Runtime.InteropServices": "4.4.0-beta-24810-02"
   },
   "frameworks": {
     "netcoreapp1.1": {}
index dcff6fa..9073deb 100644 (file)
@@ -1,12 +1,12 @@
 {
   "dependencies": {
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.Numerics.Vectors": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.Extensions": "4.4.0-beta-24721-02",
-    "System.Threading": "4.4.0-beta-24721-02",
-    "System.Threading.Thread": "4.4.0-beta-24721-02"
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.Numerics.Vectors": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+    "System.Threading": "4.4.0-beta-24810-02",
+    "System.Threading.Thread": "4.4.0-beta-24810-02"
   },
   "frameworks": {
     "netcoreapp1.1": {}
index 15678a5..b1a8047 100644 (file)
@@ -1,10 +1,10 @@
 {
   "dependencies": {
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.Extensions": "4.4.0-beta-24721-02",
-    "System.Threading": "4.4.0-beta-24721-02"
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+    "System.Threading": "4.4.0-beta-24810-02"
   },
   "frameworks": {
     "netcoreapp1.1": {}
index 90b80d0..d2a00fd 100644 (file)
@@ -3,27 +3,27 @@
     "Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
     "Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
-    "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
-    "System.Collections.NonGeneric": "4.4.0-beta-24721-02",
-    "System.Console": "4.4.0-beta-24721-02",
-    "System.IO.FileSystem": "4.4.0-beta-24721-02",
-    "System.Linq": "4.4.0-beta-24721-02",
-    "System.Linq.Expressions": "4.4.0-beta-24721-02",
-    "System.Numerics.Vectors": "4.4.0-beta-24721-02",
-    "System.Reflection": "4.4.0-beta-24721-02",
-    "System.Reflection.Extensions": "4.4.0-beta-24721-02",
-    "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
-    "System.Runtime": "4.4.0-beta-24721-02",
-    "System.Runtime.Extensions": "4.4.0-beta-24721-02",
-    "System.Runtime.Numerics": "4.4.0-beta-24721-02",
-    "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
-    "System.Threading": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks": "4.4.0-beta-24721-02",
-    "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
-    "System.Diagnostics.Process": "4.4.0-beta-24721-02",
-    "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
-    "System.Xml.XPath": "4.4.0-beta-24721-02",
-    "System.Xml.XPath.XmlDocument": "4.4.0-beta-24721-02",
+    "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+    "System.Collections.NonGeneric": "4.4.0-beta-24810-02",
+    "System.Console": "4.4.0-beta-24810-02",
+    "System.IO.FileSystem": "4.4.0-beta-24810-02",
+    "System.Linq": "4.4.0-beta-24810-02",
+    "System.Linq.Expressions": "4.4.0-beta-24810-02",
+    "System.Numerics.Vectors": "4.4.0-beta-24810-02",
+    "System.Reflection": "4.4.0-beta-24810-02",
+    "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+    "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+    "System.Runtime": "4.4.0-beta-24810-02",
+    "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+    "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+    "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+    "System.Threading": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks": "4.4.0-beta-24810-02",
+    "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+    "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+    "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+    "System.Xml.XPath": "4.4.0-beta-24810-02",
+    "System.Xml.XPath.XmlDocument": "4.4.0-beta-24810-02",
     "xunit": "2.2.0-beta2-build3300",
     "xunit.console.netcore": "1.0.2-prerelease-00177",
     "xunit.runner.utility": "2.2.0-beta2-build3300"