summaryrefslogtreecommitdiff
path: root/src/mscorlib/src
diff options
context:
space:
mode:
Diffstat (limited to 'src/mscorlib/src')
-rw-r--r--src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs7
-rw-r--r--src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs198
-rw-r--r--src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs6
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Registry.cs24
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryKey.cs296
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.cs43
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs4
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs3
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs12
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs6
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs4
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.cs4
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs2
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs25
-rw-r--r--src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs8
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Win32Native.cs115
-rw-r--r--src/mscorlib/src/System.Private.CoreLib.txt1251
-rw-r--r--src/mscorlib/src/System/Action.cs43
-rw-r--r--src/mscorlib/src/System/Activator.cs136
-rw-r--r--src/mscorlib/src/System/AggregateException.cs17
-rw-r--r--src/mscorlib/src/System/AppContext/AppContext.cs56
-rw-r--r--src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs12
-rw-r--r--src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs6
-rw-r--r--src/mscorlib/src/System/AppContext/AppContextSwitches.cs30
-rw-r--r--src/mscorlib/src/System/AppDomain.cs2188
-rw-r--r--src/mscorlib/src/System/AppDomainManager.cs171
-rw-r--r--src/mscorlib/src/System/AppDomainSetup.cs469
-rw-r--r--src/mscorlib/src/System/ApplicationId.cs6
-rw-r--r--src/mscorlib/src/System/ArgIterator.cs11
-rw-r--r--src/mscorlib/src/System/ArgumentException.cs3
-rw-r--r--src/mscorlib/src/System/ArgumentNullException.cs1
-rw-r--r--src/mscorlib/src/System/ArgumentOutOfRangeException.cs3
-rw-r--r--src/mscorlib/src/System/Array.cs433
-rw-r--r--src/mscorlib/src/System/ArraySegment.cs96
-rw-r--r--src/mscorlib/src/System/Attribute.cs137
-rw-r--r--src/mscorlib/src/System/BCLDebug.cs32
-rw-r--r--src/mscorlib/src/System/BadImageFormatException.cs3
-rw-r--r--src/mscorlib/src/System/BitConverter.cs61
-rw-r--r--src/mscorlib/src/System/Boolean.cs2
-rw-r--r--src/mscorlib/src/System/Buffer.cs50
-rw-r--r--src/mscorlib/src/System/ByReference.cs31
-rw-r--r--src/mscorlib/src/System/Byte.cs4
-rw-r--r--src/mscorlib/src/System/CLRConfig.cs2
-rw-r--r--src/mscorlib/src/System/CfgParser.cs14
-rw-r--r--src/mscorlib/src/System/Char.cs94
-rw-r--r--src/mscorlib/src/System/Collections/ArrayList.cs179
-rw-r--r--src/mscorlib/src/System/Collections/BitArray.cs524
-rw-r--r--src/mscorlib/src/System/Collections/CollectionBase.cs10
-rw-r--r--src/mscorlib/src/System/Collections/Comparer.cs5
-rw-r--r--src/mscorlib/src/System/Collections/CompatibleComparer.cs2
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs216
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs21
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs91
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs2
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs104
-rw-r--r--src/mscorlib/src/System/Collections/DictionaryEntry.cs7
-rw-r--r--src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs20
-rw-r--r--src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs452
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Comparer.cs18
-rw-r--r--src/mscorlib/src/System/Collections/Generic/DebugView.cs2
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Dictionary.cs101
-rw-r--r--src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs171
-rw-r--r--src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs17
-rw-r--r--src/mscorlib/src/System/Collections/Generic/List.cs116
-rw-r--r--src/mscorlib/src/System/Collections/Hashtable.cs187
-rw-r--r--src/mscorlib/src/System/Collections/ListDictionaryInternal.cs30
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/Collection.cs8
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs4
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs8
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs14
-rw-r--r--src/mscorlib/src/System/Collections/SortedList.cs39
-rw-r--r--src/mscorlib/src/System/Collections/Stack.cs13
-rw-r--r--src/mscorlib/src/System/CompatibilitySwitches.cs72
-rw-r--r--src/mscorlib/src/System/ContextBoundObject.cs24
-rw-r--r--src/mscorlib/src/System/ContextStaticAttribute.cs32
-rw-r--r--src/mscorlib/src/System/Convert.cs80
-rw-r--r--src/mscorlib/src/System/Currency.cs2
-rw-r--r--src/mscorlib/src/System/CurrentTimeZone.cs276
-rw-r--r--src/mscorlib/src/System/DBNull.cs1
-rw-r--r--src/mscorlib/src/System/DateTime.cs86
-rw-r--r--src/mscorlib/src/System/DateTimeOffset.cs34
-rw-r--r--src/mscorlib/src/System/Decimal.cs60
-rw-r--r--src/mscorlib/src/System/DefaultBinder.cs26
-rw-r--r--src/mscorlib/src/System/Delegate.cs107
-rw-r--r--src/mscorlib/src/System/DelegateSerializationHolder.cs29
-rw-r--r--src/mscorlib/src/System/Diagnostics/Assert.cs18
-rw-r--r--src/mscorlib/src/System/Diagnostics/AssertFilter.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs19
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs62
-rw-r--r--src/mscorlib/src/System/Diagnostics/Debugger.cs9
-rw-r--r--src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs20
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs13
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs66
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs465
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs4
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs9
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs7
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs3
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs18
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs10
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs6
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs4
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs28
-rw-r--r--src/mscorlib/src/System/Diagnostics/LogSwitch.cs7
-rw-r--r--src/mscorlib/src/System/Diagnostics/Stackframe.cs23
-rw-r--r--src/mscorlib/src/System/Diagnostics/Stacktrace.cs79
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs30
-rw-r--r--src/mscorlib/src/System/Diagnostics/log.cs5
-rw-r--r--src/mscorlib/src/System/Double.cs8
-rw-r--r--src/mscorlib/src/System/Empty.cs3
-rw-r--r--src/mscorlib/src/System/Enum.cs174
-rw-r--r--src/mscorlib/src/System/Environment.cs1154
-rw-r--r--src/mscorlib/src/System/Exception.cs88
-rw-r--r--src/mscorlib/src/System/FormattableString.cs2
-rw-r--r--src/mscorlib/src/System/GC.cs172
-rw-r--r--src/mscorlib/src/System/Globalization/Calendar.cs18
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarData.cs6
-rw-r--r--src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs17
-rw-r--r--src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs66
-rw-r--r--src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.cs171
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.cs445
-rw-r--r--src/mscorlib/src/System/Globalization/CultureInfo.cs167
-rw-r--r--src/mscorlib/src/System/Globalization/CultureNotFoundException.cs3
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormat.cs134
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs248
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs3
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeParse.cs90
-rw-r--r--src/mscorlib/src/System/Globalization/DaylightTime.cs23
-rw-r--r--src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs26
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingDataItem.cs7
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs9
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingTable.cs16
-rw-r--r--src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs8
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendar.cs50
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs24
-rw-r--r--src/mscorlib/src/System/Globalization/HebrewCalendar.cs31
-rw-r--r--src/mscorlib/src/System/Globalization/HebrewNumber.cs3
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.cs24
-rw-r--r--src/mscorlib/src/System/Globalization/IdnMapping.cs156
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.cs5
-rw-r--r--src/mscorlib/src/System/Globalization/JulianCalendar.cs18
-rw-r--r--src/mscorlib/src/System/Globalization/KoreanCalendar.cs2
-rw-r--r--src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/NumberFormatInfo.cs66
-rw-r--r--src/mscorlib/src/System/Globalization/PersianCalendar.cs37
-rw-r--r--src/mscorlib/src/System/Globalization/RegionInfo.cs200
-rw-r--r--src/mscorlib/src/System/Globalization/SortKey.cs7
-rw-r--r--src/mscorlib/src/System/Globalization/StringInfo.cs29
-rw-r--r--src/mscorlib/src/System/Globalization/TaiwanCalendar.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/TextElementEnumerator.cs7
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.cs77
-rw-r--r--src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs2
-rw-r--r--src/mscorlib/src/System/Globalization/TimeSpanFormat.cs30
-rw-r--r--src/mscorlib/src/System/Globalization/TimeSpanParse.cs33
-rw-r--r--src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs31
-rw-r--r--src/mscorlib/src/System/Guid.cs37
-rw-r--r--src/mscorlib/src/System/IAppDomain.cs246
-rw-r--r--src/mscorlib/src/System/IAppDomainPauseManager.cs15
-rw-r--r--src/mscorlib/src/System/IO/BinaryReader.cs46
-rw-r--r--src/mscorlib/src/System/IO/BinaryWriter.cs37
-rw-r--r--src/mscorlib/src/System/IO/BufferedStream.cs1320
-rw-r--r--src/mscorlib/src/System/IO/Directory.cs642
-rw-r--r--src/mscorlib/src/System/IO/DirectoryInfo.cs265
-rw-r--r--src/mscorlib/src/System/IO/DriveInfo.cs281
-rw-r--r--src/mscorlib/src/System/IO/EncodingCache.cs (renamed from src/mscorlib/src/System/Runtime/CompilerServices/IsPinned.cs)8
-rw-r--r--src/mscorlib/src/System/IO/File.cs658
-rw-r--r--src/mscorlib/src/System/IO/FileAttributes.cs20
-rw-r--r--src/mscorlib/src/System/IO/FileInfo.cs207
-rw-r--r--src/mscorlib/src/System/IO/FileLoadException.cs14
-rw-r--r--src/mscorlib/src/System/IO/FileNotFoundException.cs11
-rw-r--r--src/mscorlib/src/System/IO/FileSecurityState.cs133
-rw-r--r--src/mscorlib/src/System/IO/FileSecurityStateAccess.cs32
-rw-r--r--src/mscorlib/src/System/IO/FileStream.cs2695
-rw-r--r--src/mscorlib/src/System/IO/FileSystemEnumerable.cs185
-rw-r--r--src/mscorlib/src/System/IO/FileSystemInfo.cs137
-rw-r--r--src/mscorlib/src/System/IO/LongPathHelper.cs521
-rw-r--r--src/mscorlib/src/System/IO/MemoryStream.cs112
-rw-r--r--src/mscorlib/src/System/IO/Path.cs1435
-rw-r--r--src/mscorlib/src/System/IO/PathHelper.cs448
-rw-r--r--src/mscorlib/src/System/IO/PathInternal.cs806
-rw-r--r--src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs6
-rw-r--r--src/mscorlib/src/System/IO/Stream.cs144
-rw-r--r--src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs46
-rw-r--r--src/mscorlib/src/System/IO/StreamReader.cs100
-rw-r--r--src/mscorlib/src/System/IO/StreamWriter.cs175
-rw-r--r--src/mscorlib/src/System/IO/StringReader.cs187
-rw-r--r--src/mscorlib/src/System/IO/StringWriter.cs196
-rw-r--r--src/mscorlib/src/System/IO/TextReader.cs36
-rw-r--r--src/mscorlib/src/System/IO/TextWriter.cs37
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs215
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs187
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs9
-rw-r--r--src/mscorlib/src/System/IO/__DebugOutputTextWriter.cs76
-rw-r--r--src/mscorlib/src/System/IO/__Error.cs12
-rw-r--r--src/mscorlib/src/System/Int16.cs3
-rw-r--r--src/mscorlib/src/System/Int32.cs4
-rw-r--r--src/mscorlib/src/System/Int64.cs4
-rw-r--r--src/mscorlib/src/System/IntPtr.cs27
-rw-r--r--src/mscorlib/src/System/Internal.cs19
-rw-r--r--src/mscorlib/src/System/InvalidTimeZoneException.cs12
-rw-r--r--src/mscorlib/src/System/Lazy.cs23
-rw-r--r--src/mscorlib/src/System/LowLevelConsole.cs3
-rw-r--r--src/mscorlib/src/System/MarshalByRefObject.cs245
-rw-r--r--src/mscorlib/src/System/Math.cs191
-rw-r--r--src/mscorlib/src/System/MathF.cs253
-rw-r--r--src/mscorlib/src/System/MissingFieldException.cs1
-rw-r--r--src/mscorlib/src/System/MissingMemberException.cs5
-rw-r--r--src/mscorlib/src/System/MissingMethodException.cs1
-rw-r--r--src/mscorlib/src/System/MulticastDelegate.cs40
-rw-r--r--src/mscorlib/src/System/NotFiniteNumberException.cs3
-rw-r--r--src/mscorlib/src/System/Nullable.cs2
-rw-r--r--src/mscorlib/src/System/Number.cs191
-rw-r--r--src/mscorlib/src/System/Numerics/Hashing/HashHelpers.cs19
-rw-r--r--src/mscorlib/src/System/Object.cs48
-rw-r--r--src/mscorlib/src/System/ObjectDisposedException.cs1
-rw-r--r--src/mscorlib/src/System/OleAutBinder.cs21
-rw-r--r--src/mscorlib/src/System/OperatingSystem.cs7
-rw-r--r--src/mscorlib/src/System/ParseNumbers.cs8
-rw-r--r--src/mscorlib/src/System/Progress.cs4
-rw-r--r--src/mscorlib/src/System/Random.cs74
-rw-r--r--src/mscorlib/src/System/ReadOnlySpan.cs397
-rw-r--r--src/mscorlib/src/System/Reflection/Assembly.cs1048
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyAttributes.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyName.cs274
-rw-r--r--src/mscorlib/src/System/Reflection/Associates.cs9
-rw-r--r--src/mscorlib/src/System/Reflection/ComInterfaces.cs572
-rw-r--r--src/mscorlib/src/System/Reflection/ConstructorInfo.cs145
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttribute.cs168
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs30
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs1145
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs6
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs40
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs173
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs61
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs143
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs69
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs224
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs30
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs47
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs54
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FlowControl.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs111
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs136
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs22
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs165
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs489
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs6
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/Opcode.cs118
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OperandType.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs35
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs49
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs69
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SymbolType.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs324
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs13
-rw-r--r--src/mscorlib/src/System/Reflection/EventInfo.cs55
-rw-r--r--src/mscorlib/src/System/Reflection/FieldInfo.cs98
-rw-r--r--src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs23
-rw-r--r--src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/LoaderAllocator.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/MdConstant.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/MdImport.cs55
-rw-r--r--src/mscorlib/src/System/Reflection/MemberInfo.cs31
-rw-r--r--src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs6
-rw-r--r--src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBase.cs50
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBody.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/MethodInfo.cs164
-rw-r--r--src/mscorlib/src/System/Reflection/Missing.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/Module.cs158
-rw-r--r--src/mscorlib/src/System/Reflection/ParameterInfo.cs90
-rw-r--r--src/mscorlib/src/System/Reflection/Pointer.cs14
-rw-r--r--src/mscorlib/src/System/Reflection/PropertyInfo.cs51
-rw-r--r--src/mscorlib/src/System/Reflection/ReflectionContext.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs115
-rw-r--r--src/mscorlib/src/System/Reflection/TargetException.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/TargetInvocationException.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/TargetParameterCountException.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/TypeDelegator.cs5
-rw-r--r--src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs31
-rw-r--r--src/mscorlib/src/System/Resources/IResourceGroveler.cs5
-rw-r--r--src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs10
-rw-r--r--src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs153
-rw-r--r--src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs4
-rw-r--r--src/mscorlib/src/System/Resources/ResourceFallbackManager.cs14
-rw-r--r--src/mscorlib/src/System/Resources/ResourceManager.cs306
-rw-r--r--src/mscorlib/src/System/Resources/ResourceReader.cs71
-rw-r--r--src/mscorlib/src/System/Resources/ResourceSet.cs21
-rw-r--r--src/mscorlib/src/System/Resources/RuntimeResourceSet.cs9
-rw-r--r--src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs2
-rw-r--r--src/mscorlib/src/System/Resources/__FastResourceComparer.cs14
-rw-r--r--src/mscorlib/src/System/RtType.cs861
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs58
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CallingConvention.cs30
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs905
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/HasCopySemanticsAttribute.cs14
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs26
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IUnknownConstantAttribute.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsBoxed.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsByValue.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsConst.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsCopyConstructed.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsExplicitlyDereferenced.cs22
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsImplicitlyDereferenced.cs22
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsJitIntrinsic.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsLong.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsSignUnspecifiedByte.cs16
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsUdtReturn.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/NativeCppClassAttribute.cs16
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RequiredAttributeAttribute.cs26
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs92
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ScopelessEnumAttribute.cs14
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs23
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs80
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs52
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs41
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/GcSettings.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/COMException.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs16
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs5
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs21
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/IException.cs48
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs622
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/NativeBuffer.cs175
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs52
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs57
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs28
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeHeapHandle.cs115
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/StringBuffer.cs402
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs67
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/TypeLibConverter.cs595
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Variant.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs30
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs29
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs19
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs15
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs19
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs5
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs14
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs23
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs14
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs24
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs52
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs5
-rw-r--r--src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs92
-rw-r--r--src/mscorlib/src/System/Runtime/MemoryFailPoint.cs16
-rw-r--r--src/mscorlib/src/System/Runtime/ProfileOptimization.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs42
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs76
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs446
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs36
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs98
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs15
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/BinaryCompatibility.cs485
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs5
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/ComponentGuaranteesAttribute.cs44
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/ResourceAttributes.cs237
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs2
-rw-r--r--src/mscorlib/src/System/RuntimeHandles.cs273
-rw-r--r--src/mscorlib/src/System/SByte.cs3
-rw-r--r--src/mscorlib/src/System/Security/AccessControl/Enums.cs6
-rw-r--r--src/mscorlib/src/System/Security/Attributes.cs11
-rw-r--r--src/mscorlib/src/System/Security/BuiltInPermissionSets.cs103
-rw-r--r--src/mscorlib/src/System/Security/CodeAccessPermission.cs69
-rw-r--r--src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs468
-rw-r--r--src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs31
-rw-r--r--src/mscorlib/src/System/Security/HostProtectionException.cs5
-rw-r--r--src/mscorlib/src/System/Security/HostSecurityManager.cs131
-rw-r--r--src/mscorlib/src/System/Security/IEvidenceFactory.cs15
-rw-r--r--src/mscorlib/src/System/Security/ISecurityEncodable.cs18
-rw-r--r--src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs17
-rw-r--r--src/mscorlib/src/System/Security/NamedPermissionSet.cs202
-rw-r--r--src/mscorlib/src/System/Security/PermissionListSet.cs29
-rw-r--r--src/mscorlib/src/System/Security/PermissionSet.cs1100
-rw-r--r--src/mscorlib/src/System/Security/PermissionSetEnumerator.cs14
-rw-r--r--src/mscorlib/src/System/Security/PermissionSetTriple.cs20
-rw-r--r--src/mscorlib/src/System/Security/PermissionToken.cs202
-rw-r--r--src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs60
-rw-r--r--src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs33
-rw-r--r--src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs304
-rw-r--r--src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs16
-rw-r--r--src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs34
-rw-r--r--src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs13
-rw-r--r--src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs91
-rw-r--r--src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs314
-rw-r--r--src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs39
-rw-r--r--src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs131
-rw-r--r--src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs96
-rw-r--r--src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs108
-rw-r--r--src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs90
-rw-r--r--src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs2
-rw-r--r--src/mscorlib/src/System/Security/Permissions/UIPermission.cs44
-rw-r--r--src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs111
-rw-r--r--src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs101
-rw-r--r--src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs72
-rw-r--r--src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs573
-rw-r--r--src/mscorlib/src/System/Security/Policy/Evidence.cs1865
-rw-r--r--src/mscorlib/src/System/Security/Policy/EvidenceBase.cs31
-rw-r--r--src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs20
-rw-r--r--src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs1
-rw-r--r--src/mscorlib/src/System/Security/Policy/PolicyStatement.cs302
-rw-r--r--src/mscorlib/src/System/Security/Policy/Site.cs29
-rw-r--r--src/mscorlib/src/System/Security/Policy/StrongName.cs59
-rw-r--r--src/mscorlib/src/System/Security/Policy/URL.cs29
-rw-r--r--src/mscorlib/src/System/Security/Policy/Zone.cs66
-rw-r--r--src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs9
-rw-r--r--src/mscorlib/src/System/Security/SafeSecurityHandles.cs16
-rw-r--r--src/mscorlib/src/System/Security/SecurityContext.cs238
-rw-r--r--src/mscorlib/src/System/Security/SecurityElement.cs100
-rw-r--r--src/mscorlib/src/System/Security/SecurityException.cs608
-rw-r--r--src/mscorlib/src/System/Security/SecurityManager.cs524
-rw-r--r--src/mscorlib/src/System/Security/SecurityRuntime.cs156
-rw-r--r--src/mscorlib/src/System/Security/SecurityState.cs10
-rw-r--r--src/mscorlib/src/System/Security/Util/Config.cs48
-rw-r--r--src/mscorlib/src/System/Security/Util/Hex.cs2
-rw-r--r--src/mscorlib/src/System/Security/Util/StringExpressionSet.cs41
-rw-r--r--src/mscorlib/src/System/Security/Util/TokenBasedSet.cs32
-rw-r--r--src/mscorlib/src/System/Security/Util/URLString.cs17
-rw-r--r--src/mscorlib/src/System/Security/Util/XMLUtil.cs272
-rw-r--r--src/mscorlib/src/System/Security/securestring.cs31
-rw-r--r--src/mscorlib/src/System/SharedStatics.cs64
-rw-r--r--src/mscorlib/src/System/Single.cs16
-rw-r--r--src/mscorlib/src/System/Span.cs477
-rw-r--r--src/mscorlib/src/System/String.Comparison.cs82
-rw-r--r--src/mscorlib/src/System/String.Manipulation.cs475
-rw-r--r--src/mscorlib/src/System/String.Searching.cs36
-rw-r--r--src/mscorlib/src/System/String.cs126
-rw-r--r--src/mscorlib/src/System/StringComparer.cs35
-rw-r--r--src/mscorlib/src/System/StubHelpers.cs161
-rw-r--r--src/mscorlib/src/System/Text/ASCIIEncoding.cs77
-rw-r--r--src/mscorlib/src/System/Text/BaseCodePageEncoding.cs30
-rw-r--r--src/mscorlib/src/System/Text/CodePageEncoding.cs13
-rw-r--r--src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs102
-rw-r--r--src/mscorlib/src/System/Text/Decoder.cs32
-rw-r--r--src/mscorlib/src/System/Text/DecoderBestFitFallback.cs9
-rw-r--r--src/mscorlib/src/System/Text/DecoderFallback.cs13
-rw-r--r--src/mscorlib/src/System/Text/DecoderNLS.cs43
-rw-r--r--src/mscorlib/src/System/Text/DecoderReplacementFallback.cs9
-rw-r--r--src/mscorlib/src/System/Text/EUCJPEncoding.cs3
-rw-r--r--src/mscorlib/src/System/Text/Encoder.cs32
-rw-r--r--src/mscorlib/src/System/Text/EncoderBestFitFallback.cs12
-rw-r--r--src/mscorlib/src/System/Text/EncoderExceptionFallback.cs6
-rw-r--r--src/mscorlib/src/System/Text/EncoderFallback.cs8
-rw-r--r--src/mscorlib/src/System/Text/EncoderNLS.cs43
-rw-r--r--src/mscorlib/src/System/Text/EncoderReplacementFallback.cs10
-rw-r--r--src/mscorlib/src/System/Text/Encoding.cs222
-rw-r--r--src/mscorlib/src/System/Text/EncodingForwarder.cs98
-rw-r--r--src/mscorlib/src/System/Text/EncodingNLS.cs4
-rw-r--r--src/mscorlib/src/System/Text/EncodingProvider.cs2
-rw-r--r--src/mscorlib/src/System/Text/GB18030Encoding.cs60
-rw-r--r--src/mscorlib/src/System/Text/ISCIIEncoding.cs88
-rw-r--r--src/mscorlib/src/System/Text/ISO2022Encoding.cs74
-rw-r--r--src/mscorlib/src/System/Text/Latin1Encoding.cs66
-rw-r--r--src/mscorlib/src/System/Text/MLangCodePageEncoding.cs19
-rw-r--r--src/mscorlib/src/System/Text/Normalization.Unix.cs123
-rw-r--r--src/mscorlib/src/System/Text/Normalization.Windows.cs286
-rw-r--r--src/mscorlib/src/System/Text/Normalization.cs314
-rw-r--r--src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs93
-rw-r--r--src/mscorlib/src/System/Text/StringBuilder.cs309
-rw-r--r--src/mscorlib/src/System/Text/SurrogateEncoder.cs7
-rw-r--r--src/mscorlib/src/System/Text/UTF32Encoding.cs71
-rw-r--r--src/mscorlib/src/System/Text/UTF7Encoding.cs55
-rw-r--r--src/mscorlib/src/System/Text/UTF8Encoding.cs96
-rw-r--r--src/mscorlib/src/System/Text/UnicodeEncoding.cs92
-rw-r--r--src/mscorlib/src/System/Threading/AsyncLocal.cs387
-rw-r--r--src/mscorlib/src/System/Threading/AutoResetEvent.cs1
-rw-r--r--src/mscorlib/src/System/Threading/CancellationToken.cs14
-rw-r--r--src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs1
-rw-r--r--src/mscorlib/src/System/Threading/CancellationTokenSource.cs37
-rw-r--r--src/mscorlib/src/System/Threading/CountdownEvent.cs23
-rw-r--r--src/mscorlib/src/System/Threading/EventWaitHandle.cs69
-rw-r--r--src/mscorlib/src/System/Threading/ExecutionContext.cs1222
-rw-r--r--src/mscorlib/src/System/Threading/Interlocked.cs17
-rw-r--r--src/mscorlib/src/System/Threading/LazyInitializer.cs4
-rw-r--r--src/mscorlib/src/System/Threading/LockRecursionException.cs3
-rw-r--r--src/mscorlib/src/System/Threading/ManualResetEvent.cs1
-rw-r--r--src/mscorlib/src/System/Threading/ManualResetEventSlim.cs33
-rw-r--r--src/mscorlib/src/System/Threading/Monitor.cs26
-rw-r--r--src/mscorlib/src/System/Threading/Mutex.cs208
-rw-r--r--src/mscorlib/src/System/Threading/Overlapped.cs42
-rw-r--r--src/mscorlib/src/System/Threading/ReaderWriterLock.cs36
-rw-r--r--src/mscorlib/src/System/Threading/Semaphore.cs35
-rw-r--r--src/mscorlib/src/System/Threading/SemaphoreFullException.cs3
-rw-r--r--src/mscorlib/src/System/Threading/SemaphoreSlim.cs50
-rw-r--r--src/mscorlib/src/System/Threading/SpinLock.cs110
-rw-r--r--src/mscorlib/src/System/Threading/SpinWait.cs18
-rw-r--r--src/mscorlib/src/System/Threading/SynchronizationContext.cs90
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs4
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs16
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs42
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs148
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/Parallel.cs229
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs7
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs9
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs12
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs12
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/Task.cs229
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs6
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs64
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs36
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs100
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs21
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs5
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs7
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/future.cs27
-rw-r--r--src/mscorlib/src/System/Threading/Thread.cs633
-rw-r--r--src/mscorlib/src/System/Threading/ThreadAbortException.cs1
-rw-r--r--src/mscorlib/src/System/Threading/ThreadLocal.cs17
-rw-r--r--src/mscorlib/src/System/Threading/ThreadPool.cs230
-rw-r--r--src/mscorlib/src/System/Threading/Timer.cs79
-rw-r--r--src/mscorlib/src/System/Threading/Volatile.cs6
-rw-r--r--src/mscorlib/src/System/Threading/WaitHandle.cs83
-rw-r--r--src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs4
-rw-r--r--src/mscorlib/src/System/Threading/WaitHandleExtensions.cs46
-rw-r--r--src/mscorlib/src/System/ThrowHelper.cs211
-rw-r--r--src/mscorlib/src/System/TimeSpan.cs28
-rw-r--r--src/mscorlib/src/System/TimeZone.cs4
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.cs641
-rw-r--r--src/mscorlib/src/System/TimeZoneNotFoundException.cs3
-rw-r--r--src/mscorlib/src/System/Tuple.cs23
-rw-r--r--src/mscorlib/src/System/Type.cs144
-rw-r--r--src/mscorlib/src/System/TypeInitializationException.cs1
-rw-r--r--src/mscorlib/src/System/TypeLoadException.cs9
-rw-r--r--src/mscorlib/src/System/TypeNameParser.cs30
-rw-r--r--src/mscorlib/src/System/TypedReference.cs10
-rw-r--r--src/mscorlib/src/System/UInt16.cs4
-rw-r--r--src/mscorlib/src/System/UInt32.cs4
-rw-r--r--src/mscorlib/src/System/UInt64.cs4
-rw-r--r--src/mscorlib/src/System/UIntPtr.cs25
-rw-r--r--src/mscorlib/src/System/UnSafeCharBuffer.cs57
-rw-r--r--src/mscorlib/src/System/UnhandledExceptionEventHandler.cs3
-rw-r--r--src/mscorlib/src/System/UnitySerializationHolder.cs4
-rw-r--r--src/mscorlib/src/System/ValueType.cs4
-rw-r--r--src/mscorlib/src/System/Variant.cs27
-rw-r--r--src/mscorlib/src/System/Version.cs164
-rw-r--r--src/mscorlib/src/System/WeakReference.cs23
-rw-r--r--src/mscorlib/src/System/WeakReferenceOfT.cs10
-rw-r--r--src/mscorlib/src/System/_LocalDataStore.cs6
-rw-r--r--src/mscorlib/src/System/_LocalDataStoreMgr.cs13
-rw-r--r--src/mscorlib/src/System/__ComObject.cs13
-rw-r--r--src/mscorlib/src/System/cominterfaces.cs34
-rw-r--r--src/mscorlib/src/System/mda.cs11
-rw-r--r--src/mscorlib/src/mscorlib.Friends.cs2
-rw-r--r--src/mscorlib/src/mscorlib.txt3494
611 files changed, 12247 insertions, 52382 deletions
diff --git a/src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs b/src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs
index 28104683c7..b22310eacb 100644
--- a/src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs
+++ b/src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System;
+using System.Collections;
namespace Internal.Runtime.Augments
{
@@ -17,5 +18,11 @@ namespace Internal.Runtime.Augments
public static bool HasShutdownStarted => Environment.HasShutdownStarted;
public static string StackTrace => Environment.StackTrace;
public static int TickCount => Environment.TickCount;
+ public static string GetEnvironmentVariable(string variable) => Environment.GetEnvironmentVariable(variable);
+ public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) => Environment.GetEnvironmentVariable(variable, target);
+ public static IDictionary GetEnvironmentVariables() => Environment.GetEnvironmentVariables();
+ public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target) => Environment.GetEnvironmentVariables(target);
+ public static void SetEnvironmentVariable(string variable, string value) => Environment.SetEnvironmentVariable(variable, value);
+ public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) => Environment.SetEnvironmentVariable(variable, value, target);
}
}
diff --git a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
new file mode 100644
index 0000000000..3aafe01a2c
--- /dev/null
+++ b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
@@ -0,0 +1,198 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Threading;
+
+namespace Internal.Runtime.Augments
+{
+ public class RuntimeThread : CriticalFinalizerObject
+ {
+ public static RuntimeThread Create(ThreadStart start) => new Thread(start);
+ public static RuntimeThread Create(ThreadStart start, int maxStackSize) => new Thread(start, maxStackSize);
+ public static RuntimeThread Create(ParameterizedThreadStart start) => new Thread(start);
+ public static RuntimeThread Create(ParameterizedThreadStart start, int maxStackSize) => new Thread(start, maxStackSize);
+
+ private Thread AsThread()
+ {
+ Debug.Assert(this is Thread);
+ return (Thread)this;
+ }
+
+ public static RuntimeThread CurrentThread => Thread.CurrentThread;
+
+ /*=========================================================================
+ ** Returns true if the thread has been started and is not dead.
+ =========================================================================*/
+ public extern bool IsAlive
+ {
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ get;
+ }
+
+ /*=========================================================================
+ ** 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 bool IsBackground
+ {
+ get { return IsBackgroundNative(); }
+ set { SetBackgroundNative(value); }
+ }
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private extern bool IsBackgroundNative();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private extern void SetBackgroundNative(bool isBackground);
+
+ /*=========================================================================
+ ** Returns true if the thread is a threadpool thread.
+ =========================================================================*/
+ public extern bool IsThreadPoolThread
+ {
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ get;
+ }
+
+ public int ManagedThreadId => AsThread().ManagedThreadId;
+ public string Name { get { return AsThread().Name; } set { AsThread().Name = value; } }
+
+ /*=========================================================================
+ ** Returns the priority of the thread.
+ **
+ ** Exceptions: ThreadStateException if the thread is dead.
+ =========================================================================*/
+ public ThreadPriority Priority
+ {
+ get { return (ThreadPriority)GetPriorityNative(); }
+ set { SetPriorityNative((int)value); }
+ }
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private extern int GetPriorityNative();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private extern void SetPriorityNative(int priority);
+
+ /*=========================================================================
+ ** Return the thread state as a consistent set of bits. This is more
+ ** general then IsAlive or IsBackground.
+ =========================================================================*/
+ public ThreadState ThreadState
+ {
+ get { return (ThreadState)GetThreadStateNative(); }
+ }
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private extern int GetThreadStateNative();
+
+ public ApartmentState GetApartmentState()
+ {
+#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
+ return (ApartmentState)GetApartmentStateNative();
+#else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
+ Debug.Assert(false); // the Thread class in CoreFX should have handled this case
+ return ApartmentState.MTA;
+#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
+ }
+
+ /*=========================================================================
+ ** An unstarted thread can be marked to indicate that it will host a
+ ** single-threaded or multi-threaded apartment.
+ =========================================================================*/
+ public bool TrySetApartmentState(ApartmentState state)
+ {
+#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
+ return SetApartmentStateHelper(state, false);
+#else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
+ 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
+ internal bool SetApartmentStateHelper(ApartmentState state, bool fireMDAOnMismatch)
+ {
+ ApartmentState retState = (ApartmentState)SetApartmentStateNative((int)state, fireMDAOnMismatch);
+
+ // Special case where we pass in Unknown and get back MTA.
+ // Once we CoUninitialize the thread, the OS will still
+ // report the thread as implicitly in the MTA if any
+ // other thread in the process is CoInitialized.
+ if ((state == System.Threading.ApartmentState.Unknown) && (retState == System.Threading.ApartmentState.MTA))
+ return true;
+
+ if (retState != state)
+ return false;
+
+ return true;
+ }
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern int GetApartmentStateNative();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern int SetApartmentStateNative(int state, bool fireMDAOnMismatch);
+#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
+
+#if FEATURE_COMINTEROP
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ public extern void DisableComObjectEagerCleanup();
+#else // !FEATURE_COMINTEROP
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+ public void DisableComObjectEagerCleanup()
+ {
+ Debug.Assert(false); // the Thread class in CoreFX should have handled this case
+ }
+#endif // FEATURE_COMINTEROP
+
+ /*=========================================================================
+ ** 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.
+ =========================================================================*/
+#pragma warning disable 618 // obsolete types: SecurityPermissionAttribute, SecurityAction
+#pragma warning restore 618 // obsolete types: SecurityPermissionAttribute, SecurityAction
+ public void Interrupt() => InterruptInternal();
+
+ // Internal helper (since we can't place security demands on
+ // ecalls/fcalls).
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private extern void InterruptInternal();
+
+ /*=========================================================================
+ ** 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.
+ =========================================================================*/
+ public void Join() => JoinInternal(Timeout.Infinite);
+
+ public bool Join(int millisecondsTimeout) => JoinInternal(millisecondsTimeout);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private extern bool JoinInternal(int millisecondsTimeout);
+
+ public static void Sleep(int millisecondsTimeout) => Thread.Sleep(millisecondsTimeout);
+ public static void SpinWait(int iterations) => Thread.SpinWait(iterations);
+ public static bool Yield() => Thread.Yield();
+
+ public void Start() => AsThread().Start();
+ public void Start(object parameter) => AsThread().Start(parameter);
+ }
+}
diff --git a/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs b/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs
index 118c69b8b7..6c2c6e9630 100644
--- a/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs
+++ b/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs
@@ -73,13 +73,12 @@ 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)
- throw new ArgumentNullException("targetClass");
+ throw new ArgumentNullException(nameof(targetClass));
if (culture == null)
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
Variant result = new Variant ();
ChangeTypeEx(ref result, ref source,
#if FEATURE_USE_LCID
@@ -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);
diff --git a/src/mscorlib/src/Microsoft/Win32/Registry.cs b/src/mscorlib/src/Microsoft/Win32/Registry.cs
index 4faf29da7f..3ee5f4648b 100644
--- a/src/mscorlib/src/Microsoft/Win32/Registry.cs
+++ b/src/mscorlib/src/Microsoft/Win32/Registry.cs
@@ -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,10 +69,9 @@ 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("keyName");
+ throw new ArgumentNullException(nameof(keyName));
}
string basekeyName;
@@ -116,13 +103,8 @@ 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", "keyName"));
+ throw new ArgumentException(Environment.GetResourceString("Arg_RegInvalidKeyName", nameof(keyName)));
}
if( i == -1 || i == keyName.Length) {
subKeyName = string.Empty;
@@ -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);
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
index dcf31dc60c..ff678f132c 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
@@ -49,15 +49,12 @@
*/
-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
}
/**
@@ -96,13 +90,8 @@ namespace Microsoft.Win32 {
* @security(checkDllCalls=off)
* @security(checkClassLinking=on)
*/
-#if FEATURE_REMOTING
[ComVisible(true)]
public sealed class RegistryKey : MarshalByRefObject, IDisposable
-#else
- [ComVisible(true)]
- public sealed class RegistryKey : IDisposable
-#endif
{
// We could use const here, if C# supported ELEMENT_TYPE_I fully.
@@ -112,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.
@@ -142,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:
@@ -154,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;
@@ -188,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) {
}
@@ -203,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 = "";
@@ -227,7 +207,6 @@ namespace Microsoft.Win32 {
Dispose(true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
private void Dispose(bool disposing) {
if (hkey != null) {
@@ -260,7 +239,6 @@ namespace Microsoft.Win32 {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Flush() {
if (hkey != null) {
if (IsDirty()) {
@@ -269,11 +247,7 @@ namespace Microsoft.Win32 {
}
}
-#if FEATURE_CORECLR
void IDisposable.Dispose()
-#else
- public void Dispose()
-#endif
{
Dispose(true);
}
@@ -314,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)
{
@@ -351,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.
@@ -412,7 +356,6 @@ namespace Microsoft.Win32 {
DeleteSubKey(subkey, true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void DeleteSubKey(String subkey, bool throwOnMissingSubKey) {
ValidateKeyName(subkey);
EnsureWriteable();
@@ -466,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);
@@ -514,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) {
@@ -541,7 +482,7 @@ namespace Microsoft.Win32 {
if (ret!=0) Win32Error(ret, null);
}
else {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);
}
}
@@ -554,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);
@@ -592,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;
@@ -615,7 +553,6 @@ namespace Microsoft.Win32 {
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) {
ValidateKeyView(view);
@@ -645,11 +582,10 @@ 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)
- throw new ArgumentNullException("machineName");
+ throw new ArgumentNullException(nameof(machineName));
int index = (int)hKey & 0x0FFFFFFF;
if (index < 0 || index >= hkeyNames.Length || ((int)hKey & 0xFFFFFFF0) != 0x80000000) {
throw new ArgumentException(Environment.GetResourceString("Arg_RegKeyOutOfRange"));
@@ -687,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();
@@ -722,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();
@@ -805,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);
}
@@ -818,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();
@@ -827,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("handle");
- ValidateKeyView(view);
-
- return new RegistryKey(handle, true /* isWritable */, view);
- }
-#endif
-
- [System.Security.SecurityCritical] // auto-generated
internal int InternalSubKeyCount() {
EnsureNotDisposed();
@@ -939,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();
@@ -988,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;
@@ -1022,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();
@@ -1073,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);
@@ -1094,32 +878,21 @@ 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) {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options), "options");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options), nameof(options));
}
bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames);
CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
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
@@ -1338,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);
@@ -1382,7 +1154,6 @@ namespace Microsoft.Win32 {
}
public String Name {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
EnsureNotDisposed();
return keyName;
@@ -1403,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)
@@ -1414,7 +1184,7 @@ namespace Microsoft.Win32 {
}
if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
- throw new ArgumentException(Environment.GetResourceString("Arg_RegBadKeyKind"), "valueKind");
+ throw new ArgumentException(Environment.GetResourceString("Arg_RegBadKeyKind"), nameof(valueKind));
EnsureWriteable();
@@ -1575,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("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
@@ -1609,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:
@@ -1645,7 +1392,6 @@ namespace Microsoft.Win32 {
}
}
- [SecuritySafeCritical]
internal static void Win32ErrorStatic(int errorCode, String str) {
switch (errorCode) {
case Win32Native.ERROR_ACCESS_DENIED:
@@ -1778,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
@@ -2020,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;
@@ -2035,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()) {
@@ -2134,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;
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.cs
deleted file mode 100644
index ab06347ee4..0000000000
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-** A wrapper for file handles
-**
-**
-===========================================================*/
-
-using System;
-using System.Security;
-using System.Security.Permissions;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
-using System.Runtime.Versioning;
-using Microsoft.Win32;
-
-namespace Microsoft.Win32.SafeHandles {
-
- [System.Security.SecurityCritical] // auto-generated_required
- public sealed class SafeFileHandle: SafeHandleZeroOrMinusOneIsInvalid {
-
- private SafeFileHandle() : base(true)
- {
- }
-
- public SafeFileHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
- SetHandle(preexistingHandle);
- }
-
- [System.Security.SecurityCritical]
- override protected bool ReleaseHandle()
- {
- return Win32Native.CloseHandle(handle);
- }
- }
-}
-
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs
index 5e1b5100bc..cb915fe7c3 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFileMappingHandle.cs
@@ -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);
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs
index b24535f997..219fb77001 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs
@@ -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);
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
index d2ea42b14e..23631987a5 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
@@ -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);
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs
index 3eea2b9937..d6c1577eeb 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLocalAllocHandle.cs
@@ -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;
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
index d0e3f048f2..4f96b81e72 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
@@ -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);
}
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.cs
index 01ec4d2ad8..38a9323c0b 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeViewOfFileHandle.cs
@@ -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))
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
index fa24c96718..0e57136952 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
@@ -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);
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
index 58e0d7ad1d..08ae0955a8 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
@@ -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,9 +81,7 @@ namespace Microsoft.Win32.SafeHandles
}
public override bool IsInvalid {
- [System.Security.SecurityCritical]
get { return handle == new IntPtr(-1); }
}
}
-
}
diff --git a/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs b/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
index 9da9811ee8..19d638d61a 100644
--- a/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
+++ b/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
@@ -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,
diff --git a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
index ebe53f45af..b5b808b424 100644
--- a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
+++ b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
@@ -90,9 +90,6 @@
namespace Microsoft.Win32 {
using System;
using System.Security;
-#if FEATURE_IMPERSONATION
- using System.Security.Principal;
-#endif
using System.Text;
using System.Configuration.Assemblies;
using System.Runtime.Remoting;
@@ -113,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 {
@@ -327,7 +323,7 @@ namespace Microsoft.Win32 {
// } REG_TZI_FORMAT;
//
if (bytes == null || bytes.Length != 44) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidREG_TZI_FORMAT"), "bytes");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidREG_TZI_FORMAT"), nameof(bytes));
}
Bias = BitConverter.ToInt32(bytes, 0);
StandardBias = BitConverter.ToInt32(bytes, 4);
@@ -454,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;
@@ -516,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)");
@@ -802,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.
@@ -910,56 +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);
- // 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);
-
[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);
@@ -988,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;
@@ -1070,7 +1012,6 @@ namespace Microsoft.Win32 {
internal const int FIND_FROMSTART = 0x00400000; // look for value in source, starting at the beginning
internal const int FIND_FROMEND = 0x00800000; // look for value in source, starting at the end
-#if !FEATURE_CORECLR
[StructLayout(LayoutKind.Sequential)]
internal struct NlsVersionInfoEx
{
@@ -1080,7 +1021,6 @@ namespace Microsoft.Win32 {
internal int dwEffectiveId;
internal Guid guidCustomVersion;
}
-#endif
[DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
internal static extern int GetWindowsDirectory([Out]StringBuilder sb, int length);
@@ -1797,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(
@@ -1930,28 +1863,6 @@ namespace Microsoft.Win32 {
[In] bool bInheritHandle,
[In] uint dwOptions);
-#if FEATURE_IMPERSONATION
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- bool DuplicateTokenEx (
- [In] SafeAccessTokenHandle ExistingTokenHandle,
- [In] TokenAccessLevels DesiredAccess,
- [In] IntPtr TokenAttributes,
- [In] SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
- [In] System.Security.Principal.TokenType TokenType,
- [In,Out] ref SafeAccessTokenHandle DuplicateTokenHandle );
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern
- bool DuplicateTokenEx (
- [In] SafeAccessTokenHandle hExistingToken,
- [In] uint dwDesiredAccess,
- [In] IntPtr lpTokenAttributes, // LPSECURITY_ATTRIBUTES
- [In] uint ImpersonationLevel,
- [In] uint TokenType,
- [In,Out] ref SafeAccessTokenHandle phNewToken);
-#endif
[DllImport(
ADVAPI32,
EntryPoint="EqualDomainSid",
@@ -2345,15 +2256,6 @@ namespace Microsoft.Win32 {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern int LsaFreeReturnBuffer(IntPtr handle);
-#if FEATURE_IMPERSONATION
- [DllImport (ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
- internal static extern
- bool OpenProcessToken (
- [In] IntPtr ProcessToken,
- [In] TokenAccessLevels DesiredAccess,
- [Out] out SafeAccessTokenHandle TokenHandle);
-#endif
-
[DllImport(
ADVAPI32,
EntryPoint="SetNamedSecurityInfoW",
@@ -2386,16 +2288,6 @@ namespace Microsoft.Win32 {
byte[] dacl,
byte[] sacl );
- // Fusion APIs
-#if FEATURE_FUSION
- [DllImport(MSCORWKS, CharSet=CharSet.Unicode)]
- internal static extern int CreateAssemblyNameObject(out IAssemblyName ppEnum, String szAssemblyName, uint dwFlags, IntPtr pvReserved);
-
- [DllImport(MSCORWKS, CharSet=CharSet.Auto)]
- internal static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, IApplicationContext pAppCtx, IAssemblyName pName, uint dwFlags, IntPtr pvReserved);
-#endif // FEATURE_FUSION
-
-#if FEATURE_CORECLR
[DllImport(KERNEL32, CharSet=CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute()]
internal unsafe static extern int WideCharToMultiByte(
@@ -2417,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,
@@ -2450,6 +2340,5 @@ namespace Microsoft.Win32 {
}
}
#endif
-#endif
}
}
diff --git a/src/mscorlib/src/System.Private.CoreLib.txt b/src/mscorlib/src/System.Private.CoreLib.txt
index 0369344328..cf17dae96f 100644
--- a/src/mscorlib/src/System.Private.CoreLib.txt
+++ b/src/mscorlib/src/System.Private.CoreLib.txt
@@ -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.
@@ -206,6 +181,7 @@ Arg_ArithmeticException = Overflow or underflow in the arithmetic operation.
Arg_ArrayLengthsDiffer = Array lengths must be the same.
Arg_ArrayPlusOffTooSmall = Destination array is not long enough to copy all the items in the collection. Check array index and length.
Arg_ArrayTypeMismatchException = Attempted to access an element as a type incompatible with the array.
+Arg_BadDecimal = Read an invalid decimal value from the buffer.
Arg_BadImageFormatException = Format of the executable (.exe) or library (.dll) is invalid.
Argument_BadImageFormatExceptionResolve = A BadImageFormatException has been thrown while parsing the signature. This is likely due to lack of a generic context. Ensure genericTypeArguments and genericMethodArguments are provided and contain enough context.
Arg_BufferTooSmall = Not enough space available in the buffer.
@@ -553,26 +529,6 @@ Argument_InvalidElementText = Invalid element text '{0}'.
Argument_InvalidElementName = Invalid element name '{0}'.
Argument_InvalidElementValue = Invalid element value '{0}'.
Argument_AttributeNamesMustBeUnique = Attribute names must be unique.
-#if FEATURE_CAS_POLICY
-Argument_UninitializedCertificate = Uninitialized certificate object.
-Argument_MembershipConditionElement = Element must be a <IMembershipCondition> element.
-Argument_ReservedNPMS = Cannot remove or modify reserved permissions set '{0}'.
-Argument_NPMSInUse = Permission set '{0}' was in use and could not be deleted.
-Argument_StrongNameGetPublicKey = Unable to obtain public key for StrongNameKeyPair.
-Argument_SiteCannotBeNull = Site name must be specified.
-Argument_BlobCannotBeNull = Public key must be specified.
-Argument_ZoneCannotBeNull = Zone must be specified.
-Argument_UrlCannotBeNull = URL must be specified.
-Argument_NoNPMS = Unable to find a permission set with the provided name.
-Argument_FailedCodeGroup = Failed to create a code group of type '{0}'.
-Argument_CodeGroupChildrenMustBeCodeGroups = All objects in the input list must have a parent type of 'CodeGroup'.
-#endif // FEATURE_CAS_POLICY
-#if FEATURE_IMPERSONATION
-Argument_InvalidPrivilegeName = Privilege '{0}' is not valid on this system.
-Argument_TokenZero = Token cannot be zero.
-Argument_InvalidImpersonationToken = Invalid token for impersonation - it cannot be duplicated.
-Argument_ImpersonateUser = Unable to impersonate user.
-#endif // FEATURE_IMPERSONATION
Argument_InvalidHexFormat = Improperly formatted hex string.
Argument_InvalidSite = Invalid site.
Argument_InterfaceMap = 'this' type cannot be an interface itself.
@@ -630,6 +586,14 @@ Argument_UnmanagedMemAccessorWrapAround = The UnmanagedMemoryAccessor capacity a
Argument_UnrecognizedLoaderOptimization = Unrecognized LOADER_OPTIMIZATION property value. Supported values may include "SingleDomain", "MultiDomain", "MultiDomainHost", and "NotSpecified".
ArgumentException_NotAllCustomSortingFuncsDefined = Implementations of all the NLS functions must be provided.
ArgumentException_MinSortingVersion = The runtime does not support a version of "{0}" less than {1}.
+Argument_PreAllocatedAlreadyAllocated = 'preAllocated' is already in use.
+Argument_NativeOverlappedWrongBoundHandle = 'overlapped' was not allocated by this ThreadPoolBoundHandle instance.
+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
;
; =====================================================
@@ -1140,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.
@@ -1157,6 +1118,7 @@ InvalidOperation_MethodBaked = Type definition of the method is complete.
InvalidOperation_MethodHasBody = Method already has a body.
InvalidOperation_ModificationOfNonCanonicalAcl = This access control list is not in canonical form and therefore cannot be modified.
InvalidOperation_Method = This method is not supported by the current object.
+InvalidOperation_NativeOverlappedReused = NativeOverlapped cannot be reused for multiple operations.
InvalidOperation_NotADebugModule = Not a debug ModuleBuilder.
InvalidOperation_NoMultiModuleAssembly = You cannot have more than one dynamic module in each dynamic assembly in this version of the runtime.
InvalidOperation_OpenLocalVariableScope = Local variable scope was not properly closed.
@@ -1242,7 +1204,7 @@ InvalidOperation_CannotUseAFCOtherThread = AsyncFlowControl object must be used
InvalidOperation_CannotRestoreUnsupressedFlow = Cannot restore context flow when it is not suppressed.
InvalidOperation_CannotSupressFlowMultipleTimes = Context flow is already suppressed.
InvalidOperation_CannotUseAFCMultiple = AsyncFlowControl object can be used only once to call Undo().
-InvalidOperation_AsyncFlowCtrlCtxMismatch = AsyncFlowControl objects can be used to restore flow only on the Context that had its flow suppressed.
+InvalidOperation_AsyncFlowCtrlCtxMismatch = AsyncFlowControl objects can be used to restore flow only on a Context that had its flow suppressed.
InvalidOperation_TimeoutsNotSupported = Timeouts are not supported on this stream.
InvalidOperation_Overlapped_Pack = Cannot pack a packed Overlapped again.
InvalidOperation_OnlyValidForDS = Adding ACEs with Object Flags and Object GUIDs is only valid for directory-object ACLs.
@@ -1405,6 +1367,7 @@ NotSupported_SignalAndWaitSTAThread = SignalAndWait on a STA thread is not suppo
NotSupported_CreateInstanceWithTypeBuilder = CreateInstance cannot be used with an object of type TypeBuilder.
NotSupported_NonUrlAttrOnMBR = UrlAttribute is the only attribute supported for MarshalByRefObject.
NotSupported_ActivAttrOnNonMBR = Activation Attributes are not supported for types not deriving from MarshalByRefObject.
+NotSupported_ActivAttr = Activation Attributes are not supported.
NotSupported_ActivForCom = Activation Attributes not supported for COM Objects.
NotSupported_NoCodepageData = No data is available for encoding {0}. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
NotSupported_CodePage50229 = The ISO-2022-CN Encoding (Code page 50229) is not supported.
@@ -1451,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.
@@ -1466,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
@@ -1476,7 +1430,12 @@ NotSupported_PIAInAppxProcess = A Primary Interop Assembly is not supported in A
; Not referring to "Windows Phone" in the messages, as FEATURE_WINDOWSPHONE is defined for .NET Core as well.
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}'.
@@ -1536,81 +1495,12 @@ PlatformNotSupported_WinRT = Windows Runtime is not supported on this operating
; This still appears in bcl.small but should go away eventually
Policy_Default = Error occurred while performing a policy operation.
Policy_CannotLoadSemiTrustAssembliesDuringInit = All assemblies loaded as part of AppDomain initialization must be fully trusted.
-#if FEATURE_IMPERSONATION
-Policy_PrincipalTwice = Default principal object cannot be set twice.
-#endif // FEATURE_IMPERSONATION
-#if FEATURE_CAS_POLICY
-Policy_PolicyAlreadySet = Policy for this domain cannot be set twice.
-Policy_NoExecutionPermission = Execution permission cannot be acquired.
-Policy_NoRequiredPermission = Required permissions cannot be acquired.
-Policy_MultipleExclusive = More than one exclusive group is not allowed.
-Policy_RecoverNotFileBased = PolicyLevel object not based on a file cannot be recovered.
-Policy_RecoverNoConfigFile = No old configuration file exists to recover.
-Policy_UnableToSave = Policy level '{0}' could not be saved: {1}.
-Policy_BadXml = Policy configuration XML is invalid. The required tag '{0}' is missing.
-Policy_NonFullTrustAssembly = Policy references an assembly not in the full trust assemblies list.
-Policy_MissingActivationContextInAppEvidence = The application evidence does not contain a Fusion activation context.
-Policy_NoTrustManager = A trust manager could not be loaded for this application.
-Policy_GrantSetDoesNotMatchDomain = An assembly was provided an invalid grant set by runtime host '{0}'. In a homogenous AppDomain, the only valid grant sets are FullTrust and the AppDomain's sandbox grant set.
-#endif // FEATURE_CAS_POLICY
Policy_SaveNotFileBased = PolicyLevel object not based on a file cannot be saved.
Policy_AppTrustMustGrantAppRequest = ApplicationTrust grant set does not contain ActivationContext's minimum request set.
Error_SecurityPolicyFileParse = Error occurred while parsing the '{0}' policy level. The default policy level was used instead.
Error_SecurityPolicyFileParseEx = Error '{1}' occurred while parsing the '{0}' policy level. The default policy level was used instead.
-#if FEATURE_CAS_POLICY
-Policy_EvidenceMustBeSerializable = Objects used as evidence must be serializable.
-Policy_DuplicateEvidence = The evidence collection already contains evidence of type '{0}'. Multiple pieces of the same type of evidence are not allowed.
-Policy_IncorrectHostEvidence = Runtime host '{0}' returned evidence of type '{1}' from a request for evidence of type '{2}'.
-Policy_NullHostEvidence = Runtime host '{0}' returned null when asked for assembly evidence for assembly '{1}'.
-Policy_NullHostGrantSet = Runtime host '{0}' returned a null grant set from ResolvePolicy.
-#endif // FEATURE_CAS_POLICY
-
-; Policy codegroup and permission set names and descriptions
-#if FEATURE_CAS_POLICY
-Policy_AllCode_Name = All_Code
-Policy_AllCode_DescriptionFullTrust = Code group grants all code full trust and forms the root of the code group tree.
-Policy_AllCode_DescriptionNothing = Code group grants no permissions and forms the root of the code group tree.
-Policy_MyComputer_Name = My_Computer_Zone
-Policy_MyComputer_Description = Code group grants full trust to all code originating on the local computer
-Policy_Intranet_Name = LocalIntranet_Zone
-Policy_Intranet_Description = Code group grants the intranet permission set to code from the intranet zone. This permission set grants intranet code the right to use isolated storage, full UI access, some capability to do reflection, and limited access to environment variables.
-Policy_IntranetNet_Name = Intranet_Same_Site_Access
-Policy_IntranetNet_Description = All intranet code gets the right to connect back to the site of its origin.
-Policy_IntranetFile_Name = Intranet_Same_Directory_Access
-Policy_IntranetFile_Description = All intranet code gets the right to read from its install directory.
-Policy_Internet_Name = Internet_Zone
-Policy_Internet_Description = Code group grants code from the Internet zone the Internet permission set. This permission set grants Internet code the right to use isolated storage and limited UI access.
-Policy_InternetNet_Name = Internet_Same_Site_Access
-Policy_InternetNet_Description = All Internet code gets the right to connect back to the site of its origin.
-Policy_Trusted_Name = Trusted_Zone
-Policy_Trusted_Description = Code from a trusted zone is granted the Internet permission set. This permission set grants the right to use isolated storage and limited UI access.
-Policy_TrustedNet_Name = Trusted_Same_Site_Access
-Policy_TrustedNet_Description = All Trusted Code gets the right to connect back to the site of its origin.
-Policy_Untrusted_Name = Restricted_Zone
-Policy_Untrusted_Description = Code coming from a restricted zone does not receive any permissions.
-Policy_Microsoft_Name = Microsoft_Strong_Name
-Policy_Microsoft_Description = Code group grants full trust to code signed with the Microsoft strong name.
-Policy_Ecma_Name = ECMA_Strong_Name
-Policy_Ecma_Description = Code group grants full trust to code signed with the ECMA strong name.
-
-; Policy permission set descriptions
-Policy_PS_FullTrust = Allows full access to all resources
-Policy_PS_Everything = Allows unrestricted access to all resources covered by built-in permissions
-Policy_PS_Nothing = Denies all resources, including the right to execute
-Policy_PS_Execution = Permits execution
-Policy_PS_SkipVerification = Grants right to bypass the verification
-Policy_PS_Internet = Default rights given to Internet applications
-Policy_PS_LocalIntranet = Default rights given to applications on the local intranet
-
-; default Policy level names
-Policy_PL_Enterprise = Enterprise
-Policy_PL_Machine = Machine
-Policy_PL_User = User
-Policy_PL_AppDomain = AppDomain
-#endif // FEATURE_CAS_POLICY
-
; RankException
Rank_MultiDimNotSupported = Only single dimension arrays are supported here.
Rank_MustMatch = The specified arrays must have the same number of dimensions.
@@ -1658,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
;
@@ -1805,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
@@ -1872,12 +1625,10 @@ IO.PathNotFound_Path = Could not find a part of the path '{0}'.
IO.PathNotFound_NoPathName = Could not find a part of the path.
; PathTooLongException
-IO.PathTooLong = The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
+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.
@@ -2275,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}
@@ -2295,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}'.
@@ -2381,956 +2118,8 @@ InvalidOperation_CollectionBackingListTooLarge=The collection backing this List
InvalidOperation_CollectionBackingDictionaryTooLarge=The collection backing this Dictionary contains too many elements.
InvalidOperation_CannotRemoveLastFromEmptyCollection=Cannot remove the last element from an empty collection.
-; 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
+; Buffers
+ArgumentException_BufferNotFromPool=The buffer is not associated with this pool and may not be returned to it.
;------------------
; Encoding names:
diff --git a/src/mscorlib/src/System/Action.cs b/src/mscorlib/src/System/Action.cs
index d6653c7979..27f7fafe5c 100644
--- a/src/mscorlib/src/System/Action.cs
+++ b/src/mscorlib/src/System/Action.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Activator.cs b/src/mscorlib/src/System/Activator.cs
index 274b0e7ec5..6fad8f3173 100644
--- a/src/mscorlib/src/System/Activator.cs
+++ b/src/mscorlib/src/System/Activator.cs
@@ -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,
@@ -70,7 +65,7 @@ namespace System {
Object[] activationAttributes)
{
if ((object)type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
if (type is System.Reflection.Emit.TypeBuilder)
@@ -81,26 +76,13 @@ 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
-#endif
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR" ));
+ throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr" ));
}
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
if (rt == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"type");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(type));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return rt.CreateInstanceImpl(bindingAttr,binder,args,culture,activationAttributes, ref stackMark);
@@ -138,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)
@@ -156,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,
@@ -180,13 +160,13 @@ namespace System {
static public Object CreateInstance(Type type, bool nonPublic)
{
if ((object)type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
if (rt == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(type));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, ref stackMark);
@@ -230,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,
@@ -256,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,
@@ -280,7 +258,6 @@ namespace System {
ref stackMark);
}
- [System.Security.SecurityCritical] // auto-generated
static internal ObjectHandle CreateInstance(String assemblyString,
String typeName,
bool ignoreCase,
@@ -292,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) {
@@ -356,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,
@@ -404,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
@@ -436,15 +395,13 @@ 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("domain");
+ throw new ArgumentNullException(nameof(domain));
Contract.EndContractBlock();
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,
@@ -457,20 +414,12 @@ namespace System {
Object[] activationAttributes,
Evidence securityAttributes) {
if (domain == null)
- throw new ArgumentNullException("domain");
+ 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,
@@ -482,7 +431,7 @@ namespace System {
object[] activationAttributes)
{
if (domain == null)
- throw new ArgumentNullException("domain");
+ throw new ArgumentNullException(nameof(domain));
Contract.EndContractBlock();
return domain.InternalCreateInstanceWithNoSecurity(assemblyName,
@@ -503,15 +452,13 @@ 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("domain");
+ throw new ArgumentNullException(nameof(domain));
Contract.EndContractBlock();
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,
@@ -524,20 +471,12 @@ namespace System {
Object[] activationAttributes,
Evidence securityAttributes) {
if (domain == null)
- throw new ArgumentNullException("domain");
+ 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,
@@ -549,7 +488,7 @@ namespace System {
object[] activationAttributes)
{
if (domain == null)
- throw new ArgumentNullException("domain");
+ throw new ArgumentNullException(nameof(domain));
Contract.EndContractBlock();
return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile,
@@ -563,28 +502,8 @@ namespace System {
null);
}
-#if FEATURE_CLICKONCE
- [System.Security.SecuritySafeCritical] // auto-generated
- public static ObjectHandle CreateInstance (ActivationContext activationContext) {
- AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
- if (domainManager == null)
- domainManager = new AppDomainManager();
-
- return domainManager.ApplicationActivator.CreateInstance(activationContext);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public static ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData) {
- AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
- if (domainManager == null)
- domainManager = new AppDomainManager();
-
- return domainManager.ApplicationActivator.CreateInstance(activationContext, activationCustomData);
- }
-#endif // FEATURE_CLICKONCE
-
public static ObjectHandle CreateComInstanceFrom(String assemblyName,
- String typeName)
+ String typeName)
{
return CreateComInstanceFrom(assemblyName,
typeName,
@@ -630,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("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();
diff --git a/src/mscorlib/src/System/AggregateException.cs b/src/mscorlib/src/System/AggregateException.cs
index 064432aaaa..c0f21229ed 100644
--- a/src/mscorlib/src/System/AggregateException.cs
+++ b/src/mscorlib/src/System/AggregateException.cs
@@ -69,7 +69,7 @@ namespace System
{
if (innerException == null)
{
- throw new ArgumentNullException("innerException");
+ throw new ArgumentNullException(nameof(innerException));
}
m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[] { innerException });
@@ -149,7 +149,7 @@ namespace System
{
if (innerExceptions == null)
{
- throw new ArgumentNullException("innerExceptions");
+ throw new ArgumentNullException(nameof(innerExceptions));
}
// Copy exceptions to our internal array and validate them. We must copy them,
@@ -227,7 +227,7 @@ namespace System
{
if (innerExceptionInfos == null)
{
- throw new ArgumentNullException("innerExceptionInfos");
+ throw new ArgumentNullException(nameof(innerExceptionInfos));
}
// Copy exceptions to our internal array and validate them. We must copy them,
@@ -258,13 +258,12 @@ 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)
{
if (info == null)
{
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[];
@@ -285,12 +284,11 @@ 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)
{
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
base.GetObjectData(info, context);
@@ -351,7 +349,7 @@ namespace System
{
if (predicate == null)
{
- throw new ArgumentNullException("predicate");
+ throw new ArgumentNullException(nameof(predicate));
}
List<Exception> unhandledExceptions = null;
@@ -379,7 +377,8 @@ namespace System
/// <summary>
- /// Flattens an <see cref="AggregateException"/> instances into a single, new instance.
+ /// Flattens the inner instances of <see cref="AggregateException"/> by expanding its contained <see cref="Exception"/> instances
+ /// into a new <see cref="AggregateException"/>
/// </summary>
/// <returns>A new, flattened <see cref="AggregateException"/>.</returns>
/// <remarks>
diff --git a/src/mscorlib/src/System/AppContext/AppContext.cs b/src/mscorlib/src/System/AppContext/AppContext.cs
index 0b0643d7b4..41e44508f0 100644
--- a/src/mscorlib/src/System/AppContext/AppContext.cs
+++ b/src/mscorlib/src/System/AppContext/AppContext.cs
@@ -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,14 +38,53 @@ namespace System
}
}
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
public static object GetData(string name)
{
return AppDomain.CurrentDomain.GetData(name);
}
+ public static void SetData(string name, object data)
+ {
+ AppDomain.CurrentDomain.SetData(name, data);
+ }
+
+ public static event UnhandledExceptionEventHandler UnhandledException
+ {
+ add
+ {
+ AppDomain.CurrentDomain.UnhandledException += value;
+ }
+
+ remove
+ {
+ AppDomain.CurrentDomain.UnhandledException -= value;
+ }
+ }
+
+ public static event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException
+ {
+ add
+ {
+ AppDomain.CurrentDomain.FirstChanceException += value;
+ }
+ remove
+ {
+ AppDomain.CurrentDomain.FirstChanceException -= value;
+ }
+ }
+
+ public static event System.EventHandler ProcessExit
+ {
+ add
+ {
+ AppDomain.CurrentDomain.ProcessExit += value;
+ }
+ remove
+ {
+ AppDomain.CurrentDomain.ProcessExit -= value;
+ }
+ }
+
#region Switch APIs
static AppContext()
{
@@ -65,9 +101,9 @@ namespace System
public static bool TryGetSwitch(string switchName, out bool isEnabled)
{
if (switchName == null)
- throw new ArgumentNullException("switchName");
+ throw new ArgumentNullException(nameof(switchName));
if (switchName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "switchName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName));
// By default, the switch is not enabled.
isEnabled = false;
@@ -161,9 +197,9 @@ namespace System
public static void SetSwitch(string switchName, bool isEnabled)
{
if (switchName == null)
- throw new ArgumentNullException("switchName");
+ throw new ArgumentNullException(nameof(switchName));
if (switchName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "switchName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName));
SwitchValueState switchValue = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue)
| SwitchValueState.HasLookedForOverride;
diff --git a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs
index c80913e3a6..52bdf9d427 100644
--- a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs
+++ b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs
@@ -12,10 +12,6 @@ namespace System
internal static readonly string SwitchNoAsyncCurrentCulture = "Switch.System.Globalization.NoAsyncCurrentCulture";
internal static readonly string SwitchThrowExceptionIfDisposedCancellationTokenSource = "Switch.System.Threading.ThrowExceptionIfDisposedCancellationTokenSource";
internal static readonly string SwitchPreserveEventListnerObjectIdentity = "Switch.System.Diagnostics.EventSource.PreserveEventListnerObjectIdentity";
-#if FEATURE_PATHCOMPAT
- internal static readonly string SwitchUseLegacyPathHandling = "Switch.System.IO.UseLegacyPathHandling";
- internal static readonly string SwitchBlockLongPaths = "Switch.System.IO.BlockLongPaths";
-#endif
// This is a partial method. Platforms can provide an implementation of it that will set override values
// from whatever mechanism is available on that platform. If no implementation is provided, the compiler is going to remove the calls
@@ -43,13 +39,7 @@ namespace System
AppContext.DefineSwitchDefault(SwitchNoAsyncCurrentCulture, true);
AppContext.DefineSwitchDefault(SwitchThrowExceptionIfDisposedCancellationTokenSource, true);
}
-#if FEATURE_PATHCOMPAT
- if (version <= 40601)
- {
- AppContext.DefineSwitchDefault(SwitchUseLegacyPathHandling, true);
- AppContext.DefineSwitchDefault(SwitchBlockLongPaths, true);
- }
-#endif
+
break;
}
case "WindowsPhone":
diff --git a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs
index 7ab7ffbc04..9f00e8148c 100644
--- a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs
+++ b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/AppContext/AppContextSwitches.cs b/src/mscorlib/src/System/AppContext/AppContextSwitches.cs
index 3a96ec2159..5fdd2bc1e6 100644
--- a/src/mscorlib/src/System/AppContext/AppContextSwitches.cs
+++ b/src/mscorlib/src/System/AppContext/AppContextSwitches.cs
@@ -39,36 +39,6 @@ namespace System
}
}
-#if FEATURE_PATHCOMPAT
- private static int _useLegacyPathHandling;
-
- /// <summary>
- /// Use legacy path normalization logic and blocking of extended syntax.
- /// </summary>
- public static bool UseLegacyPathHandling
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- get
- {
- return GetCachedSwitchValue(AppContextDefaultValues.SwitchUseLegacyPathHandling, ref _useLegacyPathHandling);
- }
- }
-
- private static int _blockLongPaths;
-
- /// <summary>
- /// Throw PathTooLongException for paths greater than MAX_PATH or directories greater than 248 (as per CreateDirectory Win32 limitations)
- /// </summary>
- public static bool BlockLongPaths
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- get
- {
- return GetCachedSwitchValue(AppContextDefaultValues.SwitchBlockLongPaths, ref _blockLongPaths);
- }
- }
-#endif // FEATURE_PATHCOMPAT
-
//
// Implementation details
//
diff --git a/src/mscorlib/src/System/AppDomain.cs b/src/mscorlib/src/System/AppDomain.cs
index abaaf48770..fe524c4dc5 100644
--- a/src/mscorlib/src/System/AppDomain.cs
+++ b/src/mscorlib/src/System/AppDomain.cs
@@ -13,46 +13,29 @@
**
=============================================================================*/
-namespace System {
+namespace System
+{
using System;
-#if FEATURE_CLICKONCE
- using System.Deployment.Internal.Isolation;
- using System.Deployment.Internal.Isolation.Manifest;
- using System.Runtime.Hosting;
-#endif
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Channels;
- using System.Runtime.Remoting.Contexts;
-#endif
using System.Security;
using System.Security.Permissions;
-#if FEATURE_IMPERSONATION
- using System.Security.Principal;
-#endif
using System.Security.Policy;
using System.Security.Util;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
-#if FEATURE_REMOTING
- using Context = System.Runtime.Remoting.Contexts.Context;
-#endif
+ using System.Runtime.Remoting;
using System.Reflection.Emit;
using CultureInfo = System.Globalization.CultureInfo;
-#if !FEATURE_CORECLR
- using System.Globalization;
-#endif
using System.IO;
using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
using System.Text;
- using Microsoft.Win32;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
#if FEATURE_EXCEPTION_NOTIFICATIONS
using System.Runtime.ExceptionServices;
@@ -107,10 +90,6 @@ namespace System {
}
}
-
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
[Serializable]
[ComVisible(true)]
public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args);
@@ -177,7 +156,6 @@ namespace System {
Info = itemInfo.ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal AppDomainInitializer Unwrap()
{
if (Info==null)
@@ -204,17 +182,13 @@ namespace System {
[ComDefaultInterface(typeof(System._AppDomain))]
[ComVisible(true)]
public sealed class AppDomain :
-#if FEATURE_REMOTING
- MarshalByRefObject,
-#endif
_AppDomain, IEvidenceFactory
{
// 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;
@@ -225,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)
@@ -239,7 +211,6 @@ namespace System {
}
}
- [System.Security.SecurityCritical]
remove
{
lock (this)
@@ -249,12 +220,10 @@ namespace System {
}
}
- [System.Security.SecurityCritical]
private ResolveEventHandler _ResourceResolve;
public event ResolveEventHandler ResourceResolve
{
- [System.Security.SecurityCritical]
add
{
lock (this)
@@ -263,7 +232,6 @@ namespace System {
}
}
- [System.Security.SecurityCritical]
remove
{
lock (this)
@@ -273,12 +241,10 @@ namespace System {
}
}
- [System.Security.SecurityCritical]
private ResolveEventHandler _AssemblyResolve;
public event ResolveEventHandler AssemblyResolve
{
- [System.Security.SecurityCritical]
add
{
lock (this)
@@ -287,7 +253,6 @@ namespace System {
}
}
- [System.Security.SecurityCritical]
remove
{
lock (this)
@@ -302,38 +267,13 @@ namespace System {
public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
#endif // FEATURE_REFLECTION_ONLY
-#if FEATURE_REMOTING
- private Context _DefaultContext;
-#endif
-
-#if FEATURE_CLICKONCE
- private ActivationContext _activationContext;
- private ApplicationIdentity _applicationIdentity;
-#endif
private ApplicationTrust _applicationTrust;
-
-#if FEATURE_IMPERSONATION
- private IPrincipal _DefaultPrincipal;
-#endif // FEATURE_IMPERSONATION
-#if FEATURE_REMOTING
- private DomainSpecificRemotingData _RemotingData;
-#endif
private EventHandler _processExit;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical]
- #endif
private EventHandler _domainUnload;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
private UnhandledExceptionEventHandler _unhandledException;
-#if FEATURE_APTCA
- private String[] _aptcaVisibleAssemblies;
-#endif
-
// The compat flags are set at domain creation time to indicate that the given breaking
// changes (named in the strings) should not be used in this domain. We only use the
// keys, the vhe values are ignored.
@@ -346,9 +286,6 @@ namespace System {
private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
-#if FEATURE_CAS_POLICY
- private PrincipalPolicy _PrincipalPolicy; // this is an enum
-#endif
private bool _HasSetPolicy;
private bool _IsFastFullTrustDomain; // quick check to see if the AppDomain is fully trusted and homogenous
private bool _compatFlagsInitialized;
@@ -378,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;
@@ -400,7 +335,6 @@ namespace System {
internal static bool IsAppXNGen
{
- [SecuritySafeCritical]
get
{
return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_NGEN) != 0;
@@ -409,56 +343,37 @@ 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,
[MarshalAs(UnmanagedType.Bool)] bool runtimeSuppliedHomogenousGrantSet);
-#if FEATURE_CAS_POLICY
- [SecurityCritical]
- [SuppressUnmanagedCodeSecurity]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- private static extern void SetLegacyCasPolicyEnabled(AppDomainHandle domain);
-
- [SecurityCritical]
- private void SetLegacyCasPolicyEnabled()
- {
- SetLegacyCasPolicyEnabled(GetNativeHandle());
- }
-#endif // FEATURE_CAS_POLICY
-
/// <summary>
/// Get a handle used to make a call into the VM pointing to this domain
/// </summary>
@@ -471,9 +386,6 @@ namespace System {
throw new InvalidOperationException(Environment.GetResourceString("Argument_InvalidHandle"));
}
-#if FEATURE_REMOTING
- BCLDebug.Assert(!RemotingServices.IsTransparentProxy(this), "QCalls should be made with the real AppDomain object rather than a transparent proxy");
-#endif // FEATURE_REMOTING
return new AppDomainHandle(_pDomain);
}
@@ -481,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
@@ -566,17 +477,9 @@ namespace System {
if (notifyFusion)
SetupFusionStore(_FusionStore, FusionStoreOld); // Notify Fusion about the changes the user implementation of InitializeNewDomain may have made to the FusionStore object.
-
-#if FEATURE_APPDOMAINMANAGER_INITOPTIONS
- AppDomainManagerInitializationOptions flags = _domainManager.InitializationFlags;
- if ((flags & AppDomainManagerInitializationOptions.RegisterWithHost) == AppDomainManagerInitializationOptions.RegisterWithHost)
- {
- _domainManager.RegisterWithHost();
- }
-#endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS
}
- InitializeCompatibilityFlags();
+ InitializeCompatibilityFlags();
}
/// <summary>
@@ -596,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();
@@ -606,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;
@@ -621,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;
}
@@ -635,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());
@@ -644,7 +545,6 @@ namespace System {
/// <summary>
/// Returns whether the current AppDomain follows the AppX rules.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static bool IsAppXModel()
{
@@ -658,7 +558,6 @@ namespace System {
/// <summary>
/// Returns the setting of the AppXDevMode config switch.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static bool IsAppXDesignMode()
{
@@ -672,7 +571,6 @@ namespace System {
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.LoadFrom.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckLoadFromSupported()
{
@@ -685,7 +583,6 @@ namespace System {
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.LoadFile.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckLoadFileSupported()
{
@@ -698,7 +595,6 @@ namespace System {
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.ReflectionOnlyLoad.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckReflectionOnlyLoadSupported()
{
@@ -711,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)
{
@@ -731,7 +626,6 @@ namespace System {
/// <summary>
/// Checks (and throws on failure) if the domain supports DefinePInvokeMethod.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckDefinePInvokeSupported()
{
@@ -745,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()
{
@@ -758,7 +651,6 @@ namespace System {
/// <summary>
/// Checks (and throws on failure) if the domain supports AppDomain.CreateDomain.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckCreateDomainSupported()
{
@@ -779,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
@@ -798,77 +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);
}
-#if FEATURE_APTCA
- internal String[] PartialTrustVisibleAssemblies
- {
- get { return _aptcaVisibleAssemblies; }
-
- [SecuritySafeCritical]
- set
- {
- _aptcaVisibleAssemblies = value;
-
- // Build up the canonical representaiton of this list to allow the VM to do optimizations in
- // common cases
- string canonicalConditionalAptcaList = null;
- if (value != null)
- {
- StringBuilder conditionalAptcaListBuilder = StringBuilderCache.Acquire();
- for (int i = 0; i < value.Length; ++i)
- {
- if (value[i] != null)
- {
- conditionalAptcaListBuilder.Append(value[i].ToUpperInvariant());
- if (i != value.Length - 1)
- {
- conditionalAptcaListBuilder.Append(';');
- }
- }
- }
-
- canonicalConditionalAptcaList = StringBuilderCache.GetStringAndRelease(conditionalAptcaListBuilder);
- }
-
- SetCanonicalConditionalAptcaList(canonicalConditionalAptcaList);
- }
- }
-
- [SecurityCritical]
- [SuppressUnmanagedCodeSecurity]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- private static extern void SetCanonicalConditionalAptcaList(AppDomainHandle appDomain, string canonicalList);
-
- [SecurityCritical]
- private void SetCanonicalConditionalAptcaList(string canonicalList)
- {
- SetCanonicalConditionalAptcaList(GetNativeHandle(), canonicalList);
- }
-#endif // FEATURE_APTCA
-
-#if FEATURE_CLICKONCE
- /// <summary>
- /// If the CLR is being started up to run a ClickOnce applicaiton, setup the default AppDomain
- /// with information about that application.
- /// </summary>
- private void SetupDefaultClickOnceDomain(string fullName, string[] manifestPaths, string[] activationData)
- {
- Contract.Requires(fullName != null, "fullName != null");
- FusionStore.ActivationArguments = new ActivationArguments(fullName, manifestPaths, activationData);
- }
-#endif // FEATURE_CLICKONCE
-
/// <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,
@@ -877,91 +707,23 @@ namespace System {
{
AppDomainSetup adSetup = FusionStore;
-#if FEATURE_CAS_POLICY
- // If the AppDomain is setup to use legacy CAS policy, then set that bit in the application
- // security descriptor.
- if (CompatibilitySwitches.IsNetFx40LegacySecurityPolicy)
- {
- SetLegacyCasPolicyEnabled();
- }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CLICKONCE
-
- // Check if the domain manager set an ActivationContext (Debug-In-Zone for example)
- // or if this is an AppDomain with an ApplicationTrust.
- if (adSetup.ActivationArguments != null) {
- // Merge the new evidence with the manifest's evidence if applicable
- ActivationContext activationContext = null;
- ApplicationIdentity appIdentity = null;
- string[] activationData = null;
- CmsUtils.CreateActivationContext(adSetup.ActivationArguments.ApplicationFullName,
- adSetup.ActivationArguments.ApplicationManifestPaths,
- adSetup.ActivationArguments.UseFusionActivationContext,
- out appIdentity, out activationContext);
- activationData = adSetup.ActivationArguments.ActivationData;
- providedSecurityInfo = CmsUtils.MergeApplicationEvidence(providedSecurityInfo,
- appIdentity,
- activationContext,
- activationData,
- adSetup.ApplicationTrust);
- SetupApplicationHelper(providedSecurityInfo, creatorsSecurityInfo, appIdentity, activationContext, activationData);
- }
- else
-#endif // FEATURE_CLICKONCE
- {
- bool runtimeSuppliedHomogenousGrant = false;
- ApplicationTrust appTrust = adSetup.ApplicationTrust;
-
-#if FEATURE_CAS_POLICY
- // In non-legacy CAS mode, domains should be homogenous. If the host has not specified a sandbox
- // of their own, we'll set it up to be fully trusted. We must read the IsLegacyCasPolicy
- // enabled property here rathern than just reading the switch from above because the entire
- // process may also be opted into legacy CAS policy mode.
- if (appTrust == null && !IsLegacyCasPolicyEnabled) {
- _IsFastFullTrustDomain = true;
- runtimeSuppliedHomogenousGrant = true;
- }
-#endif // FEATURE_CAS_POLICY
+ bool runtimeSuppliedHomogenousGrant = false;
+ ApplicationTrust appTrust = adSetup.ApplicationTrust;
- if (appTrust != null) {
- SetupDomainSecurityForHomogeneousDomain(appTrust, runtimeSuppliedHomogenousGrant);
- }
- else if (_IsFastFullTrustDomain) {
- SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrant);
- }
+ if (appTrust != null) {
+ SetupDomainSecurityForHomogeneousDomain(appTrust, runtimeSuppliedHomogenousGrant);
+ }
+ else if (_IsFastFullTrustDomain) {
+ SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrant);
}
// Get the evidence supplied for the domain. If no evidence was supplied, it means that we want
// to use the default evidence creation strategy for this domain
Evidence newAppDomainEvidence = (providedSecurityInfo != null ? providedSecurityInfo : creatorsSecurityInfo);
if (newAppDomainEvidence == null && generateDefaultEvidence) {
-#if FEATURE_CAS_POLICY
- newAppDomainEvidence = new Evidence(new AppDomainEvidenceFactory(this));
-#else // !FEATURE_CAS_POLICY
newAppDomainEvidence = new Evidence();
-#endif // FEATURE_CAS_POLICY
}
-#if FEATURE_CAS_POLICY
- if (_domainManager != null) {
- // Give the host a chance to alter the AppDomain evidence
- HostSecurityManager securityManager = _domainManager.HostSecurityManager;
- if (securityManager != null) {
- nSetHostSecurityManagerFlags (securityManager.Flags);
- if ((securityManager.Flags & HostSecurityManagerOptions.HostAppDomainEvidence) == HostSecurityManagerOptions.HostAppDomainEvidence) {
- newAppDomainEvidence = securityManager.ProvideAppDomainEvidence(newAppDomainEvidence);
- // If this is a disconnected evidence collection, then attach it to the AppDomain,
- // allowing the host security manager to get callbacks for delay generated evidence
- if (newAppDomainEvidence != null && newAppDomainEvidence.Target == null) {
- newAppDomainEvidence.Target = new AppDomainEvidenceFactory(this);
- }
- }
- }
- }
-
-#endif // FEATURE_CAS_POLICY
-
// Set the evidence on the managed side
_SecurityIdentity = newAppDomainEvidence;
@@ -971,106 +733,8 @@ namespace System {
SetupDomainSecurity(newAppDomainEvidence,
parentSecurityDescriptor,
publishAppDomain);
-
-#if FEATURE_CAS_POLICY
- // The AppDomain is now resolved. Go ahead and set the PolicyLevel
- // from the HostSecurityManager if specified.
- if (_domainManager != null)
- RunDomainManagerPostInitialization(_domainManager);
-#endif // FEATURE_CAS_POLICY
- }
-
-#if FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated
- private void RunDomainManagerPostInitialization (AppDomainManager domainManager)
- {
- // force creation of the HostExecutionContextManager for the current AppDomain
- HostExecutionContextManager contextManager = domainManager.HostExecutionContextManager;
-
- if (IsLegacyCasPolicyEnabled)
- {
-#pragma warning disable 618
- HostSecurityManager securityManager = domainManager.HostSecurityManager;
- if (securityManager != null)
- {
- if ((securityManager.Flags & HostSecurityManagerOptions.HostPolicyLevel) == HostSecurityManagerOptions.HostPolicyLevel)
- {
- // set AppDomain policy if specified
- PolicyLevel level = securityManager.DomainPolicy;
- if (level != null)
- SetAppDomainPolicy(level);
- }
- }
-#pragma warning restore 618
- }
- }
-#endif
-
-
-#if FEATURE_CLICKONCE
-
- [System.Security.SecurityCritical] // auto-generated
- private void SetupApplicationHelper (Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, ApplicationIdentity appIdentity, ActivationContext activationContext, string[] activationData) {
- Contract.Requires(providedSecurityInfo != null);
- HostSecurityManager securityManager = AppDomain.CurrentDomain.HostSecurityManager;
- ApplicationTrust appTrust = securityManager.DetermineApplicationTrust(providedSecurityInfo, creatorsSecurityInfo, new TrustManagerContext());
- if (appTrust == null || !appTrust.IsApplicationTrustedToRun)
- throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"),
- System.__HResults.CORSEC_E_NO_EXEC_PERM,
- null);
-
- // The application is trusted to run. Set up the AppDomain according to the manifests.
- if (activationContext != null)
- SetupDomainForApplication(activationContext, activationData);
- SetupDomainSecurityForApplication(appIdentity, appTrust);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private void SetupDomainForApplication(ActivationContext activationContext, string[] activationData) {
- Contract.Requires(activationContext != null);
- if (IsDefaultAppDomain()) {
- // make the ActivationArguments available off the AppDomain object.
- AppDomainSetup adSetup = this.FusionStore;
- adSetup.ActivationArguments = new ActivationArguments(activationContext, activationData);
-
- // set the application base to point at where the application resides
- string entryPointPath = CmsUtils.GetEntryPointFullPath(activationContext);
- if (!String.IsNullOrEmpty(entryPointPath))
- adSetup.SetupDefaults(entryPointPath);
- else
- adSetup.ApplicationBase = activationContext.ApplicationDirectory;
-
- // update fusion context
- SetupFusionStore(adSetup, null);
- }
-
- // perform app data directory migration.
- activationContext.PrepareForExecution();
- activationContext.SetApplicationState(ActivationContext.ApplicationState.Starting);
- // set current app data directory.
- activationContext.SetApplicationState(ActivationContext.ApplicationState.Running);
-
- // make data directory path available.
- IPermission permission = null;
- string dataDirectory = activationContext.DataDirectory;
- if (dataDirectory != null && dataDirectory.Length > 0)
- permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, dataDirectory);
- this.SetData("DataDirectory", dataDirectory, permission);
-
- _activationContext = activationContext;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private void SetupDomainSecurityForApplication(ApplicationIdentity appIdentity,
- ApplicationTrust appTrust)
- {
- // Set the Application trust on the managed side.
- _applicationIdentity = appIdentity;
- SetupDomainSecurityForHomogeneousDomain(appTrust, false);
}
-#endif // FEATURE_CLICKONCE
- [System.Security.SecurityCritical] // auto-generated
private void SetupDomainSecurityForHomogeneousDomain(ApplicationTrust appTrust,
bool runtimeSuppliedHomogenousGrantSet)
{
@@ -1084,9 +748,6 @@ namespace System {
if (runtimeSuppliedHomogenousGrantSet)
{
BCLDebug.Assert(_FusionStore.ApplicationTrust != null, "Expected to find runtime supplied ApplicationTrust");
-#if FEATURE_CAS_POLICY
- _FusionStore.ApplicationTrust = null;
-#endif // FEATURE_CAS_POLICY
}
_applicationTrust = appTrust;
@@ -1096,38 +757,13 @@ namespace System {
runtimeSuppliedHomogenousGrantSet);
}
- // This method is called from CorHost2::ExecuteApplication to activate a ClickOnce application in the default AppDomain.
-#if FEATURE_CLICKONCE
- [System.Security.SecuritySafeCritical] // auto-generated
- private int ActivateApplication () {
- ObjectHandle oh = Activator.CreateInstance(AppDomain.CurrentDomain.ActivationContext);
- return (int) oh.Unwrap();
- }
-#endif //FEATURE_CLICKONCE
-
public AppDomainManager DomainManager {
- [System.Security.SecurityCritical] // auto-generated_required
get {
return _domainManager;
}
}
-#if FEATURE_CAS_POLICY
- internal HostSecurityManager HostSecurityManager {
- [System.Security.SecurityCritical] // auto-generated
- get {
- HostSecurityManager securityManager = null;
- AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
- if (domainManager != null)
- securityManager = domainManager.HostSecurityManager;
-
- if (securityManager == null)
- securityManager = new HostSecurityManager();
- return securityManager;
- }
- }
-#endif // FEATURE_CAS_POLICY
-#if FEATURE_REFLECTION_ONLY_LOAD
+#if FEATURE_REFLECTION_ONLY_LOAD
private Assembly ResolveAssemblyForIntrospection(Object sender, ResolveEventArgs args)
{
Contract.Requires(args != null);
@@ -1143,7 +779,6 @@ namespace System {
_packageGraphFilePaths = packageGraphFilePaths;
}
- [System.Security.SecurityCritical]
public void ResolveNamespace(
object sender,
System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs args)
@@ -1162,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);
@@ -1183,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,
@@ -1196,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,
@@ -1214,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,
@@ -1231,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,
@@ -1248,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(
@@ -1266,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(
@@ -1288,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(
@@ -1304,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(
@@ -1327,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(
@@ -1351,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(
@@ -1376,8 +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(
@@ -1405,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(
@@ -1434,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,
@@ -1458,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,
@@ -1484,7 +1103,6 @@ namespace System {
securityContextSource);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String nApplyPolicy(AssemblyName an);
@@ -1506,7 +1124,6 @@ namespace System {
return nApplyPolicy(asmName);
}
-
public ObjectHandle CreateInstance(String assemblyName,
String typeName)
@@ -1516,14 +1133,13 @@ namespace System {
throw new NullReferenceException();
if (assemblyName == null)
- throw new ArgumentNullException("assemblyName");
+ throw new ArgumentNullException(nameof(assemblyName));
Contract.EndContractBlock();
return Activator.CreateInstance(assemblyName,
typeName);
}
- [System.Security.SecurityCritical] // auto-generated
internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, string typeName) {
PermissionSet.s_fullTrust.Assert();
return CreateInstance(assemblyName, typeName);
@@ -1542,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);
@@ -1591,7 +1206,7 @@ namespace System {
throw new NullReferenceException();
if (assemblyName == null)
- throw new ArgumentNullException("assemblyName");
+ throw new ArgumentNullException(nameof(assemblyName));
Contract.EndContractBlock();
return Activator.CreateInstance(assemblyName,
@@ -1630,16 +1245,9 @@ namespace System {
throw new NullReferenceException();
if (assemblyName == null)
- throw new ArgumentNullException("assemblyName");
+ throw new ArgumentNullException(nameof(assemblyName));
Contract.EndContractBlock();
-#if FEATURE_CAS_POLICY
- if (securityAttributes != null && !IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
#pragma warning disable 618
return Activator.CreateInstance(assemblyName,
typeName,
@@ -1667,7 +1275,7 @@ namespace System {
throw new NullReferenceException();
if (assemblyName == null)
- throw new ArgumentNullException("assemblyName");
+ throw new ArgumentNullException(nameof(assemblyName));
Contract.EndContractBlock();
return Activator.CreateInstance(assemblyName,
@@ -1680,7 +1288,6 @@ namespace System {
activationAttributes);
}
- [System.Security.SecurityCritical] // auto-generated
internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName,
string typeName,
bool ignoreCase,
@@ -1691,10 +1298,6 @@ namespace System {
Object[] activationAttributes,
Evidence securityAttributes)
{
-#if FEATURE_CAS_POLICY
- Contract.Assert(IsLegacyCasPolicyEnabled || securityAttributes == null);
-#endif // FEATURE_CAS_POLICY
-
PermissionSet.s_fullTrust.Assert();
#pragma warning disable 618
return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
@@ -1718,13 +1321,6 @@ namespace System {
throw new NullReferenceException();
Contract.EndContractBlock();
-#if FEATURE_CAS_POLICY
- if (securityAttributes != null && !IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
return Activator.CreateInstanceFrom(assemblyFile,
typeName,
ignoreCase,
@@ -1760,7 +1356,6 @@ namespace System {
activationAttributes);
}
- [System.Security.SecurityCritical] // auto-generated
internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName,
string typeName,
bool ignoreCase,
@@ -1771,17 +1366,12 @@ namespace System {
Object[] activationAttributes,
Evidence securityAttributes)
{
-#if FEATURE_CAS_POLICY
- Contract.Assert(IsLegacyCasPolicyEnabled || securityAttributes == null);
-#endif // FEATURE_CAS_POLICY
-
PermissionSet.s_fullTrust.Assert();
#pragma warning disable 618
return CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
#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)
{
@@ -1789,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)
{
@@ -1797,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)
{
@@ -1811,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)
@@ -1825,23 +1412,12 @@ 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,
byte[] rawSymbolStore,
Evidence securityEvidence)
{
-#if FEATURE_CAS_POLICY
- if (securityEvidence != null && !IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.nLoadImage(rawAssembly,
rawSymbolStore,
@@ -1851,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,
@@ -1861,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,
@@ -1888,15 +1462,8 @@ namespace System {
Evidence assemblySecurity,
String[] args)
{
-#if FEATURE_CAS_POLICY
- if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile, assemblySecurity);
-
+
if (args == null)
args = new String[0];
@@ -1920,13 +1487,6 @@ namespace System {
byte[] hashValue,
AssemblyHashAlgorithm hashAlgorithm)
{
-#if FEATURE_CAS_POLICY
- if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile,
assemblySecurity,
hashValue,
@@ -1951,9 +1511,6 @@ namespace System {
return nExecuteAssembly(assembly, args);
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public int ExecuteAssemblyByName(String assemblyName)
{
return ExecuteAssemblyByName(assemblyName, (string[])null);
@@ -1973,15 +1530,8 @@ namespace System {
Evidence assemblySecurity,
params String[] args)
{
-#if FEATURE_CAS_POLICY
- if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName, assemblySecurity);
-
+
if (args == null)
args = new String[0];
@@ -2003,15 +1553,8 @@ namespace System {
Evidence assemblySecurity,
params String[] args)
{
-#if FEATURE_CAS_POLICY
- if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName, assemblySecurity);
-
+
if (args == null)
args = new String[0];
@@ -2036,114 +1579,28 @@ namespace System {
}
}
-#if FEATURE_CAS_POLICY
- public Evidence Evidence
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
- get {
- return EvidenceNoDemand;
- }
- }
-
- internal Evidence EvidenceNoDemand {
- [SecurityCritical]
- get {
- if (_SecurityIdentity == null) {
- if (!IsDefaultAppDomain() && nIsDefaultAppDomainForEvidence()) {
-#if !FEATURE_CORECLR
- //
- // V1.x compatibility: If this is an AppDomain created
- // by the default appdomain without an explicit evidence
- // then reuse the evidence of the default AppDomain.
- //
- return GetDefaultDomain().Evidence;
-#else
- Contract.Assert(false,"This code should not be called for core CLR");
-
- // This operation is not allowed
- throw new InvalidOperationException();
-#endif
- }
- else {
- // We can't cache this value, since the VM needs to differentiate between AppDomains
- // which have no user supplied evidence and those which do and it uses the presence
- // of Evidence on the domain to make that switch.
- return new Evidence(new AppDomainEvidenceFactory(this));
- }
- }
- else {
- return _SecurityIdentity.Clone();
- }
- }
- }
-
- internal Evidence InternalEvidence
- {
- get {
- return _SecurityIdentity;
- }
- }
-
- internal EvidenceBase GetHostEvidence(Type type)
- {
- if (_SecurityIdentity != null)
- {
- return _SecurityIdentity.GetHostEvidence(type);
- }
- else
- {
- return new Evidence(new AppDomainEvidenceFactory(this)).GetHostEvidence(type);
- }
- }
-#endif // FEATURE_CAS_POLICY
-
public String FriendlyName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get { return nGetFriendlyName(); }
}
public String BaseDirectory
{
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical]
-#endif
get {
return FusionStore.ApplicationBase;
}
}
-#if FEATURE_FUSION
- public String RelativeSearchPath
- {
- get { return FusionStore.PrivateBinPath; }
- }
-
- public bool ShadowCopyFiles
- {
- get {
- String s = FusionStore.ShadowCopyFiles;
- if((s != null) &&
- (String.Compare(s, "true", StringComparison.OrdinalIgnoreCase) == 0))
- return true;
- else
- return false;
- }
- }
-#endif
-
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
-
+
String fn = nGetFriendlyName();
if (fn != null) {
sb.Append(Environment.GetResourceString("Loader_Name") + fn);
sb.Append(Environment.NewLine);
}
-
+
if(_Policies == null || _Policies.Length == 0)
sb.Append(Environment.GetResourceString("Loader_NoContextPolicies")
+ Environment.NewLine);
@@ -2164,222 +1621,67 @@ namespace System {
return nGetAssemblies(false /* forIntrospection */);
}
-
public Assembly[] ReflectionOnlyGetAssemblies()
{
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
+ // 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
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern bool IsFinalizingForUnload();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle);
-#if FEATURE_FUSION
- // Appends the following string to the private path. Valid paths
- // are of the form "bin;util/i386" etc.
- [System.Security.SecurityCritical] // auto-generated_required
- [Obsolete("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public void AppendPrivatePath(String path)
- {
- if(path == null || path.Length == 0)
- return;
-
- String current = FusionStore.Value[(int) AppDomainSetup.LoaderInformation.PrivateBinPathValue];
- StringBuilder appendPath = StringBuilderCache.Acquire();
-
- if(current != null && current.Length > 0) {
- // See if the last character is a separator
- appendPath.Append(current);
- if((current[current.Length-1] != Path.PathSeparator) &&
- (path[0] != Path.PathSeparator))
- appendPath.Append(Path.PathSeparator);
- }
- appendPath.Append(path);
-
- String result = StringBuilderCache.GetStringAndRelease(appendPath);
- InternalSetPrivateBinPath(result);
- }
-
-
- [System.Security.SecurityCritical] // auto-generated_required
- [Obsolete("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public void ClearPrivatePath()
- {
- InternalSetPrivateBinPath(String.Empty);
- }
-
- [System.Security.SecurityCritical] // auto-generated_required
- [Obsolete("AppDomain.ClearShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public void ClearShadowCopyPath()
- {
- InternalSetShadowCopyPath(String.Empty);
- }
-
- [System.Security.SecurityCritical] // auto-generated_required
- [Obsolete("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public void SetCachePath(String path)
- {
- InternalSetCachePath(path);
- }
-#endif // FEATURE_FUSION
-
- [System.Security.SecurityCritical] // auto-generated_required
public void SetData (string name, object data) {
-#if FEATURE_CORECLR
- if (!name.Equals("LOCATION_URI"))
- {
- // Only LOCATION_URI can be set using AppDomain.SetData
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyLocationURI", name));
- }
-#endif // FEATURE_CORECLR
SetDataHelper(name, data, null);
}
- [System.Security.SecurityCritical] // auto-generated_required
- public void SetData (string name, object data, IPermission permission) {
-#if FEATURE_CORECLR
+ public void SetData (string name, object data, IPermission permission)
+ {
if (!name.Equals("LOCATION_URI"))
{
// Only LOCATION_URI can be set using AppDomain.SetData
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyLocationURI", name));
}
-#endif // FEATURE_CORECLR
+
SetDataHelper(name, data, permission);
}
- [System.Security.SecurityCritical] // auto-generated
- private void SetDataHelper (string name, object data, IPermission permission) {
+ private void SetDataHelper (string name, object data, IPermission permission)
+ {
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
- //
- // Synopsis:
- // IgnoreSystemPolicy is provided as a legacy flag to allow callers to
- // skip enterprise, machine and user policy levels. When this flag is set,
- // any demands triggered in this AppDomain will be evaluated against the
- // AppDomain CAS policy level that is set on the AppDomain.
- // Security Requirements:
- // The caller needs to be fully trusted in order to be able to set
- // this legacy mode.
- // Remarks:
- // There needs to be an AppDomain policy level set before this compat
- // switch can be set on the AppDomain.
- //
-#if FEATURE_FUSION
- if (name.Equals(TargetFrameworkNameAppCompatSetting)) {
- _FusionStore.TargetFrameworkName = (String) data;
- return;
- }
-#if FEATURE_CAS_POLICY
- if (name.Equals("IgnoreSystemPolicy")) {
- lock (this) {
- if (!_HasSetPolicy)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData"));
- }
- new PermissionSet(PermissionState.Unrestricted).Demand();
- }
-#endif
- int key = AppDomainSetup.Locate(name);
-
- if(key == -1) {
- lock (((ICollection)LocalStore).SyncRoot) {
- LocalStore[name] = new object[] {data, permission};
- }
- }
- else {
- if (permission != null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData"));
- // Be sure to call these properties, not Value, since
- // these do more than call Value.
- switch(key) {
- case (int) AppDomainSetup.LoaderInformation.DynamicBaseValue:
- FusionStore.DynamicBase = (string) data;
- break;
- case (int) AppDomainSetup.LoaderInformation.DevPathValue:
- FusionStore.DeveloperPath = (string) data;
- break;
- case (int) AppDomainSetup.LoaderInformation.ShadowCopyDirectoriesValue:
- FusionStore.ShadowCopyDirectories = (string) data;
- break;
- case (int) AppDomainSetup.LoaderInformation.DisallowPublisherPolicyValue:
- if(data != null)
- FusionStore.DisallowPublisherPolicy = true;
- else
- FusionStore.DisallowPublisherPolicy = false;
- break;
- case (int) AppDomainSetup.LoaderInformation.DisallowCodeDownloadValue:
- if (data != null)
- FusionStore.DisallowCodeDownload = true;
- else
- FusionStore.DisallowCodeDownload = false;
- break;
- case (int) AppDomainSetup.LoaderInformation.DisallowBindingRedirectsValue:
- if(data != null)
- FusionStore.DisallowBindingRedirects = true;
- else
- FusionStore.DisallowBindingRedirects = false;
- break;
- case (int) AppDomainSetup.LoaderInformation.DisallowAppBaseProbingValue:
- if(data != null)
- FusionStore.DisallowApplicationBaseProbing = true;
- else
- FusionStore.DisallowApplicationBaseProbing = false;
- break;
- case (int) AppDomainSetup.LoaderInformation.ConfigurationBytesValue:
- FusionStore.SetConfigurationBytes((byte[]) data);
- break;
- default:
- FusionStore.Value[key] = (string) data;
- break;
- }
- }
-#else // FEATURE_FUSION
-#if FEATURE_CORECLR
// SetData should only be used to set values that don't already exist.
+ object[] currentVal;
+ lock (((ICollection)LocalStore).SyncRoot) {
+ LocalStore.TryGetValue(name, out currentVal);
+ }
+ if (currentVal != null && currentVal[0] != null)
{
- object[] currentVal;
- lock (((ICollection)LocalStore).SyncRoot) {
- LocalStore.TryGetValue(name, out currentVal);
- }
- if (currentVal != null && currentVal[0] != null)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce"));
- }
+ throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce"));
}
-#endif // FEATURE_CORECLR
lock (((ICollection)LocalStore).SyncRoot) {
LocalStore[name] = new object[] {data, permission};
}
-#endif // FEATURE_FUSION
}
[Pure]
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
public Object GetData(string name)
{
if(name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
int key = AppDomainSetup.Locate(name);
@@ -2412,43 +1714,11 @@ namespace System {
return FusionStore.ApplicationBase;
case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue:
return FusionStore.ApplicationName;
-#if FEATURE_FUSION
- case (int) AppDomainSetup.LoaderInformation.ConfigurationFileValue:
- return FusionStore.ConfigurationFile;
- case (int) AppDomainSetup.LoaderInformation.DynamicBaseValue:
- return FusionStore.DynamicBase;
- case (int) AppDomainSetup.LoaderInformation.DevPathValue:
- return FusionStore.DeveloperPath;
- case (int) AppDomainSetup.LoaderInformation.PrivateBinPathValue:
- return FusionStore.PrivateBinPath;
- case (int) AppDomainSetup.LoaderInformation.PrivateBinPathProbeValue:
- return FusionStore.PrivateBinPathProbe;
- case (int) AppDomainSetup.LoaderInformation.ShadowCopyDirectoriesValue:
- return FusionStore.ShadowCopyDirectories;
- case (int) AppDomainSetup.LoaderInformation.ShadowCopyFilesValue:
- return FusionStore.ShadowCopyFiles;
- case (int) AppDomainSetup.LoaderInformation.CachePathValue:
- return FusionStore.CachePath;
- case (int) AppDomainSetup.LoaderInformation.LicenseFileValue:
- return FusionStore.LicenseFile;
- case (int) AppDomainSetup.LoaderInformation.DisallowPublisherPolicyValue:
- return FusionStore.DisallowPublisherPolicy;
- case (int) AppDomainSetup.LoaderInformation.DisallowCodeDownloadValue:
- return FusionStore.DisallowCodeDownload;
- case (int) AppDomainSetup.LoaderInformation.DisallowBindingRedirectsValue:
- return FusionStore.DisallowBindingRedirects;
- case (int) AppDomainSetup.LoaderInformation.DisallowAppBaseProbingValue:
- return FusionStore.DisallowApplicationBaseProbing;
- case (int) AppDomainSetup.LoaderInformation.ConfigurationBytesValue:
- return FusionStore.GetConfigurationBytes();
-#endif //FEATURE_FUSION
-
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;
}
}
-
}
// The compat flags are set at domain creation time to indicate that the given breaking
@@ -2477,84 +1747,8 @@ namespace System {
[DllImport(Microsoft.Win32.Win32Native.KERNEL32)]
public static extern int GetCurrentThreadId();
-#if FEATURE_REMOTING
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, ControlAppDomain = true ),
- ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail)]
- public static void Unload(AppDomain domain)
+ internal ApplicationTrust ApplicationTrust
{
- if (domain == null)
- throw new ArgumentNullException("domain");
- Contract.EndContractBlock();
-
- try {
- Int32 domainID = AppDomain.GetIdForUnload(domain);
- if (domainID==0)
- throw new CannotUnloadAppDomainException();
- AppDomain.nUnload(domainID);
- }
- catch(Exception e) {
- throw e; // throw it again to reset stack trace
- }
- }
-#endif
-
- // Explicitly set policy for a domain (providing policy hasn't been set
- // previously). Making this call will guarantee that previously loaded
- // assemblies will be granted permissions based on the default machine
- // policy that was in place prior to this call.
-#if FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated_required
- [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 void SetAppDomainPolicy(PolicyLevel domainPolicy)
- {
- if (domainPolicy == null)
- throw new ArgumentNullException("domainPolicy");
- Contract.EndContractBlock();
-
- if (!IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- // Check that policy has not been set previously.
- lock (this) {
- if (_HasSetPolicy)
- throw new PolicyException(Environment.GetResourceString("Policy_PolicyAlreadySet"));
- _HasSetPolicy = true;
-
- // Make sure that the loader allows us to change security policy
- // at this time (this will throw if not.)
- nChangeSecurityPolicy();
- }
-
- // Add the new policy level.
- SecurityManager.PolicyManager.AddLevel(domainPolicy);
- }
-#endif //#if !FEATURE_CAS_POLICY
-#if FEATURE_CLICKONCE
- public ActivationContext ActivationContext {
- [System.Security.SecurityCritical] // auto-generated_required
- get {
- return _activationContext;
- }
- }
-
- public ApplicationIdentity ApplicationIdentity {
- [System.Security.SecurityCritical] // auto-generated_required
- get {
- return _applicationIdentity;
- }
- }
-#endif // FEATURE_CLICKONCE
-
-
-#if FEATURE_CLICKONCE
- public ApplicationTrust ApplicationTrust {
- [System.Security.SecurityCritical] // auto-generated_required
-#else // FEATURE_CLICKONCE
- internal ApplicationTrust ApplicationTrust {
-#endif // FEATURE_CLICKONCE
get {
if (_applicationTrust == null && _IsFastFullTrustDomain) {
_applicationTrust = new ApplicationTrust(new PermissionSet(PermissionState.Unrestricted));
@@ -2564,66 +1758,8 @@ namespace System {
}
}
-#if FEATURE_IMPERSONATION
- // Set the default principal object to be attached to threads if they
- // attempt to bind to a principal while executing in this appdomain. The
- // default can only be set once.
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)]
- public void SetThreadPrincipal(IPrincipal principal)
- {
- if (principal == null)
- throw new ArgumentNullException("principal");
- Contract.EndContractBlock();
-
- lock (this) {
- // Check that principal has not been set previously.
- if (_DefaultPrincipal != null)
- throw new PolicyException(Environment.GetResourceString("Policy_PrincipalTwice"));
-
- _DefaultPrincipal = principal;
- }
- }
-#endif // FEATURE_IMPERSONATION
-
-#if FEATURE_CAS_POLICY
- // Similar to the above, but sets the class of principal to be created
- // instead.
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)]
- public void SetPrincipalPolicy(PrincipalPolicy policy)
- {
- _PrincipalPolicy = policy;
- }
-#endif
-
-
-#if FEATURE_REMOTING
- // This method gives AppDomain an infinite life time by preventing a lease from being
- // created
- [System.Security.SecurityCritical] // auto-generated_required
- public override Object InitializeLifetimeService()
- {
- return null;
- }
- // This is useful for requesting execution of some code
- // in another appDomain ... the delegate may be defined
- // on a marshal-by-value object or a marshal-by-ref or
- // contextBound object.
- public void DoCallBack(CrossAppDomainDelegate callBackDelegate)
- {
- if (callBackDelegate == null)
- throw new ArgumentNullException("callBackDelegate");
- Contract.EndContractBlock();
-
- callBackDelegate();
- }
-#endif
-
-
public String DynamicDirectory
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
String dyndir = GetDynamicDir();
if (dyndir != null)
@@ -2633,211 +1769,13 @@ namespace System {
}
}
-#if FEATURE_CAS_POLICY
- public static AppDomain CreateDomain(String friendlyName,
- Evidence securityInfo) // Optional
- {
- return CreateDomain(friendlyName,
- securityInfo,
- null);
- }
-
- public static AppDomain CreateDomain(String friendlyName,
- Evidence securityInfo, // Optional
- String appBasePath,
- String appRelativeSearchPath,
- bool shadowCopyFiles)
- {
- AppDomainSetup info = new AppDomainSetup();
- info.ApplicationBase = appBasePath;
- info.PrivateBinPath = appRelativeSearchPath;
- if(shadowCopyFiles)
- info.ShadowCopyFiles = "true";
-
- return CreateDomain(friendlyName,
- securityInfo,
- info);
- }
-#endif // #if FEATURE_CAS_POLICY (not exposed in core)
-
-
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private String GetDynamicDir();
- // Private helpers called from unmanaged code.
-
-#if FEATURE_REMOTING
-
- public static AppDomain CreateDomain(String friendlyName)
- {
- return CreateDomain(friendlyName, null, null);
- }
-
-
- // Marshal a single object into a serialized blob.
- [System.Security.SecurityCritical] // auto-generated
- private static byte[] MarshalObject(Object o)
- {
- CodeAccessPermission.Assert(true);
-
- return Serialize(o);
- }
-
- // Marshal two objects into serialized blobs.
- [System.Security.SecurityCritical] // auto-generated
- private static byte[] MarshalObjects(Object o1, Object o2, out byte[] blob2)
- {
- CodeAccessPermission.Assert(true);
-
- byte[] blob1 = Serialize(o1);
- blob2 = Serialize(o2);
- return blob1;
- }
-
- // Unmarshal a single object from a serialized blob.
- [System.Security.SecurityCritical] // auto-generated
- private static Object UnmarshalObject(byte[] blob)
- {
- CodeAccessPermission.Assert(true);
-
- return Deserialize(blob);
- }
-
- // Unmarshal two objects from serialized blobs.
- [System.Security.SecurityCritical] // auto-generated
- private static Object UnmarshalObjects(byte[] blob1, byte[] blob2, out Object o2)
- {
- CodeAccessPermission.Assert(true);
-
- Object o1 = Deserialize(blob1);
- o2 = Deserialize(blob2);
- return o1;
- }
-
- // Helper routines.
- [System.Security.SecurityCritical] // auto-generated
- private static byte[] Serialize(Object o)
- {
- if (o == null)
- {
- return null;
- }
- else if (o is ISecurityEncodable)
- {
- SecurityElement element = ((ISecurityEncodable)o).ToXml();
- MemoryStream ms = new MemoryStream( 4096 );
- ms.WriteByte( 0 );
- StreamWriter writer = new StreamWriter( ms, Encoding.UTF8 );
- element.ToWriter( writer );
- writer.Flush();
- return ms.ToArray();
- }
- else
- {
- MemoryStream ms = new MemoryStream();
- ms.WriteByte( 1 );
- CrossAppDomainSerializer.SerializeObject(o, ms);
- return ms.ToArray();
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private static Object Deserialize(byte[] blob)
- {
- if (blob == null)
- return null;
-
- if (blob[0] == 0)
- {
- Parser parser = new Parser( blob, Tokenizer.ByteTokenEncoding.UTF8Tokens, 1 );
- SecurityElement root = parser.GetTopElement();
- if (root.Tag.Equals( "IPermission" ) || root.Tag.Equals( "Permission" ))
- {
- IPermission ip = System.Security.Util.XMLUtil.CreatePermission( root, PermissionState.None, false );
-
- if (ip == null)
- {
- return null;
- }
-
- ip.FromXml( root );
-
- return ip;
- }
- else if (root.Tag.Equals( "PermissionSet" ))
- {
- PermissionSet permissionSet = new PermissionSet();
-
- permissionSet.FromXml( root, false, false );
-
- return permissionSet;
- }
- else if (root.Tag.Equals( "PermissionToken" ))
- {
- PermissionToken pToken = new PermissionToken();
-
- pToken.FromXml( root );
-
- return pToken;
- }
- else
- {
- return null;
- }
-
- }
- else
- {
- Object obj = null;
- using(MemoryStream stream = new MemoryStream( blob, 1, blob.Length - 1 )) {
- obj = CrossAppDomainSerializer.DeserializeObject(stream);
- }
-
- Contract.Assert( !(obj is IPermission), "IPermission should be xml deserialized" );
- Contract.Assert( !(obj is PermissionSet), "PermissionSet should be xml deserialized" );
-
- return obj;
- }
- }
-
-#endif // FEATURE_REMOTING
-
-#if !FEATURE_CORECLR
- //
- // Called by the VM if ICLRExecutionManager::Pause is called with the PAUSE_APP_DOMAINS flag.
- // This mimics the behavior of the CoreCLR FAS (fast application switching) model, to ensure
- // that code that depends on things happening in a particular order will work.
- //
- [System.Security.SecurityCritical]
- internal static void Pause()
- {
- AppDomainPauseManager.Instance.Pausing();
- AppDomainPauseManager.Instance.Paused();
- }
-
- //
- // Called by the VM if ICLRExecutionManager::Resume is called after ICLRExecutionManager::Pause
- // was called with the PAUSE_APP_DOMAINS flag.
- // This mimics the behavior of the CoreCLR FAS (fast application switching) model, to ensure
- // that code that depends on things happening in a particular order will work.
- //
- [System.Security.SecurityCritical]
- internal static void Resume()
- {
- if (AppDomainPauseManager.IsPaused)
- {
- AppDomainPauseManager.Instance.Resuming();
- AppDomainPauseManager.Instance.Resumed();
- }
- }
-#endif
-
private AppDomain() {
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)
@@ -2849,45 +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
-#if FEATURE_REMOTING
- internal void CreateRemotingData()
- {
- lock(this) {
- if (_RemotingData == null)
- _RemotingData = new DomainSpecificRemotingData();
- }
- }
-
- internal DomainSpecificRemotingData RemotingData
- {
- get
- {
- if (_RemotingData == null)
- CreateRemotingData();
-
- return _RemotingData;
- }
- }
-#endif // FEATURE_REMOTING
-
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String nGetFriendlyName();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool nIsDefaultAppDomainForEvidence();
@@ -2899,7 +1810,6 @@ namespace System {
public event EventHandler ProcessExit
{
- [System.Security.SecuritySafeCritical] // auto-generated_required
add
{
if (value != null)
@@ -2919,7 +1829,6 @@ namespace System {
public event EventHandler DomainUnload
{
- [System.Security.SecuritySafeCritical] // auto-generated_required
add
{
if (value != null)
@@ -2929,9 +1838,6 @@ namespace System {
_domainUnload += value;
}
}
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
remove
{
lock(this)
@@ -2942,7 +1848,6 @@ namespace System {
public event UnhandledExceptionEventHandler UnhandledException
{
- [System.Security.SecurityCritical] // auto-generated_required
add
{
if (value != null)
@@ -2952,7 +1857,6 @@ namespace System {
_unhandledException += value;
}
}
- [System.Security.SecurityCritical] // auto-generated_required
remove
{
lock(this)
@@ -2967,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)
@@ -2977,7 +1880,6 @@ namespace System {
_firstChanceException += value;
}
}
- [System.Security.SecurityCritical] // auto-generated_required
remove
{
lock(this)
@@ -2996,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;
@@ -3016,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;
@@ -3036,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;
@@ -3058,36 +1957,6 @@ namespace System {
return null;
}
-#if FEATURE_REFLECTION_ONLY_LOAD
-
- private RuntimeAssembly OnReflectionOnlyAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
- {
- ResolveEventHandler eventHandler = ReflectionOnlyAssemblyResolve;
- if (eventHandler != null) {
-
- Delegate[] ds = eventHandler.GetInvocationList();
- int len = ds.Length;
- for (int i = 0; i < len; i++) {
- Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName, assembly));
- RuntimeAssembly ret = GetRuntimeAssembly(asm);
- if (ret != null)
- return ret;
- }
- }
-
- return null;
- }
-
-#if FEATURE_COMINTEROP
- // Called by VM - code:CLRPrivTypeCacheReflectionOnlyWinRT::RaiseNamespaceResolveEvent
- private RuntimeAssembly[] OnReflectionOnlyNamespaceResolveEvent(RuntimeAssembly assembly, string namespaceName)
- {
- return System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.OnReflectionOnlyNamespaceResolveEvent(this, assembly, namespaceName);
- }
-#endif // FEATURE_COMINTEROP
-
-#endif // FEATURE_REFLECTION_ONLY_LOAD
-
#if FEATURE_COMINTEROP
// Called by VM - code:CLRPrivTypeCacheWinRT::RaiseDesignerNamespaceResolveEvent
private string[] OnDesignerNamespaceResolveEvent(string namespaceName)
@@ -3099,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;
}
@@ -3133,319 +2002,33 @@ namespace System {
}
}
-#if FEATURE_FUSION
- private void TurnOnBindingRedirects()
- {
- _FusionStore.DisallowBindingRedirects = false;
- }
-#endif
-
- // This will throw a CannotUnloadAppDomainException if the appdomain is
- // in another process.
-#if FEATURE_REMOTING
- [System.Security.SecurityCritical] // auto-generated
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- internal static Int32 GetIdForUnload(AppDomain domain)
- {
- if (RemotingServices.IsTransparentProxy(domain))
- {
- return RemotingServices.GetServerDomainIdForProxy(domain);
- }
- else
- return domain.Id;
- }
-#endif
-
// 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);
-
-#if FEATURE_REMOTING
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static internal extern AppDomain GetDefaultDomain();
-#endif
-
-#if FEATURE_IMPERSONATION
- // Internal routine to retrieve the default principal object. If this is
- // called before the principal has been explicitly set, it will
- // automatically allocate a default principal based on the policy set by
- // SetPrincipalPolicy.
- internal IPrincipal GetThreadPrincipal()
- {
- IPrincipal principal = null;
- if (_DefaultPrincipal == null) {
-#if FEATURE_CAS_POLICY
- switch (_PrincipalPolicy) {
- case PrincipalPolicy.NoPrincipal:
- principal = null;
- break;
- case PrincipalPolicy.UnauthenticatedPrincipal:
- principal = new GenericPrincipal(new GenericIdentity("", ""),
- new String[] {""});
- break;
- case PrincipalPolicy.WindowsPrincipal:
- principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
- break;
- default:
- principal = null;
- break;
- }
-#else
- principal = new GenericPrincipal(new GenericIdentity("", ""),
- new String[] {""});
-
-#endif
- }
- else
- principal = _DefaultPrincipal;
-
- return principal;
- }
-#endif // FEATURE_IMPERSONATION
-
-#if FEATURE_REMOTING
-
- [System.Security.SecurityCritical] // auto-generated
- internal void CreateDefaultContext()
- {
- lock(this) {
- // if it has not been created we ask the Context class to
- // create a new default context for this appdomain.
- if (_DefaultContext == null)
- _DefaultContext = Context.CreateDefaultContext();
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal Context GetDefaultContext()
- {
- if (_DefaultContext == null)
- CreateDefaultContext();
- return _DefaultContext;
- }
-
- // Ensure that evidence provided when creating an AppDomain would not have been used to create a
- // sandbox in legacy CAS mode. If it could have been used to create a sandbox, and we're not in CAS
- // mode, then we throw an exception to prevent acciental creation of unsandboxed domains where a
- // sandbox would have been expected.
- [SecuritySafeCritical]
- internal static void CheckDomainCreationEvidence(AppDomainSetup creationDomainSetup,
- Evidence creationEvidence)
- {
- if (creationEvidence != null && !CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- if (creationDomainSetup == null || creationDomainSetup.ApplicationTrust == null)
- {
- // We allow non-null evidence in CAS mode to support the common pattern of passing in
- // AppDomain.CurrentDomain.Evidence. Since the zone evidence must have been changed
- // if the user has any expectation of sandboxing the domain under legacy CAS policy,
- // we use a zone comparison to check for this pattern. A strict comparison will not
- // work, since MSDN samples for creating a domain show using a modified version of the
- // current domain's evidence and we would capturce people who copied and pasted these
- // samples without intending to sandbox.
- Zone creatorsZone = CurrentDomain.EvidenceNoDemand.GetHostEvidence<Zone>();
- SecurityZone creatorsSecurityZone = creatorsZone != null ?
- creatorsZone.SecurityZone :
- SecurityZone.MyComputer;
-
- Zone suppliedZone = creationEvidence.GetHostEvidence<Zone>();
- if (suppliedZone != null)
- {
- if (suppliedZone.SecurityZone != creatorsSecurityZone &&
- suppliedZone.SecurityZone != SecurityZone.MyComputer)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
- }
- }
- }
- }
-
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, ControlAppDomain = true )]
- public static AppDomain CreateDomain(String friendlyName,
- Evidence securityInfo,
- AppDomainSetup info)
- {
- return InternalCreateDomain(friendlyName, securityInfo, info);
- }
-#else
- internal static AppDomain CreateDomain(String friendlyName,
- Evidence securityInfo,
- AppDomainSetup info)
- {
- return InternalCreateDomain(friendlyName, securityInfo, info);
- }
-#endif
-
- [System.Security.SecurityCritical] // auto-generated
- internal static AppDomain InternalCreateDomain(String friendlyName,
- Evidence securityInfo,
- AppDomainSetup info)
- {
- if (friendlyName == null)
- throw new ArgumentNullException("friendlyName", Environment.GetResourceString("ArgumentNull_String"));
-
- Contract.EndContractBlock();
-
- AppDomain.CheckCreateDomainSupported();
-
- if (info == null)
- info = new AppDomainSetup();
- if (info.TargetFrameworkName == null)
- info.TargetFrameworkName = AppDomain.CurrentDomain.GetTargetFrameworkName();
- AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
- if (domainManager != null)
- return domainManager.CreateDomain(friendlyName, securityInfo, info);
-
- // No AppDomainManager is set up for this domain
-
- // If evidence is provided, we check to make sure that is allowed.
- if (securityInfo != null)
- {
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
-
- // If we're potentially trying to sandbox without using a homogenous domain, we need to reject
- // the domain creation.
- CheckDomainCreationEvidence(info, securityInfo);
- }
-
- return nCreateDomain(friendlyName,
- info,
- securityInfo,
- securityInfo == null ? AppDomain.CurrentDomain.InternalEvidence : null,
- AppDomain.CurrentDomain.GetSecurityDescriptor());
- }
-#endif // FEATURE_REMOTING
-
-#if FEATURE_CAS_POLICY
-
- public static AppDomain CreateDomain (string friendlyName,
- Evidence securityInfo,
- AppDomainSetup info,
- PermissionSet grantSet,
- params StrongName[] fullTrustAssemblies)
- {
- if (info == null)
- throw new ArgumentNullException("info");
- if (info.ApplicationBase == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AppDomainSandboxAPINeedsExplicitAppBase"));
- Contract.EndContractBlock();
-
- if (fullTrustAssemblies == null)
- {
- fullTrustAssemblies = new StrongName[0];
- }
-
- info.ApplicationTrust = new ApplicationTrust(grantSet, fullTrustAssemblies);
- return CreateDomain(friendlyName, securityInfo, info);
- }
-
- public static AppDomain CreateDomain(String friendlyName,
- Evidence securityInfo, // Optional
- String appBasePath,
- String appRelativeSearchPath,
- bool shadowCopyFiles,
- AppDomainInitializer adInit,
- string[] adInitArgs)
- {
- AppDomainSetup info = new AppDomainSetup();
- info.ApplicationBase = appBasePath;
- info.PrivateBinPath = appRelativeSearchPath;
- info.AppDomainInitializer=adInit;
- info.AppDomainInitializerArguments=adInitArgs;
- if(shadowCopyFiles)
- info.ShadowCopyFiles = "true";
-
- return CreateDomain(friendlyName,
- securityInfo,
- info);
- }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nSetNativeDllSearchDirectories(string paths);
-#endif
- [System.Security.SecurityCritical] // auto-generated
private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
{
Contract.Requires(info != null);
-#if FEATURE_FUSION
- if (oldInfo == null) {
-
- // Create the application base and configuration file from the imagelocation
- // passed in or use the Win32 Image name.
- if(info.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] == null ||
- info.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] == null )
-#else
if (info.ApplicationBase == null)
-#endif
-
{
-#if FEATURE_FUSION
- AppDomain defaultDomain = GetDefaultDomain();
- if (this == defaultDomain) {
- // The default domain gets its defaults from the main process.
- info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
- }
- else {
- // Other domains get their defaults from the default domain. This way, a host process
- // can use AppDomainManager to set up the defaults for every domain created in the process.
- if (info.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] == null)
- info.ConfigurationFile = defaultDomain.FusionStore.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue];
- if (info.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] == null)
- info.ApplicationBase = defaultDomain.FusionStore.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue];
- if (info.Value[(int) AppDomainSetup.LoaderInformation.ApplicationNameValue] == null)
- info.ApplicationName = defaultDomain.FusionStore.Value[(int) AppDomainSetup.LoaderInformation.ApplicationNameValue];
- }
-#else
info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
-#endif
-
- }
-
-#if FEATURE_FUSION
- // If there is no relative path then check the
- // environment
- if(info.Value[(int) AppDomainSetup.LoaderInformation.PrivateBinPathValue] == null)
- info.PrivateBinPath = Environment.nativeGetEnvironmentVariable(AppDomainSetup.PrivateBinPathEnvironmentVariable);
-
- // Add the developer path if it exists on this
- // machine.
- if(info.DeveloperPath == null)
- info.DeveloperPath = RuntimeEnvironment.GetDeveloperPath();
-
}
-
- // Set up the fusion context
- IntPtr fusionContext = GetFusionContext();
- info.SetupFusionContext(fusionContext, oldInfo);
- // Set loader optimization policy
-#else
#if FEATURE_VERSIONING
nCreateContext();
#endif // FEATURE_VERSIONING
-#endif // FEATURE_FUSION
#if FEATURE_LOADER_OPTIMIZATION
if (info.LoaderOptimization != LoaderOptimization.NotSpecified || (oldInfo != null && info.LoaderOptimization != oldInfo.LoaderOptimization))
UpdateLoaderOptimization(info.LoaderOptimization);
-#endif
-
-
-
+#endif
// This must be the last action taken
_FusionStore = info;
}
@@ -3475,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,
@@ -3488,54 +2070,6 @@ namespace System {
byte[] serializedEvidence = null;
bool generateDefaultEvidence = false;
-#if FEATURE_CAS_POLICY
- // serialize evidence
- EvidenceCollection evidenceCollection = null;
-
- if (providedSecurityInfo != null || creatorsSecurityInfo != null)
- {
- // If we're just passing through AppDomain.CurrentDomain.Evidence, and that evidence is just
- // using the standard runtime AppDomainEvidenceFactory, don't waste time serializing it and
- // deserializing it back -- instead, we can recreate a new AppDomainEvidenceFactory in the new
- // domain. We only want to do this if there is no HostSecurityManager, otherwise the
- // HostSecurityManager could have added additional evidence on top of our standard factory.
- HostSecurityManager hsm = CurrentDomain.DomainManager != null ? CurrentDomain.DomainManager.HostSecurityManager : null;
- bool hostMayContributeEvidence = hsm != null &&
- hsm.GetType() != typeof(HostSecurityManager) &&
- (hsm.Flags & HostSecurityManagerOptions.HostAppDomainEvidence) == HostSecurityManagerOptions.HostAppDomainEvidence;
- if (!hostMayContributeEvidence)
- {
- if (providedSecurityInfo != null &&
- providedSecurityInfo.IsUnmodified &&
- providedSecurityInfo.Target != null &&
- providedSecurityInfo.Target is AppDomainEvidenceFactory)
- {
- providedSecurityInfo = null;
- generateDefaultEvidence = true;
- }
- if (creatorsSecurityInfo != null &&
- creatorsSecurityInfo.IsUnmodified &&
- creatorsSecurityInfo.Target != null &&
- creatorsSecurityInfo.Target is AppDomainEvidenceFactory)
- {
- creatorsSecurityInfo = null;
- generateDefaultEvidence = true;
- }
- }
- }
- if ((providedSecurityInfo != null) ||
- (creatorsSecurityInfo != null)) {
- evidenceCollection = new EvidenceCollection();
- evidenceCollection.ProvidedSecurityInfo = providedSecurityInfo;
- evidenceCollection.CreatorsSecurityInfo = creatorsSecurityInfo;
- }
-
- if (evidenceCollection != null) {
- serializedEvidence =
- CrossAppDomainSerializer.SerializeObject(evidenceCollection).GetBuffer();
- }
-#endif // FEATURE_CAS_POLICY
-
AppDomainInitializerInfo initializerInfo = null;
if (setup!=null && setup.AppDomainInitializer!=null)
initializerInfo=new AppDomainInitializerInfo(setup.AppDomainInitializer);
@@ -3543,7 +2077,6 @@ namespace System {
// will travel x-Ad, drop non-agile data
AppDomainSetup newSetup = new AppDomainSetup(setup, false);
-#if FEATURE_CORECLR
// Remove the special AppDomainCompatSwitch entries from the set of name value pairs
// And add them to the AppDomainSetup
//
@@ -3551,7 +2084,7 @@ namespace System {
// Desktop code should use System.AppDomain.CreateDomain() or
// System.AppDomainManager.CreateDomain() and add the flags to the AppDomainSetup
List<String> compatList = new List<String>();
-
+
if(propertyNames!=null && propertyValues != null)
{
for (int i=0; i<propertyNames.Length; i++)
@@ -3559,7 +2092,7 @@ namespace System {
if(String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0)
{
compatList.Add(propertyValues[i]);
- propertyNames[i] = null;
+ propertyNames[i] = null;
propertyValues[i] = null;
}
@@ -3568,10 +2101,8 @@ namespace System {
if (compatList.Count > 0)
{
newSetup.SetCompatibilitySwitches(compatList);
- }
+ }
}
-#endif // FEATURE_CORECLR
-
return new Object[]
{
@@ -3587,8 +2118,6 @@ namespace System {
};
} // PrepareDataForSetup
-
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static Object Setup(Object arg)
{
@@ -3604,44 +2133,47 @@ namespace System {
AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5];
string sandboxName = (string)args[6];
string[] propertyNames = (string[])args[7]; // can contain null elements
- string[] propertyValues = (string[])args[8]; // can contain null elements
+ string[] propertyValues = (string[])args[8]; // can contain null elements
// extract evidence
Evidence providedSecurityInfo = null;
Evidence creatorsSecurityInfo = null;
-
AppDomain ad = AppDomain.CurrentDomain;
AppDomainSetup newSetup=new AppDomainSetup(setup,false);
if(propertyNames!=null && propertyValues != null)
{
-#if FEATURE_CORECLR
- StringBuilder normalisedAppPathList = null;
-#endif // FEATURE_CORECLR
+ 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++)
{
if(propertyNames[i]=="APPBASE") // make sure in sync with Fusion
{
if(propertyValues[i]==null)
throw new ArgumentNullException("APPBASE");
-
- if (Path.IsRelative(propertyValues[i]))
+
+ if (PathInternal.IsPartiallyQualified(propertyValues[i]))
throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
-
- }
-#if FEATURE_CAS_POLICY
- else if(propertyNames[i]=="LOCATION_URI" && providedSecurityInfo==null)
- {
- providedSecurityInfo=new Evidence();
- providedSecurityInfo.AddHostEvidence(new Url(propertyValues[i]));
- ad.SetDataHelper(propertyNames[i],propertyValues[i],null);
}
-#endif // FEATURE_CAS_POLICY
#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");
@@ -3656,119 +2188,32 @@ namespace System {
}
}
#endif // FEATURE_LOADER_OPTIMIZATION
-#if FEATURE_CORECLR
- 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 (Path.IsRelative(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
}
-#endif
-
}
}
-#if !FEATURE_CORECLR
- AppDomainSortingSetupInfo sortingSetup = newSetup._AppDomainSortingSetupInfo;
-
- if(sortingSetup != null)
- {
- if(sortingSetup._pfnIsNLSDefinedString == IntPtr.Zero || sortingSetup._pfnCompareStringEx == IntPtr.Zero || sortingSetup._pfnLCMapStringEx == IntPtr.Zero || sortingSetup._pfnFindNLSStringEx == IntPtr.Zero
- || sortingSetup._pfnCompareStringOrdinal == IntPtr.Zero || sortingSetup._pfnGetNLSVersionEx == IntPtr.Zero)
- {
-
- if(!(sortingSetup._pfnIsNLSDefinedString == IntPtr.Zero && sortingSetup._pfnCompareStringEx == IntPtr.Zero && sortingSetup._pfnLCMapStringEx == IntPtr.Zero && sortingSetup._pfnFindNLSStringEx == IntPtr.Zero
- && sortingSetup._pfnCompareStringOrdinal == IntPtr.Zero && sortingSetup._pfnGetNLSVersionEx == IntPtr.Zero))
- {
- // Some functions defined but not all of them.
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_NotAllCustomSortingFuncsDefined"));
- }
-
- }
- }
-#endif
-
ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup
// technically, we don't need this, newSetup refers to the same object as FusionStore
// but it's confusing since it isn't immediately obvious whether we have a ref or a copy
AppDomainSetup adSetup = ad.FusionStore;
-#if FEATURE_CORECLR
adSetup.InternalSetApplicationTrust(sandboxName);
-#endif // FEATURE_CORECLR
-
-#if !FEATURE_CORECLR // not used by coreclr
- if (serializedEvidence != null) {
- EvidenceCollection evidenceCollection = (EvidenceCollection)
- CrossAppDomainSerializer.DeserializeObject(new MemoryStream(serializedEvidence));
- providedSecurityInfo = evidenceCollection.ProvidedSecurityInfo;
- creatorsSecurityInfo = evidenceCollection.CreatorsSecurityInfo;
- }
-#endif
+
// set up the friendly name
ad.nSetupFriendlyName(friendlyName);
@@ -3785,11 +2230,6 @@ namespace System {
ad.SetAppDomainManagerType(adSetup.AppDomainManagerAssembly, adSetup.AppDomainManagerType);
}
-#if FEATURE_APTCA
- // set any conditial-aptca visible assemblies
- ad.PartialTrustVisibleAssemblies = adSetup.PartialTrustVisibleAssemblies;
-#endif // FEATURE_APTCA
-
ad.CreateAppDomainManager(); // could modify FusionStore's object
ad.InitializeDomainSecurity(providedSecurityInfo,
creatorsSecurityInfo,
@@ -3802,221 +2242,81 @@ namespace System {
adSetup.AppDomainInitializer=initializerInfo.Unwrap();
RunInitializer(adSetup);
- // Activate the application if needed.
-#if FEATURE_CLICKONCE
- ObjectHandle oh = null;
- if (adSetup.ActivationArguments != null && adSetup.ActivationArguments.ActivateInstance)
- oh = Activator.CreateInstance(ad.ActivationContext);
- return RemotingServices.MarshalInternal(oh, null, null);
-#else
return null;
-#endif // FEATURE_CLICKONCE
}
- [SecuritySafeCritical]
- internal static string NormalizePath(string path, bool fullCheck)
+ private static string NormalizeAppPaths(string values)
{
-#if FEATURE_PATHCOMPAT
- // Appcontext switches can't currently be safely hit during AppDomain bringup
- return Path.LegacyNormalizePath(
- path: path,
- fullCheck: fullCheck,
- maxPathLength: PathInternal.MaxShortPath,
- expandShortPaths: true);
-#else
- return Path.NormalizePath(
- path: path,
- fullCheck: fullCheck,
- expandShortPaths: true);
-#endif
- }
+ int estimatedLength = values.Length + 1; // +1 for extra separator temporarily added at end
+ StringBuilder sb = StringBuilderCache.Acquire(estimatedLength);
-#if FEATURE_APTCA
- // Called from DomainAssembly in Conditional APTCA cases
- [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
- [SecuritySafeCritical]
- private bool IsAssemblyOnAptcaVisibleList(RuntimeAssembly assembly)
- {
- if (_aptcaVisibleAssemblies == null)
- return false;
-
- AssemblyName assemblyName = assembly.GetName();
- String name = assemblyName.GetNameWithPublicKey();
-
- name = name.ToUpperInvariant();
-
- int index = Array.BinarySearch<string>(_aptcaVisibleAssemblies, name,
- StringComparer.OrdinalIgnoreCase);
- return (index >=0);
-
- }
-
- //Used to binary search the list of C-APTCA strings for an AssemblyName. It compares assembly name
- //and public key token.
- private class CAPTCASearcher : IComparer
- {
- int IComparer.Compare(object /*string*/lhs, object /*AssemblyName*/rhs)
+ for (int pos = 0; pos < values.Length; pos++)
{
- AssemblyName captcaEntry = new AssemblyName((string)lhs);
- AssemblyName comparand = (AssemblyName)rhs;
- int nameComp = string.Compare(captcaEntry.Name,
- comparand.Name,
- StringComparison.OrdinalIgnoreCase);
- if (nameComp != 0)
- {
- return nameComp;
- }
-
- //simple names match. Compare public key tokens.
- byte[] lhsKey = captcaEntry.GetPublicKeyToken();
- byte[] rhsKey = comparand.GetPublicKeyToken();
+ string path;
- // We require both sides have a public key token
- if (lhsKey == null)
+ int nextPos = values.IndexOf(Path.PathSeparator, pos);
+ if (nextPos == -1)
{
- return -1;
+ path = values.Substring(pos);
+ pos = values.Length - 1;
}
- if (rhsKey == null)
- {
- return 1;
- }
- if (lhsKey.Length < rhsKey.Length)
- {
- return -1;
- }
- if (lhsKey.Length > rhsKey.Length)
+ else
{
- return 1;
+ path = values.Substring(pos, nextPos - pos);
+ pos = nextPos;
}
- // Tokens seem valid - make sure the compare correctly
- for (int i = 0; i < lhsKey.Length; ++i)
- {
- byte lhsByte = lhsKey[i];
- byte rhsByte = rhsKey[i];
+ // Skip empty directories
+ if (path.Length == 0)
+ continue;
- if (lhsByte < rhsByte)
- {
- return -1;
- }
- if (lhsByte > rhsByte)
- {
- return 1;
- }
- }
+ if (PathInternal.IsPartiallyQualified(path))
+ throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"));
- //They match.
- return 0;
+ string appPath = NormalizePath(path, fullCheck: true);
+ sb.Append(appPath);
+ sb.Append(Path.PathSeparator);
}
- }
- [System.Security.SecurityCritical]
- private unsafe bool IsAssemblyOnAptcaVisibleListRaw(char * namePtr, int nameLen, byte * keyTokenPtr,
- int keyTokenLen)
- {
- //This version is used for checking ngen dependencies against the C-APTCA list. It lets us
- //reject ngen images that depend on an assembly that has been disabled in the current domain.
- //Since we only have the public key token in the ngen image, we'll check against that. The
- //rationale is that if you have a public key token collision in your process you have many
- //problems. Since the source of this public key token is an ngen image for a full trust
- //assembly, there is essentially no risk to the reduced check.
- if (_aptcaVisibleAssemblies == null)
- return false;
-
- string name = new string(namePtr, 0, nameLen);
- byte[] keyToken = new byte[keyTokenLen];
- for( int i = 0; i < keyToken.Length; ++i )
- keyToken[i] = keyTokenPtr[i];
-
- AssemblyName asmName = new AssemblyName();
- asmName.Name = name;
- asmName.SetPublicKeyToken(keyToken);
- try
+ // Strip the last separator
+ if (sb.Length > 0)
{
- int index = Array.BinarySearch(_aptcaVisibleAssemblies, asmName, new CAPTCASearcher());
- return (index >= 0);
+ sb.Remove(sb.Length - 1, 1);
}
- catch (InvalidOperationException) { /* Can happen for poorly formed assembly names */ return false; }
+
+ return StringBuilderCache.GetStringAndRelease(sb);
}
-#endif
+ internal static string NormalizePath(string path, bool fullCheck)
+ {
+ return Path.GetFullPath(path);
+ }
// 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
// the default domain. We will just take the winner of these two.
// (eg. one thread doing a com call and another doing attach for IJW)
- lock (this) {
- if(_FusionStore == null) {
+ lock (this)
+ {
+ if(_FusionStore == null)
+ {
AppDomainSetup setup = new AppDomainSetup();
-#if FEATURE_CORECLR
+
// always use internet permission set
setup.InternalSetApplicationTrust("Internet");
-#endif // FEATURE_CORECLR
-#if FEATURE_FUSION
- setup.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
- if(path != null)
- setup.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] = path;
- if(configFile != null)
- setup.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] = configFile;
-
- // Default fusion context starts with binding redirects turned off.
- if (!allowRedirects)
- setup.DisallowBindingRedirects = true;
-#endif
-
-#if !FEATURE_CORECLR
- if (propertyNames != null) {
- BCLDebug.Assert(propertyValues != null, "propertyValues != null");
- BCLDebug.Assert(propertyNames.Length == propertyValues.Length, "propertyNames.Length == propertyValues.Length");
-
- for (int i = 0; i < propertyNames.Length; ++i) {
- if (String.Equals(propertyNames[i], "PARTIAL_TRUST_VISIBLE_ASSEMBLIES", StringComparison.Ordinal)) {
- // The value of the PARTIAL_TRUST_VISIBLE_ASSEMBLIES property is a semicolon
- // delimited list of assembly names to add to the
- // PartialTrustVisibleAssemblies setting of the domain setup
- if (propertyValues[i] != null) {
- if (propertyValues[i].Length > 0) {
- setup.PartialTrustVisibleAssemblies = propertyValues[i].Split(';');
- }
- else {
- setup.PartialTrustVisibleAssemblies = new string[0];
- }
- }
- }
- else {
- // In v4 we disallow anything but PARTIAL_TRUST_VISIBLE_ASSEMBLIES to come
- // in via the default domain properties. That restriction could be lifted
- // in a future release, at which point this assert should be removed.
- //
- // This should be kept in sync with the real externally facing filter code
- // in CorHost2::SetPropertiesForDefaultAppDomain
- BCLDebug.Assert(false, "Unexpected default domain property");
- }
- }
- }
-#endif // !FEATURE_CORECLR
-
-#if FEATURE_APTCA
- // Propigate the set of conditional APTCA assemblies that will be used in the default
- // domain onto the domain itself and also into the VM
- PartialTrustVisibleAssemblies = setup.PartialTrustVisibleAssemblies;
-#endif // FEATURE_APTCA
-
SetupFusionStore(setup, null);
}
}
}
#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;
@@ -4024,36 +2324,10 @@ namespace System {
}
}
#endif
-
-#if FEATURE_FUSION
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern IntPtr GetFusionContext();
-#endif // FEATURE_FUSION
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetSecurityDescriptor();
-#if FEATURE_REMOTING
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern AppDomain nCreateDomain(String friendlyName,
- AppDomainSetup setup,
- Evidence providedSecurityInfo,
- Evidence creatorsSecurityInfo,
- IntPtr parentSecurityDescriptor);
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern ObjRef nCreateInstance(String friendlyName,
- AppDomainSetup setup,
- Evidence providedSecurityInfo,
- Evidence creatorsSecurityInfo,
- IntPtr parentSecurityDescriptor);
-#endif
-
- [SecurityCritical]
private void SetupDomainSecurity(Evidence appDomainEvidence,
IntPtr creatorsSecurityDescriptor,
bool publishAppDomain)
@@ -4066,7 +2340,6 @@ namespace System {
}
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetupDomainSecurity(AppDomainHandle appDomain,
@@ -4074,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);
@@ -4084,39 +2356,10 @@ namespace System {
#endif // FEATURE_COMINTEROP
#if FEATURE_LOADER_OPTIMIZATION
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void UpdateLoaderOptimization(LoaderOptimization optimization);
#endif
-#if FEATURE_FUSION
- //
- // This is just designed to prevent compiler warnings.
- // This field is used from native, but we need to prevent the compiler warnings.
- //
-
- [System.Security.SecurityCritical] // auto-generated_required
- [Obsolete("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public void SetShadowCopyPath(String path)
- {
- InternalSetShadowCopyPath(path);
- }
-
- [System.Security.SecurityCritical] // auto-generated_required
- [Obsolete("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public void SetShadowCopyFiles()
- {
- InternalSetShadowCopyFiles();
- }
-
- [System.Security.SecurityCritical] // auto-generated_required
- [Obsolete("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public void SetDynamicBase(String path)
- {
- InternalSetDynamicBase(path);
- }
-#endif // FEATURE_FUSION
-
public AppDomainSetup SetupInformation
{
get {
@@ -4124,84 +2367,19 @@ namespace System {
}
}
-#if FEATURE_FUSION
- [System.Security.SecurityCritical] // auto-generated
- internal void InternalSetShadowCopyPath(String path)
- {
- if (path != null)
- {
- IntPtr fusionContext = GetFusionContext();
- AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyDirectoriesKey, path);
- }
- FusionStore.ShadowCopyDirectories = path;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal void InternalSetShadowCopyFiles()
- {
- IntPtr fusionContext = GetFusionContext();
- AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyFilesKey, "true");
- FusionStore.ShadowCopyFiles = "true";
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal void InternalSetCachePath(String path)
- {
- FusionStore.CachePath = path;
- if (FusionStore.Value[(int) AppDomainSetup.LoaderInformation.CachePathValue] != null)
- {
- IntPtr fusionContext = GetFusionContext();
- AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.CachePathKey,
- FusionStore.Value[(int) AppDomainSetup.LoaderInformation.CachePathValue]);
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal void InternalSetPrivateBinPath(String path)
- {
- IntPtr fusionContext = GetFusionContext();
- AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.PrivateBinPathKey, path);
- FusionStore.PrivateBinPath = path;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal void InternalSetDynamicBase(String path)
- {
- FusionStore.DynamicBase = path;
- if (FusionStore.Value[(int) AppDomainSetup.LoaderInformation.DynamicBaseValue] != null)
- {
- IntPtr fusionContext = GetFusionContext();
- AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.DynamicBaseKey,
- FusionStore.Value[(int) AppDomainSetup.LoaderInformation.DynamicBaseValue]);
- }
- }
-#endif // FEATURE_FUSION
-
- [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);
-#if FEATURE_CAS_POLICY
- [SecurityCritical]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool GetIsLegacyCasPolicyEnabled(AppDomainHandle domain);
-#endif // FEATURE_CAS_POLICY
-
public PermissionSet PermissionSet
{
// SecurityCritical because permissions can contain sensitive information such as paths
- [SecurityCritical]
get
{
PermissionSet grantSet = null;
@@ -4220,7 +2398,6 @@ namespace System {
public bool IsFullyTrusted
{
- [SecuritySafeCritical]
get
{
PermissionSet grantSet = null;
@@ -4239,62 +2416,9 @@ namespace System {
}
}
-#if FEATURE_CAS_POLICY
- internal bool IsLegacyCasPolicyEnabled
- {
- [SecuritySafeCritical]
- get
- {
- return GetIsLegacyCasPolicyEnabled(GetNativeHandle());
- }
- }
-
- // Determine what this homogenous domain thinks the grant set should be for a specific set of evidence
- [SecuritySafeCritical]
- internal PermissionSet GetHomogenousGrantSet(Evidence evidence)
- {
- Contract.Assert(evidence != null);
- Contract.Assert(IsHomogenous);
- Contract.Assert(evidence.GetHostEvidence<GacInstalled>() == null);
-
- if (_IsFastFullTrustDomain)
- {
- return new PermissionSet(PermissionState.Unrestricted);
- }
-
- // If the ApplicationTrust's full trust list calls out the assembly, then it is fully trusted
- if (evidence.GetDelayEvaluatedHostEvidence<StrongName>() != null)
- {
- foreach (StrongName fullTrustAssembly in ApplicationTrust.FullTrustAssemblies)
- {
- StrongNameMembershipCondition sn = new StrongNameMembershipCondition(fullTrustAssembly.PublicKey,
- fullTrustAssembly.Name,
- fullTrustAssembly.Version);
-
- object usedEvidence = null;
- if ((sn as IReportMatchMembershipCondition).Check(evidence, out usedEvidence))
- {
- IDelayEvaluatedEvidence delayEvidence = usedEvidence as IDelayEvaluatedEvidence;
- if (usedEvidence != null)
- {
- delayEvidence.MarkUsed();
- }
-
- return new PermissionSet(PermissionState.Unrestricted);
- }
- }
- }
-
- // Otherwise, the grant set is just the default grant set
- return ApplicationTrust.DefaultGrantSet.PermissionSet.Copy();
- }
-#endif // FEATURE_CAS_POLICY
-
- [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);
@@ -4309,7 +2433,6 @@ namespace System {
return oh.Unwrap();
} // CreateInstanceAndUnwrap
-
public Object CreateInstanceAndUnwrap(String assemblyName,
String typeName,
Object[] activationAttributes)
@@ -4454,7 +2577,6 @@ namespace System {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern Int32 GetId();
@@ -4468,76 +2590,35 @@ namespace System {
return false;
}
-#if FEATURE_FUSION
- private static AppDomainSetup InternalCreateDomainSetup(String imageLocation)
- {
- int i = imageLocation.LastIndexOf('\\');
-
- Contract.Assert(i != -1, "invalid image location");
-
- AppDomainSetup info = new AppDomainSetup();
- info.ApplicationBase = imageLocation.Substring(0, i+1);
-
- StringBuilder config = new StringBuilder(imageLocation.Substring(i+1));
- config.Append(AppDomainSetup.ConfigurationExtension);
- info.ConfigurationFile = config.ToString();
-
- return info;
- }
-
- // Used by the validator for testing but not executing an assembly
- private static AppDomain InternalCreateDomain(String imageLocation)
- {
- AppDomainSetup info = InternalCreateDomainSetup(imageLocation);
- return CreateDomain("Validator",
- null,
- info);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private void InternalSetDomainContext(String imageLocation)
- {
- SetupFusionStore(InternalCreateDomainSetup(imageLocation), null);
- }
-#endif
-
#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)
{
@@ -4554,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)
@@ -4570,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)
@@ -4588,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)
@@ -4608,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)
@@ -4619,49 +2696,8 @@ namespace System {
}
}
#endif
-
-#if !FEATURE_CORECLR
- // this method is required so Object.GetType is not made virtual by the compiler
- // _AppDomain.GetType()
- public new Type GetType()
- {
- return base.GetType();
- }
-
- void _AppDomain.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _AppDomain.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _AppDomain.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 _AppDomain.Invoke in VM\DangerousAPIs.h and
- // include _AppDomain in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _AppDomain.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
- // CallBacks provide a facility to request execution of some code
- // in another context/appDomain.
- // CrossAppDomainDelegate type is defined for appdomain call backs.
- // The delegate used to request a callbak through the DoCallBack method
- // must be of CrossContextDelegate type.
-#if FEATURE_REMOTING
-[System.Runtime.InteropServices.ComVisible(true)]
- public delegate void CrossAppDomainDelegate();
-#endif
-
/// <summary>
/// Handle used to marshal an AppDomain to the VM (eg QCall). When marshaled via a QCall, the target
/// method in the VM will recieve a QCall::AppDomainHandle parameter.
diff --git a/src/mscorlib/src/System/AppDomainManager.cs b/src/mscorlib/src/System/AppDomainManager.cs
index 291099e199..71bc088d1d 100644
--- a/src/mscorlib/src/System/AppDomainManager.cs
+++ b/src/mscorlib/src/System/AppDomainManager.cs
@@ -8,151 +8,28 @@
// participate in the creation and control the settings of new AppDomains.
//
-namespace System {
- using System.Collections;
- using System.Globalization;
- using System.IO;
+namespace System
+{
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
- using System.Security.Permissions;
- using System.Security.Policy;
- using System.Threading;
-#if FEATURE_CLICKONCE
- using System.Runtime.Hosting;
-#endif
- using System.Runtime.Versioning;
using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
-#if FEATURE_APPDOMAINMANAGER_INITOPTIONS
- [Flags]
[System.Runtime.InteropServices.ComVisible(true)]
- public enum AppDomainManagerInitializationOptions {
- None = 0x0000,
- RegisterWithHost = 0x0001
- }
-#endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS
-
- [System.Security.SecurityCritical] // auto-generated_required
- [System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.Infrastructure)]
-#endif
-#if FEATURE_REMOTING
- public class AppDomainManager : MarshalByRefObject {
-#else // FEATURE_REMOTING
- public class AppDomainManager {
-#endif // FEATURE_REMOTING
+ public class AppDomainManager : MarshalByRefObject
+ {
public AppDomainManager () {}
-#if FEATURE_REMOTING
- [System.Security.SecurityCritical] // auto-generated
- public virtual AppDomain CreateDomain (string friendlyName,
- Evidence securityInfo,
- AppDomainSetup appDomainInfo) {
- return CreateDomainHelper(friendlyName, securityInfo, appDomainInfo);
- }
-
- [System.Security.SecurityCritical] // auto-generated_required
- [SecurityPermissionAttribute(SecurityAction.Demand, ControlAppDomain = true)]
- protected static AppDomain CreateDomainHelper (string friendlyName,
- Evidence securityInfo,
- AppDomainSetup appDomainInfo) {
- if (friendlyName == null)
- throw new ArgumentNullException("friendlyName", Environment.GetResourceString("ArgumentNull_String"));
-
- Contract.EndContractBlock();
- // If evidence is provided, we check to make sure that is allowed.
- if (securityInfo != null) {
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
-
- // Check the evidence to ensure that if it expects a sandboxed domain, it actually gets one.
- AppDomain.CheckDomainCreationEvidence(appDomainInfo, securityInfo);
- }
-
- if (appDomainInfo == null) {
- appDomainInfo = new AppDomainSetup();
- }
-
- // If there was no specified AppDomainManager for the new domain, default it to being the same
- // as the current domain's AppDomainManager.
- if (appDomainInfo.AppDomainManagerAssembly == null || appDomainInfo.AppDomainManagerType == null) {
- string inheritedDomainManagerAssembly;
- string inheritedDomainManagerType;
-
- AppDomain.CurrentDomain.GetAppDomainManagerType(out inheritedDomainManagerAssembly,
- out inheritedDomainManagerType);
- if (appDomainInfo.AppDomainManagerAssembly == null) {
- appDomainInfo.AppDomainManagerAssembly = inheritedDomainManagerAssembly;
- }
- if (appDomainInfo.AppDomainManagerType == null) {
- appDomainInfo.AppDomainManagerType = inheritedDomainManagerType;
- }
- }
-
- // If there was no specified TargetFrameworkName for the new domain, default it to the current domain's.
- if (appDomainInfo.TargetFrameworkName == null)
- appDomainInfo.TargetFrameworkName = AppDomain.CurrentDomain.GetTargetFrameworkName();
-
- return AppDomain.nCreateDomain(friendlyName,
- appDomainInfo,
- securityInfo,
- securityInfo == null ? AppDomain.CurrentDomain.InternalEvidence : null,
- AppDomain.CurrentDomain.GetSecurityDescriptor());
- }
-#endif // FEATURE_REMOTING
-
- [System.Security.SecurityCritical]
- public virtual void InitializeNewDomain (AppDomainSetup appDomainInfo) {
+ public virtual void InitializeNewDomain (AppDomainSetup appDomainInfo)
+ {
// By default, InitializeNewDomain does nothing. AppDomain.CreateAppDomainManager relies on this fact.
}
-#if FEATURE_APPDOMAINMANAGER_INITOPTIONS
-
- private AppDomainManagerInitializationOptions m_flags = AppDomainManagerInitializationOptions.None;
- public AppDomainManagerInitializationOptions InitializationFlags {
- get {
- return m_flags;
- }
- set {
- m_flags = value;
- }
- }
-#endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS
-
-#if FEATURE_CLICKONCE
- private ApplicationActivator m_appActivator = null;
- public virtual ApplicationActivator ApplicationActivator {
- get {
- if (m_appActivator == null)
- m_appActivator = new ApplicationActivator();
- return m_appActivator;
- }
- }
-#endif //#if FEATURE_CLICKONCE
-
-#if FEATURE_CAS_POLICY
- public virtual HostSecurityManager HostSecurityManager {
- get {
- return null;
- }
- }
-
- public virtual HostExecutionContextManager HostExecutionContextManager {
- get {
- // By default, the AppDomainManager returns the HostExecutionContextManager.
- return HostExecutionContextManager.GetInternalHostExecutionContextManager();
- }
- }
-#endif // FEATURE_CAS_POLICY
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void GetEntryAssembly(ObjectHandleOnStack retAssembly);
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
@@ -160,14 +37,6 @@ namespace System {
// In the second case, we maintain the old behavior by calling GetEntryAssembly().
if (m_entryAssembly == null)
{
-
-#if FEATURE_CLICKONCE
- AppDomain domain = AppDomain.CurrentDomain;
- if (domain.IsDefaultAppDomain() && domain.ActivationContext != null) {
- ManifestRunner runner = new ManifestRunner(domain, domain.ActivationContext);
- m_entryAssembly = runner.EntryAssembly;
- } else
-#endif //#if FEATURE_CLICKONCE
{
RuntimeAssembly entryAssembly = null;
GetEntryAssembly(JitHelpers.GetObjectHandleOnStack(ref entryAssembly));
@@ -179,7 +48,6 @@ namespace System {
}
internal static AppDomainManager CurrentAppDomainManager {
- [System.Security.SecurityCritical] // auto-generated
get {
return AppDomain.CurrentDomain.DomainManager;
}
@@ -189,32 +57,5 @@ namespace System {
{
return false;
}
-
-#if FEATURE_APPDOMAINMANAGER_INITOPTIONS
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern bool HasHost();
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
- [SuppressUnmanagedCodeSecurity]
- private static extern void RegisterWithHost(IntPtr appDomainManager);
-
- internal void RegisterWithHost() {
- if (HasHost()) {
- IntPtr punkAppDomainManager = IntPtr.Zero;
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- punkAppDomainManager = Marshal.GetIUnknownForObject(this);
- RegisterWithHost(punkAppDomainManager);
- }
- finally {
- if (!punkAppDomainManager.IsNull()) {
- Marshal.Release(punkAppDomainManager);
- }
- }
- }
- }
-#endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS
}
}
diff --git a/src/mscorlib/src/System/AppDomainSetup.cs b/src/mscorlib/src/System/AppDomainSetup.cs
index f1057da082..fc8a64c192 100644
--- a/src/mscorlib/src/System/AppDomainSetup.cs
+++ b/src/mscorlib/src/System/AppDomainSetup.cs
@@ -13,28 +13,16 @@
**
=============================================================================*/
-namespace System {
- using System;
-#if FEATURE_CLICKONCE
- using System.Deployment.Internal.Isolation;
- using System.Deployment.Internal.Isolation.Manifest;
- using System.Runtime.Hosting;
-#endif
- using System.Runtime.CompilerServices;
- using System.Runtime;
+namespace System
+{
using System.Text;
- using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
- using System.Reflection;
using System.Security;
- using System.Security.Permissions;
using System.Security.Policy;
- using System.Globalization;
using Path = System.IO.Path;
- using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
- using System.Collections;
using System.Collections.Generic;
[Serializable]
@@ -75,10 +63,6 @@ namespace System {
private const string MACHINE_CONFIGURATION_FILE = "config\\machine.config";
private const string ACTAG_HOST_CONFIG_FILE = "HOST_CONFIG";
-#if FEATURE_FUSION
- private const string LICENSE_FILE = "LICENSE_FILE";
-#endif
-
// Constants from fusionpriv.h
private const string ACTAG_APP_CONFIG_FILE = "APP_CONFIG_FILE";
private const string ACTAG_MACHINE_CONFIG = "MACHINE_CONFIG";
@@ -109,14 +93,9 @@ namespace System {
private AppDomainInitializer _AppDomainInitializer;
[OptionalField(VersionAdded = 2)]
private string[] _AppDomainInitializerArguments;
-#if FEATURE_CLICKONCE
- [OptionalField(VersionAdded = 2)]
- private ActivationArguments _ActivationArguments;
-#endif
-#if FEATURE_CORECLR
+
// On the CoreCLR, this contains just the name of the permission set that we install in the new appdomain.
// Not the ToXml().ToString() of an ApplicationTrust object.
-#endif
[OptionalField(VersionAdded = 2)]
private string _ApplicationTrust;
[OptionalField(VersionAdded = 2)]
@@ -130,11 +109,6 @@ namespace System {
[OptionalField(VersionAdded = 4)]
private string _AppDomainManagerType;
-#if FEATURE_APTCA
- [OptionalField(VersionAdded = 4)]
- private string[] _AptcaVisibleAssemblies;
-#endif
-
// A collection of strings used to indicate which breaking changes shouldn't be applied
// to an AppDomain. We only use the keys, the values are ignored.
[OptionalField(VersionAdded = 4)]
@@ -143,11 +117,6 @@ namespace System {
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private String _TargetFrameworkName;
-#if !FEATURE_CORECLR
- [NonSerialized]
- internal AppDomainSortingSetupInfo _AppDomainSortingSetupInfo;
-#endif
-
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private bool _CheckedForTargetFrameworkName;
@@ -156,7 +125,6 @@ namespace System {
private bool _UseRandomizedStringHashing;
#endif
- [SecuritySafeCritical]
internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData)
{
string[] mine = Value;
@@ -180,10 +148,8 @@ namespace System {
_LoaderOptimization = copy._LoaderOptimization;
_AppDomainInitializerArguments = copy.AppDomainInitializerArguments;
-#if FEATURE_CLICKONCE
- _ActivationArguments = copy.ActivationArguments;
-#endif
_ApplicationTrust = copy._ApplicationTrust;
+
if (copyDomainBoundData)
_AppDomainInitializer = copy.AppDomainInitializer;
else
@@ -195,21 +161,12 @@ namespace System {
#endif // FEATURE_COMINTEROP
_AppDomainManagerAssembly = copy.AppDomainManagerAssembly;
_AppDomainManagerType = copy.AppDomainManagerType;
-#if FEATURE_APTCA
- _AptcaVisibleAssemblies = copy.PartialTrustVisibleAssemblies;
-#endif
if (copy._CompatFlags != null)
{
SetCompatibilitySwitches(copy._CompatFlags.Keys);
}
-#if !FEATURE_CORECLR
- if(copy._AppDomainSortingSetupInfo != null)
- {
- _AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo(copy._AppDomainSortingSetupInfo);
- }
-#endif
_TargetFrameworkName = copy._TargetFrameworkName;
#if FEATURE_RANDOMIZED_STRING_HASHING
@@ -226,32 +183,6 @@ namespace System {
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
-#if FEATURE_CLICKONCE
- // Creates an AppDomainSetup object from an application identity.
- public AppDomainSetup (ActivationContext activationContext) : this (new ActivationArguments(activationContext)) {}
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public AppDomainSetup (ActivationArguments activationArguments) {
- if (activationArguments == null)
- throw new ArgumentNullException("activationArguments");
- Contract.EndContractBlock();
-
- _LoaderOptimization = LoaderOptimization.NotSpecified;
- ActivationArguments = activationArguments;
-
- Contract.Assert(activationArguments.ActivationContext != null, "Cannot set base directory without activation context");
- string entryPointPath = CmsUtils.GetEntryPointFullPath(activationArguments);
- if (!String.IsNullOrEmpty(entryPointPath))
- SetupDefaults(entryPointPath);
- else
- ApplicationBase = activationArguments.ActivationContext.ApplicationDirectory;
-
- }
-#endif // !FEATURE_CLICKONCE
-
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false) {
char[] sep = {'\\', '/'};
int i = imageLocation.LastIndexOfAny(sep);
@@ -297,37 +228,13 @@ namespace System {
set { _AppDomainManagerType = value; }
}
-#if FEATURE_APTCA
- public string[] PartialTrustVisibleAssemblies
- {
- get { return _AptcaVisibleAssemblies; }
- set {
- if (value != null) {
- _AptcaVisibleAssemblies = (string[])value.Clone();
- Array.Sort<string>(_AptcaVisibleAssemblies, StringComparer.OrdinalIgnoreCase);
- }
- else {
- _AptcaVisibleAssemblies = null;
- }
- }
- }
-#endif
-
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);
}
@@ -550,7 +457,6 @@ namespace System {
public String ConfigurationFile
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.ConfigurationFileValue], true);
}
@@ -604,15 +510,6 @@ namespace System {
public void SetCompatibilitySwitches(IEnumerable<String> switches)
{
-
-#if !FEATURE_CORECLR
- if(_AppDomainSortingSetupInfo != null)
- {
- _AppDomainSortingSetupInfo._useV2LegacySorting = false;
- _AppDomainSortingSetupInfo._useV4LegacySorting = false;
- }
-#endif
-
#if FEATURE_RANDOMIZED_STRING_HASHING
_UseRandomizedStringHashing = false;
#endif
@@ -621,30 +518,11 @@ namespace System {
_CompatFlags = new Dictionary<string, object>();
foreach (String str in switches)
{
-#if !FEATURE_CORECLR
- if(StringComparer.OrdinalIgnoreCase.Equals("NetFx40_Legacy20SortingBehavior", str)) {
- if(_AppDomainSortingSetupInfo == null)
- {
- _AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo();
- }
- _AppDomainSortingSetupInfo._useV2LegacySorting = true;
- }
-
- if(StringComparer.OrdinalIgnoreCase.Equals("NetFx45_Legacy40SortingBehavior", str)) {
- if(_AppDomainSortingSetupInfo == null)
- {
- _AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo();
- }
- _AppDomainSortingSetupInfo._useV4LegacySorting = true;
- }
-#endif
-
#if FEATURE_RANDOMIZED_STRING_HASHING
if(StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str)) {
_UseRandomizedStringHashing = true;
}
#endif
-
_CompatFlags.Add(str, null);
}
}
@@ -671,82 +549,12 @@ namespace System {
set { _CheckedForTargetFrameworkName = value; }
}
-#if !FEATURE_CORECLR
- [SecurityCritical]
- public void SetNativeFunction(string functionName, int functionVersion, IntPtr functionPointer)
- {
- if(functionName == null)
- {
- throw new ArgumentNullException("functionName");
- }
-
- if(functionPointer == IntPtr.Zero)
- {
- throw new ArgumentNullException("functionPointer");
- }
-
- if(String.IsNullOrWhiteSpace(functionName))
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_NPMSInvalidName"), "functionName");
- }
-
- Contract.EndContractBlock();
-
- if(functionVersion < 1)
- {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_MinSortingVersion", 1, functionName));
- }
-
- if(_AppDomainSortingSetupInfo == null)
- {
- _AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo();
- }
-
- if(String.Equals(functionName, "IsNLSDefinedString", StringComparison.OrdinalIgnoreCase))
- {
- _AppDomainSortingSetupInfo._pfnIsNLSDefinedString = functionPointer;
- }
-
- if (String.Equals(functionName, "CompareStringEx", StringComparison.OrdinalIgnoreCase))
- {
- _AppDomainSortingSetupInfo._pfnCompareStringEx = functionPointer;
- }
-
- if (String.Equals(functionName, "LCMapStringEx", StringComparison.OrdinalIgnoreCase))
- {
- _AppDomainSortingSetupInfo._pfnLCMapStringEx = functionPointer;
- }
-
- if (String.Equals(functionName, "FindNLSStringEx", StringComparison.OrdinalIgnoreCase))
- {
- _AppDomainSortingSetupInfo._pfnFindNLSStringEx = functionPointer;
- }
-
- if (String.Equals(functionName, "CompareStringOrdinal", StringComparison.OrdinalIgnoreCase))
- {
- _AppDomainSortingSetupInfo._pfnCompareStringOrdinal = functionPointer;
- }
-
- if (String.Equals(functionName, "GetNLSVersionEx", StringComparison.OrdinalIgnoreCase))
- {
- _AppDomainSortingSetupInfo._pfnGetNLSVersionEx = functionPointer;
- }
-
- if (String.Equals(functionName, "FindStringOrdinal", StringComparison.OrdinalIgnoreCase))
- {
- _AppDomainSortingSetupInfo._pfnFindStringOrdinal = functionPointer;
- }
- }
-#endif
-
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;
@@ -772,7 +580,6 @@ namespace System {
}
}
-
public bool DisallowPublisherPolicy
{
get
@@ -835,7 +642,6 @@ namespace System {
}
}
- [System.Security.SecurityCritical] // auto-generated
private String VerifyDir(String dir, bool normalize)
{
if (dir != null) {
@@ -844,22 +650,12 @@ namespace System {
else {
if (normalize)
dir = NormalizePath(dir, true);
-
- // The only way AppDomainSetup is exposed in coreclr is through the AppDomainManager
- // and the AppDomainManager is a SecurityCritical type. Also, all callers of callstacks
- // leading from VerifyDir are SecurityCritical. So we can remove the Demand because
- // we have validated that all callers are SecurityCritical
-#if !FEATURE_CORECLR
- if (IsFilePath(dir))
- new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dir ).Demand();
-#endif // !FEATURE_CORECLR
}
}
return dir;
}
- [System.Security.SecurityCritical] // auto-generated
private void VerifyDirList(String dirs)
{
if (dirs != null) {
@@ -873,7 +669,6 @@ namespace System {
internal String DeveloperPath
{
- [System.Security.SecurityCritical] // auto-generated
get {
String dirs = Value[(int) LoaderInformation.DevPathValue];
VerifyDirList(dirs);
@@ -896,7 +691,7 @@ namespace System {
else
fDelimiter = true;
- newPath.Append(Path.GetFullPathInternal(directories[i]));
+ newPath.Append(Path.GetFullPath(directories[i]));
}
}
@@ -988,83 +783,29 @@ namespace System {
}
}
-#if FEATURE_CLICKONCE
- [XmlIgnoreMember]
- public ActivationArguments ActivationArguments {
- [Pure]
- get {
- return _ActivationArguments;
- }
- set {
- _ActivationArguments = value;
- }
- }
-#endif // !FEATURE_CLICKONCE
-
internal ApplicationTrust InternalGetApplicationTrust()
{
-
if (_ApplicationTrust == null) return null;
-
-
-#if FEATURE_CORECLR
ApplicationTrust grantSet = new ApplicationTrust(NamedPermissionSet.GetBuiltInSet(_ApplicationTrust));
-#else
- SecurityElement securityElement = SecurityElement.FromString(_ApplicationTrust);
- ApplicationTrust grantSet = new ApplicationTrust();
- grantSet.FromXml(securityElement);
-#endif
return grantSet;
}
-#if FEATURE_CORECLR
internal void InternalSetApplicationTrust(String permissionSetName)
{
_ApplicationTrust = permissionSetName;
}
-#else
- internal void InternalSetApplicationTrust(ApplicationTrust value)
- {
- if (value != null)
- {
- _ApplicationTrust = value.ToXml().ToString();
- }
- else
- {
- _ApplicationTrust = null;
- }
- }
-#endif
-#if FEATURE_CLICKONCE
- [XmlIgnoreMember]
- public ApplicationTrust ApplicationTrust
- {
- get {
- return InternalGetApplicationTrust();
- }
- set {
- InternalSetApplicationTrust(value);
- }
- }
-#else // FEATURE_CLICKONCE
[XmlIgnoreMember]
internal ApplicationTrust ApplicationTrust
{
- get {
+ get
+ {
return InternalGetApplicationTrust();
}
-#if !FEATURE_CORECLR
- set {
- InternalSetApplicationTrust(value);
- }
-#endif
}
-#endif // FEATURE_CLICKONCE
public String PrivateBinPath
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
String dirs = Value[(int) LoaderInformation.PrivateBinPathValue];
VerifyDirList(dirs);
@@ -1083,7 +824,6 @@ namespace System {
}
}
-
public String PrivateBinPathProbe
{
get {
@@ -1104,7 +844,6 @@ namespace System {
public String ShadowCopyDirectories
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
String dirs = Value[(int) LoaderInformation.ShadowCopyDirectoriesValue];
VerifyDirList(dirs);
@@ -1147,7 +886,6 @@ namespace System {
public String CachePath
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.CachePathValue], false);
}
@@ -1166,7 +904,6 @@ namespace System {
public String LicenseFile
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.LicenseFileValue], true);
}
@@ -1229,203 +966,17 @@ namespace System {
}
}
-#if FEATURE_FUSION
- [SecurityCritical]
- internal bool UpdateContextPropertyIfNeeded(LoaderInformation FieldValue, String FieldKey, String UpdatedField, IntPtr fusionContext, AppDomainSetup oldADS)
- {
- String FieldString = Value[(int) FieldValue],
- OldFieldString = (oldADS == null ? null : oldADS.Value[(int) FieldValue]);
- if (FieldString != OldFieldString) { // Compare references since strings are immutable
- UpdateContextProperty(fusionContext, FieldKey, UpdatedField == null ? FieldString : UpdatedField);
- return true;
- }
-
- return false;
- }
-
- [SecurityCritical]
- internal void UpdateBooleanContextPropertyIfNeeded(LoaderInformation FieldValue, String FieldKey, IntPtr fusionContext, AppDomainSetup oldADS)
- {
- if (Value[(int) FieldValue] != null)
- UpdateContextProperty(fusionContext, FieldKey, "true");
- else if (oldADS != null && oldADS.Value[(int) FieldValue] != null)
- UpdateContextProperty(fusionContext, FieldKey, "false");
- }
-
- [SecurityCritical]
- internal static bool ByteArraysAreDifferent(Byte[] A, Byte[] B)
- {
- int length = A.Length;
- if (length != B.Length)
- return true;
-
- for(int i = 0; i < length; i++) {
- if (A[i] != B[i])
- return true;
- }
-
- return false;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal static void UpdateByteArrayContextPropertyIfNeeded(Byte[] NewArray, Byte[] OldArray, String FieldKey, IntPtr fusionContext)
- {
- if ((NewArray != null && OldArray == null) ||
- (NewArray == null && OldArray != null) ||
- (NewArray != null && OldArray != null && ByteArraysAreDifferent(NewArray, OldArray)))
- UpdateContextProperty(fusionContext, FieldKey, NewArray);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal void SetupFusionContext(IntPtr fusionContext, AppDomainSetup oldADS)
- {
- UpdateContextPropertyIfNeeded(LoaderInformation.ApplicationBaseValue, ApplicationBaseKey, null, fusionContext, oldADS);
- UpdateContextPropertyIfNeeded(LoaderInformation.PrivateBinPathValue, PrivateBinPathKey, null, fusionContext, oldADS);
- UpdateContextPropertyIfNeeded(LoaderInformation.DevPathValue, DeveloperPathKey, null, fusionContext, oldADS);
-
- UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowPublisherPolicyValue, DisallowPublisherPolicyKey, fusionContext, oldADS);
- UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowCodeDownloadValue, DisallowCodeDownloadKey, fusionContext, oldADS);
- UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowBindingRedirectsValue, DisallowBindingRedirectsKey, fusionContext, oldADS);
- UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowAppBaseProbingValue, DisallowAppBaseProbingKey, fusionContext, oldADS);
-
- if(UpdateContextPropertyIfNeeded(LoaderInformation.ShadowCopyFilesValue, ShadowCopyFilesKey, ShadowCopyFiles, fusionContext, oldADS)) {
-
- // If we are asking for shadow copy directories then default to
- // only to the ones that are in the private bin path.
- if(Value[(int) LoaderInformation.ShadowCopyDirectoriesValue] == null)
- ShadowCopyDirectories = BuildShadowCopyDirectories();
-
- UpdateContextPropertyIfNeeded(LoaderInformation.ShadowCopyDirectoriesValue, ShadowCopyDirectoriesKey, null, fusionContext, oldADS);
- }
-
- UpdateContextPropertyIfNeeded(LoaderInformation.CachePathValue, CachePathKey, null, fusionContext, oldADS);
- UpdateContextPropertyIfNeeded(LoaderInformation.PrivateBinPathProbeValue, PrivateBinPathProbeKey, PrivateBinPathProbe, fusionContext, oldADS);
- UpdateContextPropertyIfNeeded(LoaderInformation.ConfigurationFileValue, ConfigurationFileKey, null, fusionContext, oldADS);
-
- UpdateByteArrayContextPropertyIfNeeded(_ConfigurationBytes, oldADS == null ? null : oldADS.GetConfigurationBytes(), ConfigurationBytesKey, fusionContext);
-
- UpdateContextPropertyIfNeeded(LoaderInformation.ApplicationNameValue, ApplicationNameKey, ApplicationName, fusionContext, oldADS);
- UpdateContextPropertyIfNeeded(LoaderInformation.DynamicBaseValue, DynamicBaseKey, null, fusionContext, oldADS);
-
- // Always add the runtime configuration file to the appdomain
- UpdateContextProperty(fusionContext, MachineConfigKey, RuntimeEnvironment.GetRuntimeDirectoryImpl() + RuntimeConfigurationFile);
-
- String hostBindingFile = RuntimeEnvironment.GetHostBindingFile();
- if(hostBindingFile != null || oldADS != null) // If oldADS != null, we don't know the old value of the hostBindingFile, so we force an update even when hostBindingFile == null.
- UpdateContextProperty(fusionContext, HostBindingKey, hostBindingFile);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern void UpdateContextProperty(IntPtr fusionContext, string key, Object value);
-#endif // FEATURE_FUSION
-
static internal int Locate(String s)
{
if(String.IsNullOrEmpty(s))
return -1;
-#if FEATURE_FUSION
-
- // verify assumptions hardcoded into the switch below
- Contract.Assert('A' == ACTAG_APP_CONFIG_FILE[0] , "Assumption violated");
- Contract.Assert('A' == ACTAG_APP_NAME[0] , "Assumption violated");
- Contract.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated");
- Contract.Assert('B' == ACTAG_BINPATH_PROBE_ONLY[0] , "Assumption violated");
- Contract.Assert('C' == ACTAG_APP_CACHE_BASE[0] , "Assumption violated");
- Contract.Assert('D' == ACTAG_DEV_PATH[0] , "Assumption violated");
- Contract.Assert('D' == ACTAG_APP_DYNAMIC_BASE[0] , "Assumption violated");
- Contract.Assert('F' == ACTAG_FORCE_CACHE_INSTALL[0] , "Assumption violated");
- Contract.Assert('L' == LICENSE_FILE[0] , "Assumption violated");
- Contract.Assert('P' == ACTAG_APP_PRIVATE_BINPATH[0] , "Assumption violated");
- Contract.Assert('S' == ACTAG_APP_SHADOW_COPY_DIRS[0], "Assumption violated");
- Contract.Assert('D' == ACTAG_DISALLOW_APPLYPUBLISHERPOLICY[0], "Assumption violated");
- Contract.Assert('C' == ACTAG_CODE_DOWNLOAD_DISABLED[0], "Assumption violated");
- Contract.Assert('D' == ACTAG_DISALLOW_APP_BINDING_REDIRECTS[0], "Assumption violated");
- Contract.Assert('D' == ACTAG_DISALLOW_APP_BASE_PROBING[0], "Assumption violated");
- Contract.Assert('A' == ACTAG_APP_CONFIG_BLOB[0], "Assumption violated");
-
- switch (s[0]) {
- case 'A':
- if (s == ACTAG_APP_CONFIG_FILE) return (int)LoaderInformation.ConfigurationFileValue;
- if (s == ACTAG_APP_NAME) return (int)LoaderInformation.ApplicationNameValue;
- if (s == ACTAG_APP_BASE_URL) return (int)LoaderInformation.ApplicationBaseValue;
- if (s == ACTAG_APP_CONFIG_BLOB) return (int)LoaderInformation.ConfigurationBytesValue;
- break;
- case 'B':
- if (s == ACTAG_BINPATH_PROBE_ONLY) return (int)LoaderInformation.PrivateBinPathProbeValue;
- break;
- case 'C':
- if (s == ACTAG_APP_CACHE_BASE) return (int)LoaderInformation.CachePathValue;
- if (s == ACTAG_CODE_DOWNLOAD_DISABLED) return (int)LoaderInformation.DisallowCodeDownloadValue;
- break;
- case 'D':
- if (s == ACTAG_DEV_PATH) return (int)LoaderInformation.DevPathValue;
- if (s == ACTAG_APP_DYNAMIC_BASE) return (int)LoaderInformation.DynamicBaseValue;
- if (s == ACTAG_DISALLOW_APPLYPUBLISHERPOLICY) return (int)LoaderInformation.DisallowPublisherPolicyValue;
- if (s == ACTAG_DISALLOW_APP_BINDING_REDIRECTS) return (int)LoaderInformation.DisallowBindingRedirectsValue;
- if (s == ACTAG_DISALLOW_APP_BASE_PROBING) return (int)LoaderInformation.DisallowAppBaseProbingValue;
- break;
- case 'F':
- if (s == ACTAG_FORCE_CACHE_INSTALL) return (int)LoaderInformation.ShadowCopyFilesValue;
- break;
- case 'L':
- if (s == LICENSE_FILE) return (int)LoaderInformation.LicenseFileValue;
- break;
- case 'P':
- if (s == ACTAG_APP_PRIVATE_BINPATH) return (int)LoaderInformation.PrivateBinPathValue;
- break;
- case 'S':
- if (s == ACTAG_APP_SHADOW_COPY_DIRS) return (int)LoaderInformation.ShadowCopyDirectoriesValue;
- break;
- }
-#else
- 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;
-#endif //FEATURE_FUSION
-
return -1;
}
-#if FEATURE_FUSION
- private string BuildShadowCopyDirectories()
- {
- // Default to only to the ones that are in the private bin path.
- String binPath = Value[(int) LoaderInformation.PrivateBinPathValue];
- if(binPath == null)
- return null;
-
- StringBuilder result = StringBuilderCache.Acquire();
- String appBase = Value[(int) LoaderInformation.ApplicationBaseValue];
- if(appBase != null) {
- char[] sep = {';'};
- string[] directories = binPath.Split(sep);
- int size = directories.Length;
- bool appendSlash = !( (appBase[appBase.Length-1] == '/') ||
- (appBase[appBase.Length-1] == '\\') );
-
- if (size == 0) {
- result.Append(appBase);
- if (appendSlash)
- result.Append('\\');
- result.Append(binPath);
- }
- else {
- for(int i = 0; i < size; i++) {
- result.Append(appBase);
- if (appendSlash)
- result.Append('\\');
- result.Append(directories[i]);
-
- if (i < size-1)
- result.Append(';');
- }
- }
- }
-
- return StringBuilderCache.GetStringAndRelease(result);
- }
-#endif // FEATURE_FUSION
#if FEATURE_COMINTEROP
public bool SandboxInterop
diff --git a/src/mscorlib/src/System/ApplicationId.cs b/src/mscorlib/src/System/ApplicationId.cs
index fa8be957e2..93fc37dd99 100644
--- a/src/mscorlib/src/System/ApplicationId.cs
+++ b/src/mscorlib/src/System/ApplicationId.cs
@@ -33,13 +33,13 @@ namespace System {
public ApplicationId (byte[] publicKeyToken, string name, Version version, string processorArchitecture, string culture) {
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyApplicationName"));
if (version == null)
- throw new ArgumentNullException("version");
+ throw new ArgumentNullException(nameof(version));
if (publicKeyToken == null)
- throw new ArgumentNullException("publicKeyToken");
+ throw new ArgumentNullException(nameof(publicKeyToken));
Contract.EndContractBlock();
m_publicKeyToken = new byte[publicKeyToken.Length];
diff --git a/src/mscorlib/src/System/ArgIterator.cs b/src/mscorlib/src/System/ArgIterator.cs
index 0ce27ed24a..c5bc379505 100644
--- a/src/mscorlib/src/System/ArgIterator.cs
+++ b/src/mscorlib/src/System/ArgIterator.cs
@@ -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()));
diff --git a/src/mscorlib/src/System/ArgumentException.cs b/src/mscorlib/src/System/ArgumentException.cs
index 8edb7e4279..f37b7690a8 100644
--- a/src/mscorlib/src/System/ArgumentException.cs
+++ b/src/mscorlib/src/System/ArgumentException.cs
@@ -82,10 +82,9 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
base.GetObjectData(info, context);
diff --git a/src/mscorlib/src/System/ArgumentNullException.cs b/src/mscorlib/src/System/ArgumentNullException.cs
index 4bcb537b81..661ebd29af 100644
--- a/src/mscorlib/src/System/ArgumentNullException.cs
+++ b/src/mscorlib/src/System/ArgumentNullException.cs
@@ -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) {
}
}
diff --git a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
index a54380b39d..78a90db34e 100644
--- a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
+++ b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
@@ -89,10 +89,9 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
base.GetObjectData(info, context);
diff --git a/src/mscorlib/src/System/Array.cs b/src/mscorlib/src/System/Array.cs
index 08790490f4..7bb6ebbdd3 100644
--- a/src/mscorlib/src/System/Array.cs
+++ b/src/mscorlib/src/System/Array.cs
@@ -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,13 +65,12 @@ 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)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType);
if (length < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
Contract.Ensures(Contract.Result<Array>() != null);
Contract.Ensures(Contract.Result<Array>().Length == length);
Contract.Ensures(Contract.Result<Array>().Rank == 1);
@@ -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)
@@ -904,7 +861,7 @@ namespace System {
if (index < lb)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - (index - lb) < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (array.Rank != 1)
@@ -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);
@@ -1002,7 +958,7 @@ namespace System {
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
@@ -1073,6 +1029,42 @@ namespace System {
return Array.FindIndex(array, match) != -1;
}
+ public static void Fill<T>(T[] array, T value)
+ {
+ if (array == null)
+ {
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ }
+
+ for (int i = 0; i < array.Length; i++)
+ {
+ array[i] = value;
+ }
+ }
+
+ public static void Fill<T>(T[] array, T value, int startIndex, int count)
+ {
+ if (array == null)
+ {
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ }
+
+ if (startIndex < 0 || startIndex > array.Length)
+ {
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
+ }
+
+ if (count < 0 || startIndex > array.Length - count)
+ {
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
+ }
+
+ for (int i = startIndex; i < startIndex + count; i++)
+ {
+ array[i] = value;
+ }
+ }
+
public static T Find<T>(T[] array, Predicate<T> match) {
if( array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
@@ -1136,11 +1128,11 @@ namespace System {
}
if( startIndex < 0 || startIndex > array.Length ) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (count < 0 || startIndex > array.Length - count) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
if( match == null) {
@@ -1205,19 +1197,19 @@ namespace System {
if(array.Length == 0) {
// Special case for 0 length List
if( startIndex != -1) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
else {
// Make sure we're not out of range
if ( startIndex < 0 || startIndex >= array.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
int endIndex = startIndex - count;
@@ -1293,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)
@@ -1305,9 +1296,9 @@ namespace System {
int lb = array.GetLowerBound(0);
if (startIndex < lb || startIndex > array.Length + lb)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
if (count < 0 || count > array.Length - startIndex + lb)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
// Try calling a quick native method to handle primitive types.
int retVal;
@@ -1376,11 +1367,11 @@ namespace System {
}
if (startIndex < 0 || startIndex > array.Length ) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (count < 0 || count > array.Length - startIndex) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
Contract.Ensures(Contract.Result<int>() < array.Length);
Contract.EndContractBlock();
@@ -1388,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);
@@ -1429,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)
@@ -1442,9 +1431,9 @@ namespace System {
}
if (startIndex < lb || startIndex >= array.Length + lb)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
if (count < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
if (count > startIndex - lb + 1)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.endIndex, ExceptionResource.ArgumentOutOfRange_EndIndexStartIndex);
if (array.Rank != 1)
@@ -1518,30 +1507,29 @@ namespace System {
// accept -1 and 0 as valid startIndex for compablility reason.
//
if( startIndex != -1 && startIndex != 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
// only 0 is a valid value for count if array is empty
if( count != 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
return -1;
}
// Make sure we're not out of range
if ( startIndex < 0 || startIndex >= array.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
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);
@@ -1566,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)
@@ -1575,7 +1562,7 @@ namespace System {
if (index < lowerBound)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - (index - lowerBound) < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
@@ -1610,11 +1597,44 @@ 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);
-
+
+ [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
+ public static void Reverse<T>(T[] array)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ Contract.EndContractBlock();
+ Reverse(array, 0, array.Length);
+ }
+
+ [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
+ public static void Reverse<T>(T[] array, int index, int length)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (index < 0)
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
+ if (length < 0)
+ ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
+ if (array.Length - index < length)
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
+ Contract.EndContractBlock();
+
+ int i = index;
+ int j = index + length - 1;
+ while (i < j)
+ {
+ T temp = array[i];
+ array[i] = array[j];
+ array[j] = temp;
+ i++;
+ j--;
+ }
+ }
+
// Sorts the elements of an array. The sort compares the elements to each
// other using the IComparable interface, which must be implemented
// by all elements of the array.
@@ -1710,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)
@@ -1723,7 +1742,7 @@ namespace System {
if (index < keysLowerBound)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (keys.Length - (index - keysLowerBound) < length || (items != null && (index - keysLowerBound) > items.Length - length))
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
@@ -1752,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);
@@ -1799,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)
@@ -1807,7 +1824,7 @@ namespace System {
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
@@ -1823,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)
@@ -1831,7 +1847,7 @@ namespace System {
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (keys.Length - index < length || (items != null && index > items.Length - length))
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
@@ -1863,8 +1879,7 @@ namespace System {
}
Contract.EndContractBlock();
- IComparer<T> comparer = Comparer<T>.Create(comparison);
- Array.Sort(array, comparer);
+ ArraySortHelper<T>.Sort(array, 0, array.Length, comparison);
}
public static bool TrueForAll<T>(T[] array, Predicate<T> match) {
@@ -1935,120 +1950,7 @@ namespace System {
internal void Sort(int left, int length)
{
-#if FEATURE_CORECLR
- // Since QuickSort and IntrospectiveSort produce different sorting sequence for equal keys the upgrade
- // to IntrospectiveSort was quirked. However since the phone builds always shipped with the new sort aka
- // IntrospectiveSort and we would want to continue using this sort moving forward CoreCLR always uses the new sort.
-
IntrospectiveSort(left, length);
-#else
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
- {
- IntrospectiveSort(left, length);
- }
- else
- {
- DepthLimitedQuickSort(left, length + left - 1, IntrospectiveSortUtilities.QuickSortDepthThreshold);
- }
-#endif
- }
-
- private void DepthLimitedQuickSort(int left, int right, int depthLimit)
- {
- // Can use the much faster jit helpers for array access.
- do
- {
- if (depthLimit == 0)
- {
- // Add a try block here to detect IComparers (or their
- // underlying IComparables, etc) that are bogus.
- try
- {
- Heapsort(left, right);
- return;
- }
- catch (IndexOutOfRangeException)
- {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_BogusIComparer, ExceptionArgument.comparer);
- }
- catch (Exception e)
- {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
- }
- }
-
- int i = left;
- int j = right;
-
- // pre-sort the low, middle (pivot), and high values in place.
- // this improves performance in the face of already sorted data, or
- // data that is made up of multiple sorted runs appended together.
- int middle = GetMedian(i, j);
-
- // Add a try block here to detect IComparers (or their
- // underlying IComparables, etc) that are bogus.
- try
- {
- SwapIfGreaterWithItems(i, middle); // swap the low with the mid point
- SwapIfGreaterWithItems(i, j); // swap the low with the high
- SwapIfGreaterWithItems(middle, j); // swap the middle with the high
- }
- catch (Exception e)
- {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
- }
- Object x = keys[middle];
- do
- {
- // Add a try block here to detect IComparers (or their
- // underlying IComparables, etc) that are bogus.
- try
- {
- while (comparer.Compare(keys[i], x) < 0) i++;
- while (comparer.Compare(x, keys[j]) < 0) j--;
- }
- catch (IndexOutOfRangeException)
- {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_BogusIComparer, ExceptionArgument.comparer);
- }
- catch (Exception e)
- {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
- }
- Contract.Assert(i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?");
- if (i > j) break;
- if (i < j)
- {
- Object key = keys[i];
- keys[i] = keys[j];
- keys[j] = key;
- if (items != null)
- {
- Object item = items[i];
- items[i] = items[j];
- items[j] = item;
- }
- }
- i++;
- j--;
- } while (i <= j);
-
- // The next iteration of the while loop is to "recursively" sort the larger half of the array and the
- // following calls recursively sort the smaller half. So we subtract one from depthLimit here so
- // both sorts see the new value.
- depthLimit--;
-
- if (j - left <= right - i)
- {
- if (left < j) DepthLimitedQuickSort(left, j, depthLimit);
- left = i;
- }
- else
- {
- if (i < right) DepthLimitedQuickSort(i, right, depthLimit);
- right = j;
- }
- } while (left < right);
}
private void IntrospectiveSort(int left, int length)
@@ -2254,118 +2156,7 @@ namespace System {
internal void Sort(int left, int length)
{
-#if FEATURE_CORECLR
- // Since QuickSort and IntrospectiveSort produce different sorting sequence for equal keys the upgrade
- // to IntrospectiveSort was quirked. However since the phone builds always shipped with the new sort aka
- // IntrospectiveSort and we would want to continue using this sort moving forward CoreCLR always uses the new sort.
-
IntrospectiveSort(left, length);
-#else
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
- {
- IntrospectiveSort(left, length);
- }
- else
- {
- DepthLimitedQuickSort(left, length + left - 1, IntrospectiveSortUtilities.QuickSortDepthThreshold);
- }
-#endif
- }
-
- private void DepthLimitedQuickSort(int left, int right, int depthLimit)
- {
- // Must use slow Array accessors (GetValue & SetValue)
- do
- {
- if (depthLimit == 0)
- {
- // Add a try block here to detect IComparers (or their
- // underlying IComparables, etc) that are bogus.
- try
- {
- Heapsort(left, right);
- return;
- }
- catch (IndexOutOfRangeException)
- {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_BogusIComparer, ExceptionArgument.comparer);
- }
- catch (Exception e)
- {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
- }
- }
-
- int i = left;
- int j = right;
-
- // pre-sort the low, middle (pivot), and high values in place.
- // this improves performance in the face of already sorted data, or
- // data that is made up of multiple sorted runs appended together.
- int middle = GetMedian(i, j);
- try
- {
- SwapIfGreaterWithItems(i, middle); // swap the low with the mid point
- SwapIfGreaterWithItems(i, j); // swap the low with the high
- SwapIfGreaterWithItems(middle, j); // swap the middle with the high
- }
- catch (Exception e)
- {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
- }
-
- Object x = keys.GetValue(middle);
- do
- {
- // Add a try block here to detect IComparers (or their
- // underlying IComparables, etc) that are bogus.
- try
- {
- while (comparer.Compare(keys.GetValue(i), x) < 0) i++;
- while (comparer.Compare(x, keys.GetValue(j)) < 0) j--;
- }
- catch (IndexOutOfRangeException)
- {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_BogusIComparer, ExceptionArgument.comparer);
- }
- catch (Exception e)
- {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
- }
- Contract.Assert(i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?");
- if (i > j) break;
- if (i < j)
- {
- Object key = keys.GetValue(i);
- keys.SetValue(keys.GetValue(j), i);
- keys.SetValue(key, j);
- if (items != null)
- {
- Object item = items.GetValue(i);
- items.SetValue(items.GetValue(j), i);
- items.SetValue(item, j);
- }
- }
- if (i != Int32.MaxValue) ++i;
- if (j != Int32.MinValue) --j;
- } while (i <= j);
-
- // The next iteration of the while loop is to "recursively" sort the larger half of the array and the
- // following calls recursively sort the smaller half. So we subtract one from depthLimit here so
- // both sorts see the new value.
- depthLimit--;
-
- if (j - left <= right - i)
- {
- if (left < j) DepthLimitedQuickSort(left, j, depthLimit);
- left = i;
- }
- else
- {
- if (i < right) DepthLimitedQuickSort(i, right, depthLimit);
- right = j;
- }
- } while (left < right);
}
private void IntrospectiveSort(int left, int length)
@@ -2530,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;
@@ -2551,8 +2342,8 @@ namespace System {
public Object Current {
get {
- if (_index < 0) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted);
- if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded);
+ if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
+ if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return _array.GetValue(_index);
}
}
@@ -2629,8 +2420,8 @@ namespace System {
public Object Current {
get {
- if (index < startIndex) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted);
- if (_complete) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded);
+ if (index < startIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
+ if (_complete) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return array.GetValue(_indices);
}
}
@@ -2652,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();
}
@@ -2689,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!
@@ -2707,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!
@@ -2716,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!
@@ -2727,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!
@@ -2739,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!
@@ -2756,12 +2541,11 @@ 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!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
- return Array.IndexOf(_this, value) != -1;
+ return Array.IndexOf(_this, value, 0, _this.Length) >= 0;
}
bool get_IsReadOnly<T>() {
@@ -2775,12 +2559,11 @@ 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!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
- return Array.IndexOf(_this, value);
+ return Array.IndexOf(_this, value, 0, _this.Length);
}
void Insert<T>(int index, T value) {
@@ -2812,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;
@@ -2828,8 +2611,8 @@ namespace System {
public T Current {
get {
- if (_index < 0) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted);
- if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded);
+ if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
+ if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return _array[_index];
}
}
diff --git a/src/mscorlib/src/System/ArraySegment.cs b/src/mscorlib/src/System/ArraySegment.cs
index bc39c2474f..b767e7bd77 100644
--- a/src/mscorlib/src/System/ArraySegment.cs
+++ b/src/mscorlib/src/System/ArraySegment.cs
@@ -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,19 +103,38 @@ 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()
{
- return null == _array
- ? 0
- : _array.GetHashCode() ^ _offset ^ _count;
+ if (_array == null)
+ {
+ return 0;
+ }
+
+ int hash = 5381;
+ hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset);
+ hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count);
+
+ // The array hash is expected to be an evenly-distributed mixture of bits,
+ // so rather than adding the cost of another rotation we just xor it.
+ hash ^= _array.GetHashCode();
+ return hash;
}
public override bool Equals(Object obj)
@@ -174,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;
@@ -236,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;
@@ -259,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()
@@ -315,19 +323,15 @@ namespace System
{
get
{
- if (_current < _start) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted);
- if (_current >= _end) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.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()
{
diff --git a/src/mscorlib/src/System/Attribute.cs b/src/mscorlib/src/System/Attribute.cs
index 6475d8d7e7..e77450e972 100644
--- a/src/mscorlib/src/System/Attribute.cs
+++ b/src/mscorlib/src/System/Attribute.cs
@@ -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);
@@ -456,10 +456,10 @@ namespace System {
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
{
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
@@ -486,7 +486,7 @@ namespace System {
public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
{
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
Contract.EndContractBlock();
switch (element.MemberType)
@@ -511,10 +511,10 @@ namespace System {
{
// Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
@@ -568,16 +568,16 @@ namespace System {
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
{
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
if (element.Member == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), nameof(element));
Contract.EndContractBlock();
@@ -591,10 +591,10 @@ namespace System {
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
{
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
if (element.Member == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), nameof(element));
Contract.EndContractBlock();
@@ -614,10 +614,10 @@ namespace System {
{
// Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
@@ -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"));
}
}
@@ -681,7 +681,7 @@ namespace System {
public static Attribute[] GetCustomAttributes(Module element, bool inherit)
{
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
@@ -690,10 +690,10 @@ namespace System {
public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit)
{
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
@@ -711,10 +711,10 @@ namespace System {
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
@@ -754,10 +754,10 @@ namespace System {
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit)
{
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
@@ -774,7 +774,7 @@ namespace System {
public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
{
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
@@ -789,10 +789,10 @@ namespace System {
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
- throw new ArgumentNullException("element");
+ throw new ArgumentNullException(nameof(element));
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
@@ -830,14 +830,13 @@ namespace System {
#endregion
#region Object Overrides
- [SecuritySafeCritical]
public override bool Equals(Object obj)
{
if (obj == null)
return false;
- RuntimeType thisType = (RuntimeType)this.GetType();
- RuntimeType thatType = (RuntimeType)obj.GetType();
+ Type thisType = this.GetType();
+ Type thatType = obj.GetType();
if (thatType != thisType)
return false;
@@ -845,18 +844,22 @@ namespace System {
Object thisObj = this;
Object thisResult, thatResult;
- FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
-
- for (int i = 0; i < thisFields.Length; i++)
+ while (thisType != typeof(Attribute))
{
- // Visibility check and consistency check are not necessary.
- thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
- thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);
+ FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
- if (!AreFieldValuesEqual(thisResult, thatResult))
+ for (int i = 0; i < thisFields.Length; i++)
{
- return false;
+ // Visibility check and consistency check are not necessary.
+ thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
+ thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);
+
+ if (!AreFieldValuesEqual(thisResult, thatResult))
+ {
+ return false;
+ }
}
+ thisType = thisType.BaseType;
}
return true;
@@ -887,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)))
@@ -901,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;
}
@@ -909,32 +912,36 @@ namespace System {
return true;
}
- [SecuritySafeCritical]
public override int GetHashCode()
{
Type type = GetType();
- FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
- Object vThis = null;
-
- for (int i = 0; i < fields.Length; i++)
+ while (type != typeof(Attribute))
{
- // Visibility check and consistency check are not necessary.
- Object fieldValue = ((RtFieldInfo)fields[i]).UnsafeGetValue(this);
+ FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
+ Object vThis = null;
- // The hashcode of an array ignores the contents of the array, so it can produce
- // different hashcodes for arrays with the same contents.
- // Since we do deep comparisons of arrays in Equals(), this means Equals and GetHashCode will
- // be inconsistent for arrays. Therefore, we ignore hashes of arrays.
- if (fieldValue != null && !fieldValue.GetType().IsArray)
- vThis = fieldValue;
+ for (int i = 0; i < fields.Length; i++)
+ {
+ // Visibility check and consistency check are not necessary.
+ Object fieldValue = ((RtFieldInfo)fields[i]).UnsafeGetValue(this);
+
+ // The hashcode of an array ignores the contents of the array, so it can produce
+ // different hashcodes for arrays with the same contents.
+ // Since we do deep comparisons of arrays in Equals(), this means Equals and GetHashCode will
+ // be inconsistent for arrays. Therefore, we ignore hashes of arrays.
+ if (fieldValue != null && !fieldValue.GetType().IsArray)
+ vThis = fieldValue;
+
+ if (vThis != null)
+ break;
+ }
if (vThis != null)
- break;
- }
+ return vThis.GetHashCode();
- if (vThis != null)
- return vThis.GetHashCode();
+ type = type.BaseType;
+ }
return type.GetHashCode();
}
@@ -949,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
}
}
diff --git a/src/mscorlib/src/System/BCLDebug.cs b/src/mscorlib/src/System/BCLDebug.cs
index 9b2ade26fa..0ca6e616f2 100644
--- a/src/mscorlib/src/System/BCLDebug.cs
+++ b/src/mscorlib/src/System/BCLDebug.cs
@@ -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,33 +332,9 @@ namespace System {
System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, trace.ToString());
}
- // 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);
- }
- }
-
// 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())
@@ -384,7 +354,6 @@ namespace System {
// BCLCorrectnessWarnings to non-zero.
[Conditional("_DEBUG")]
#if _DEBUG
- [SecuritySafeCritical]
#endif
internal static void Correctness(bool expr, String msg)
{
@@ -409,7 +378,6 @@ namespace System {
}
#if !BIT64 // 32
- [SecuritySafeCritical]
#endif
internal static bool CorrectnessEnabled()
{
diff --git a/src/mscorlib/src/System/BadImageFormatException.cs b/src/mscorlib/src/System/BadImageFormatException.cs
index b71fcc3a49..3f3f4a5b6e 100644
--- a/src/mscorlib/src/System/BadImageFormatException.cs
+++ b/src/mscorlib/src/System/BadImageFormatException.cs
@@ -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);
diff --git a/src/mscorlib/src/System/BitConverter.cs b/src/mscorlib/src/System/BitConverter.cs
index e4bb9ddc88..3a6d1c03b0 100644
--- a/src/mscorlib/src/System/BitConverter.cs
+++ b/src/mscorlib/src/System/BitConverter.cs
@@ -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);
@@ -156,7 +152,7 @@ namespace System {
}
if ((uint)startIndex >= value.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (startIndex > value.Length - 2) {
@@ -168,14 +164,13 @@ 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);
}
if ((uint) startIndex >= value.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (startIndex > value.Length -2) {
@@ -200,14 +195,13 @@ 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);
}
if ((uint) startIndex >= value.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (startIndex > value.Length -4) {
@@ -231,14 +225,13 @@ 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);
}
if ((uint) startIndex >= value.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (startIndex > value.Length -8) {
@@ -274,7 +267,7 @@ namespace System {
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
if (startIndex > value.Length - 2)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
@@ -290,7 +283,7 @@ namespace System {
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
if (startIndex > value.Length - 4)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
@@ -306,7 +299,7 @@ namespace System {
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
if (startIndex > value.Length - 8)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
@@ -315,13 +308,12 @@ 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)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
if (startIndex > value.Length - 4)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
@@ -331,13 +323,12 @@ 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)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
if (startIndex > value.Length - 8)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
@@ -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');
}
@@ -358,15 +349,15 @@ namespace System {
// Converts an array of bytes into a String.
public static String ToString (byte[] value, int startIndex, int length) {
if (value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array.
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (length < 0) {
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
if (startIndex > value.Length - length) {
@@ -380,7 +371,7 @@ namespace System {
if (length > (Int32.MaxValue / 3)) {
// (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3)));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3)));
}
int chArrayLength = length * 3;
@@ -402,7 +393,7 @@ namespace System {
// Converts an array of bytes into a String.
public static String ToString(byte [] value) {
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return ToString(value, 0, value.Length);
@@ -411,7 +402,7 @@ namespace System {
// Converts an array of bytes into a String.
public static String ToString (byte [] value, int startIndex) {
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return ToString(value, startIndex, value.Length - startIndex);
@@ -428,24 +419,30 @@ namespace System {
// Converts an array of bytes into a boolean.
public static bool ToBoolean(byte[] value, int startIndex) {
if (value==null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (startIndex > value.Length - 1)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
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);
- }
+ }
+
+ public static unsafe int SingleToInt32Bits(float value) {
+ return *((int*)&value);
+ }
+
+ public static unsafe float Int32BitsToSingle(int value) {
+ return *((float*)&value);
+ }
}
}
diff --git a/src/mscorlib/src/System/Boolean.cs b/src/mscorlib/src/System/Boolean.cs
index c5cd45a428..9aaec9a345 100644
--- a/src/mscorlib/src/System/Boolean.cs
+++ b/src/mscorlib/src/System/Boolean.cs
@@ -151,7 +151,7 @@ namespace System {
// Determines whether a String represents true or false.
//
public static Boolean Parse (String value) {
- if (value==null) throw new ArgumentNullException("value");
+ if (value==null) throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
Boolean result = false;
if (!TryParse(value, out result)) {
diff --git a/src/mscorlib/src/System/Buffer.cs b/src/mscorlib/src/System/Buffer.cs
index ea647f1e9a..eee2a81b51 100644
--- a/src/mscorlib/src/System/Buffer.cs
+++ b/src/mscorlib/src/System/Buffer.cs
@@ -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,24 +129,22 @@ 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?
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
// Is it of primitive types?
if (!IsPrimitiveTypeArray(array))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array));
// Is the index in valid range of the array?
if (index < 0 || index >= _ByteLength(array))
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
return _GetByte(array, index);
}
@@ -160,24 +155,22 @@ 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?
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
// Is it of primitive types?
if (!IsPrimitiveTypeArray(array))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array));
// Is the index in valid range of the array?
if (index < 0 || index >= _ByteLength(array))
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
// Make the FCall to do the work
_SetByte(array, index, value);
@@ -190,36 +183,32 @@ 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?
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
// Is it of primitive types?
if (!IsPrimitiveTypeArray(array))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array));
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)
diff --git a/src/mscorlib/src/System/ByReference.cs b/src/mscorlib/src/System/ByReference.cs
new file mode 100644
index 0000000000..6f8bb2281e
--- /dev/null
+++ b/src/mscorlib/src/System/ByReference.cs
@@ -0,0 +1,31 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.CompilerServices;
+
+namespace System
+{
+ // ByReference<T> is meant to be used to represent "ref T" fields. It is working
+ // around lack of first class support for byref fields in C# and IL. The JIT and
+ // type loader has special handling for it that turns it into a thin wrapper around ref T.
+ internal struct ByReference<T>
+ {
+ private IntPtr _value;
+
+ public ByReference(ref T value)
+ {
+ // TODO-SPAN: This has GC hole. It needs to be JIT intrinsic instead
+ unsafe { _value = (IntPtr)Unsafe.AsPointer(ref value); }
+ }
+
+ public ref T Value
+ {
+ get
+ {
+ // TODO-SPAN: This has GC hole. It needs to be JIT intrinsic instead
+ unsafe { return ref Unsafe.As<IntPtr, T>(ref *(IntPtr*)_value); }
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Byte.cs b/src/mscorlib/src/System/Byte.cs
index 2c24bf6d3b..980412b69e 100644
--- a/src/mscorlib/src/System/Byte.cs
+++ b/src/mscorlib/src/System/Byte.cs
@@ -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));
diff --git a/src/mscorlib/src/System/CLRConfig.cs b/src/mscorlib/src/System/CLRConfig.cs
index 0831c4bb65..01ad7c31ab 100644
--- a/src/mscorlib/src/System/CLRConfig.cs
+++ b/src/mscorlib/src/System/CLRConfig.cs
@@ -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();
diff --git a/src/mscorlib/src/System/CfgParser.cs b/src/mscorlib/src/System/CfgParser.cs
index ef368a9020..b21da7fe94 100644
--- a/src/mscorlib/src/System/CfgParser.cs
+++ b/src/mscorlib/src/System/CfgParser.cs
@@ -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,11 +244,10 @@ namespace System
return Parse(fileName, configPath, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal ConfigNode Parse(String fileName, String configPath, bool skipSecurityStuff)
{
if (fileName == null)
- throw new ArgumentNullException("fileName");
+ throw new ArgumentNullException(nameof(fileName));
Contract.EndContractBlock();
this.fileName = fileName;
if (configPath[0] == '/'){
@@ -264,7 +262,7 @@ namespace System
}
if (!skipSecurityStuff) {
- (new FileIOPermission( FileIOPermissionAccess.Read, System.IO.Path.GetFullPathInternal( fileName ) )).Demand();
+ (new FileIOPermission(FileIOPermissionAccess.Read, Path.GetFullPath(fileName))).Demand();
}
#pragma warning disable 618
(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert();
@@ -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
}
}
}
diff --git a/src/mscorlib/src/System/Char.cs b/src/mscorlib/src/System/Char.cs
index ff936c6618..b9c9305932 100644
--- a/src/mscorlib/src/System/Char.cs
+++ b/src/mscorlib/src/System/Char.cs
@@ -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]);
}
@@ -167,7 +168,7 @@ namespace System {
public static char Parse(String s) {
if (s==null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
@@ -364,7 +365,7 @@ namespace System {
// <;<;Not fully implemented>;>;
public static char ToUpper(char c, CultureInfo culture) {
if (culture==null)
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
Contract.EndContractBlock();
return culture.TextInfo.ToUpper(c);
}
@@ -393,7 +394,7 @@ namespace System {
// <;<;Not fully implemented>;>;
public static char ToLower(char c, CultureInfo culture) {
if (culture==null)
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
Contract.EndContractBlock();
return culture.TextInfo.ToLower(c);
}
@@ -508,9 +509,9 @@ namespace System {
public static bool IsControl(String s, int index) {
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
@@ -524,9 +525,9 @@ namespace System {
public static bool IsDigit(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
@@ -539,9 +540,9 @@ namespace System {
public static bool IsLetter(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
@@ -558,9 +559,9 @@ namespace System {
public static bool IsLetterOrDigit(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
@@ -573,9 +574,9 @@ namespace System {
public static bool IsLower(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
@@ -617,9 +618,9 @@ namespace System {
public static bool IsNumber(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
@@ -643,9 +644,9 @@ namespace System {
public static bool IsPunctuation (String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
@@ -688,9 +689,9 @@ namespace System {
public static bool IsSeparator(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
@@ -710,10 +711,10 @@ namespace System {
public static bool IsSurrogate(String s, int index)
{
if (s==null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return (IsSurrogate(s[index]));
@@ -745,9 +746,9 @@ namespace System {
public static bool IsSymbol(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
if (IsLatin1(s[index])) {
@@ -760,9 +761,9 @@ namespace System {
public static bool IsUpper(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
@@ -779,9 +780,9 @@ namespace System {
public static bool IsWhiteSpace(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
@@ -803,9 +804,9 @@ namespace System {
public static UnicodeCategory GetUnicodeCategory(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
if (IsLatin1(s[index])) {
@@ -822,9 +823,9 @@ namespace System {
public static double GetNumericValue(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return CharUnicodeInfo.GetNumericValue(s, index);
@@ -842,10 +843,10 @@ namespace System {
[Pure]
public static bool IsHighSurrogate(String s, int index) {
if (s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return (IsHighSurrogate(s[index]));
@@ -862,10 +863,10 @@ namespace System {
[Pure]
public static bool IsLowSurrogate(String s, int index) {
if (s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return (IsLowSurrogate(s[index]));
@@ -877,10 +878,10 @@ namespace System {
[Pure]
public static bool IsSurrogatePair(String s, int index) {
if (s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
if (index + 1 < s.Length) {
@@ -911,13 +912,12 @@ 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
// are considered as irregular code unit sequence, but they are not illegal.
if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END)) {
- throw new ArgumentOutOfRangeException("utf32", Environment.GetResourceString("ArgumentOutOfRange_InvalidUTF32"));
+ throw new ArgumentOutOfRangeException(nameof(utf32), Environment.GetResourceString("ArgumentOutOfRange_InvalidUTF32"));
}
Contract.EndContractBlock();
@@ -945,10 +945,10 @@ namespace System {
public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) {
if (!IsHighSurrogate(highSurrogate)) {
- throw new ArgumentOutOfRangeException("highSurrogate", Environment.GetResourceString("ArgumentOutOfRange_InvalidHighSurrogate"));
+ throw new ArgumentOutOfRangeException(nameof(highSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidHighSurrogate"));
}
if (!IsLowSurrogate(lowSurrogate)) {
- throw new ArgumentOutOfRangeException("lowSurrogate", Environment.GetResourceString("ArgumentOutOfRange_InvalidLowSurrogate"));
+ throw new ArgumentOutOfRangeException(nameof(lowSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidLowSurrogate"));
}
Contract.EndContractBlock();
return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START);
@@ -964,11 +964,11 @@ namespace System {
public static int ConvertToUtf32(String s, int index) {
if (s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
// Check if the character at index is a high surrogate.
@@ -983,15 +983,15 @@ namespace System {
// Found a low surrogate.
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
} else {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), "s");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), nameof(s));
}
} else {
// Found a high surrogate at the end of the string.
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), "s");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), nameof(s));
}
} else {
// Find a low surrogate at the character pointed by index.
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidLowSurrogate", index), "s");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidLowSurrogate", index), nameof(s));
}
}
// Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters.
diff --git a/src/mscorlib/src/System/Collections/ArrayList.cs b/src/mscorlib/src/System/Collections/ArrayList.cs
index 94f4dc74e8..e7f121370b 100644
--- a/src/mscorlib/src/System/Collections/ArrayList.cs
+++ b/src/mscorlib/src/System/Collections/ArrayList.cs
@@ -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]
@@ -68,7 +66,7 @@ namespace System.Collections {
// before any reallocations are required.
//
public ArrayList(int capacity) {
- if (capacity < 0) throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", "capacity"));
+ if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(capacity)));
Contract.EndContractBlock();
if (capacity == 0)
@@ -83,7 +81,7 @@ namespace System.Collections {
//
public ArrayList(ICollection c) {
if (c==null)
- throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection"));
+ throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection"));
Contract.EndContractBlock();
int count = c.Count;
@@ -108,7 +106,7 @@ namespace System.Collections {
}
set {
if (value < _size) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
Contract.Ensures(Capacity >= 0);
Contract.EndContractBlock();
@@ -166,12 +164,12 @@ namespace System.Collections {
//
public virtual Object this[int index] {
get {
- if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return _items[index];
}
set {
- if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
_items[index] = value;
_version++;
@@ -188,7 +186,7 @@ namespace System.Collections {
//
public static ArrayList Adapter(IList list) {
if (list==null)
- throw new ArgumentNullException("list");
+ throw new ArgumentNullException(nameof(list));
Contract.Ensures(Contract.Result<ArrayList>() != null);
Contract.EndContractBlock();
return new IListWrapper(list);
@@ -236,9 +234,9 @@ namespace System.Collections {
//
public virtual int BinarySearch(int index, int count, Object value, IComparer comparer) {
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_size - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<int>() < Count);
@@ -356,7 +354,7 @@ namespace System.Collections {
//
public static IList FixedSize(IList list) {
if (list==null)
- throw new ArgumentNullException("list");
+ throw new ArgumentNullException(nameof(list));
Contract.Ensures(Contract.Result<IList>() != null);
Contract.EndContractBlock();
return new FixedSizeList(list);
@@ -367,7 +365,7 @@ namespace System.Collections {
//
public static ArrayList FixedSize(ArrayList list) {
if (list==null)
- throw new ArgumentNullException("list");
+ throw new ArgumentNullException(nameof(list));
Contract.Ensures(Contract.Result<ArrayList>() != null);
Contract.EndContractBlock();
return new FixedSizeArrayList(list);
@@ -390,9 +388,9 @@ namespace System.Collections {
//
public virtual IEnumerator GetEnumerator(int index, int count) {
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_size - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<IEnumerator>() != null);
@@ -425,7 +423,7 @@ namespace System.Collections {
//
public virtual int IndexOf(Object value, int startIndex) {
if (startIndex > _size)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf((Array)_items, value, startIndex, _size - startIndex);
@@ -442,8 +440,8 @@ namespace System.Collections {
//
public virtual int IndexOf(Object value, int startIndex, int count) {
if (startIndex > _size)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (count <0 || startIndex > _size - count) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (count <0 || startIndex > _size - count) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf((Array)_items, value, startIndex, count);
@@ -455,7 +453,7 @@ namespace System.Collections {
//
public virtual void Insert(int index, Object value) {
// Note that insertions at the end are legal.
- if (index < 0 || index > _size) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_ArrayListInsert"));
+ if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_ArrayListInsert"));
//Contract.Ensures(Count == Contract.OldValue(Count) + 1);
Contract.EndContractBlock();
@@ -475,8 +473,8 @@ namespace System.Collections {
//
public virtual void InsertRange(int index, ICollection c) {
if (c==null)
- throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection"));
- if (index < 0 || index > _size) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection"));
+ if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
//Contract.Ensures(Count == Contract.OldValue(Count) + c.Count);
Contract.EndContractBlock();
@@ -522,7 +520,7 @@ namespace System.Collections {
public virtual int LastIndexOf(Object value, int startIndex)
{
if (startIndex >= _size)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return LastIndexOf(value, startIndex, startIndex + 1);
@@ -539,7 +537,7 @@ namespace System.Collections {
//
public virtual int LastIndexOf(Object value, int startIndex, int count) {
if (Count != 0 && (startIndex < 0 || count < 0))
- throw new ArgumentOutOfRangeException((startIndex<0 ? "startIndex" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((startIndex<0 ? nameof(startIndex) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
@@ -547,19 +545,17 @@ namespace System.Collections {
return -1;
if (startIndex >= _size || count > startIndex + 1)
- throw new ArgumentOutOfRangeException((startIndex>=_size ? "startIndex" : "count"), Environment.GetResourceString("ArgumentOutOfRange_BiggerThanCollection"));
+ throw new ArgumentOutOfRangeException((startIndex>=_size ? nameof(startIndex) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_BiggerThanCollection"));
return Array.LastIndexOf((Array)_items, value, startIndex, count);
}
// 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("list");
+ throw new ArgumentNullException(nameof(list));
Contract.Ensures(Contract.Result<IList>() != null);
Contract.EndContractBlock();
return new ReadOnlyList(list);
@@ -569,7 +565,7 @@ namespace System.Collections {
//
public static ArrayList ReadOnly(ArrayList list) {
if (list==null)
- throw new ArgumentNullException("list");
+ throw new ArgumentNullException(nameof(list));
Contract.Ensures(Contract.Result<ArrayList>() != null);
Contract.EndContractBlock();
return new ReadOnlyArrayList(list);
@@ -591,7 +587,7 @@ namespace System.Collections {
// decreased by one.
//
public virtual void RemoveAt(int index) {
- if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.Ensures(Count >= 0);
//Contract.Ensures(Count == Contract.OldValue(Count) - 1);
Contract.EndContractBlock();
@@ -608,9 +604,9 @@ namespace System.Collections {
//
public virtual void RemoveRange(int index, int count) {
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_size - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Count >= 0);
@@ -632,7 +628,7 @@ namespace System.Collections {
//
public static ArrayList Repeat(Object value, int count) {
if (count < 0)
- throw new ArgumentOutOfRangeException("count",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Contract.Result<ArrayList>() != null);
Contract.EndContractBlock();
@@ -657,9 +653,9 @@ namespace System.Collections {
//
public virtual void Reverse(int index, int count) {
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_size - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -671,10 +667,10 @@ namespace System.Collections {
// given collection.
//
public virtual void SetRange(int index, ICollection c) {
- if (c==null) throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection"));
+ if (c==null) throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection"));
Contract.EndContractBlock();
int count = c.Count;
- if (index < 0 || index > _size - count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index > _size - count) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count > 0) {
c.CopyTo(_items, index);
@@ -684,7 +680,7 @@ namespace System.Collections {
public virtual ArrayList GetRange(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_size - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<ArrayList>() != null);
@@ -716,9 +712,9 @@ namespace System.Collections {
//
public virtual void Sort(int index, int count, IComparer comparer) {
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_size - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -729,10 +725,9 @@ 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("list");
+ throw new ArgumentNullException(nameof(list));
Contract.Ensures(Contract.Result<IList>() != null);
Contract.EndContractBlock();
return new SyncIList(list);
@@ -740,10 +735,9 @@ 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("list");
+ throw new ArgumentNullException(nameof(list));
Contract.Ensures(Contract.Result<ArrayList>() != null);
Contract.EndContractBlock();
return new SyncArrayList(list);
@@ -764,10 +758,9 @@ 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("type");
+ throw new ArgumentNullException(nameof(type));
Contract.Ensures(Contract.Result<Array>() != null);
Contract.EndContractBlock();
Array array = Array.UnsafeCreateInstance(type, _size);
@@ -804,7 +797,7 @@ namespace System.Collections {
public override int Capacity {
get { return _list.Count; }
set {
- if (value < Count) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ if (value < Count) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
Contract.EndContractBlock();
}
}
@@ -854,7 +847,7 @@ namespace System.Collections {
public override int BinarySearch(int index, int count, Object value, IComparer comparer)
{
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (this.Count - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -906,11 +899,11 @@ namespace System.Collections {
public override void CopyTo(int index, Array array, int arrayIndex, int count) {
if (array==null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (index < 0 || arrayIndex < 0)
- throw new ArgumentOutOfRangeException((index < 0) ? "index" : "arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if( count < 0)
- throw new ArgumentOutOfRangeException( "count" , Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException( nameof(count) , Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - arrayIndex < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
if (array.Rank != 1)
@@ -930,7 +923,7 @@ namespace System.Collections {
public override IEnumerator GetEnumerator(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (_list.Count - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
@@ -948,8 +941,8 @@ namespace System.Collections {
}
public override int IndexOf(Object value, int startIndex, int count) {
- if (startIndex < 0 || startIndex > this.Count) throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (count < 0 || startIndex > this.Count - count) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ if (startIndex < 0 || startIndex > this.Count) throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (count < 0 || startIndex > this.Count - count) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
Contract.EndContractBlock();
int endIndex = startIndex + count;
@@ -973,8 +966,8 @@ namespace System.Collections {
public override void InsertRange(int index, ICollection c) {
if (c==null)
- throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection"));
- if (index < 0 || index > this.Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection"));
+ if (index < 0 || index > this.Count) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
if( c.Count > 0) {
@@ -1009,8 +1002,8 @@ namespace System.Collections {
if (_list.Count == 0)
return -1;
- if (startIndex < 0 || startIndex >= _list.Count) throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (count < 0 || count > startIndex + 1) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ if (startIndex < 0 || startIndex >= _list.Count) throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (count < 0 || count > startIndex + 1) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
int endIndex = startIndex - count + 1;
if (value == null) {
@@ -1039,7 +1032,7 @@ namespace System.Collections {
public override void RemoveRange(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (_list.Count - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
@@ -1055,7 +1048,7 @@ namespace System.Collections {
public override void Reverse(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (_list.Count - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
@@ -1073,12 +1066,12 @@ namespace System.Collections {
public override void SetRange(int index, ICollection c) {
if (c==null) {
- throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection"));
+ throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection"));
}
Contract.EndContractBlock();
if (index < 0 || index > _list.Count - c.Count) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if( c.Count > 0) {
@@ -1092,7 +1085,7 @@ namespace System.Collections {
public override ArrayList GetRange(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (_list.Count - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
@@ -1101,7 +1094,7 @@ namespace System.Collections {
public override void Sort(int index, int count, IComparer comparer) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (_list.Count - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
@@ -1122,11 +1115,10 @@ namespace System.Collections {
return array;
}
- [SecuritySafeCritical]
public override Array ToArray(Type type)
{
if (type==null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
Array array = Array.UnsafeCreateInstance(type, _list.Count);
_list.CopyTo(array, 0);
@@ -1806,7 +1798,7 @@ namespace System.Collections {
public override ArrayList GetRange(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (Count - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -2062,7 +2054,7 @@ namespace System.Collections {
public override ArrayList GetRange(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (Count - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -2191,7 +2183,7 @@ namespace System.Collections {
public override void AddRange(ICollection c) {
if( c == null ) {
- throw new ArgumentNullException("c");
+ throw new ArgumentNullException(nameof(c));
}
Contract.EndContractBlock();
@@ -2207,7 +2199,7 @@ namespace System.Collections {
// Other overloads with automatically work
public override int BinarySearch(int index, int count, Object value, IComparer comparer) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_baseSize - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -2224,7 +2216,7 @@ namespace System.Collections {
}
set {
- if (value < Count) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ if (value < Count) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
Contract.EndContractBlock();
}
}
@@ -2265,11 +2257,11 @@ namespace System.Collections {
public override void CopyTo(Array array, int index) {
if (array==null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - index < _baseSize)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -2280,11 +2272,11 @@ namespace System.Collections {
public override void CopyTo(int index, Array array, int arrayIndex, int count) {
if (array==null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - arrayIndex < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
if (_baseSize - index < count)
@@ -2320,7 +2312,7 @@ namespace System.Collections {
public override IEnumerator GetEnumerator(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_baseSize - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -2331,7 +2323,7 @@ namespace System.Collections {
public override ArrayList GetRange(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_baseSize - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -2356,9 +2348,9 @@ namespace System.Collections {
public override int IndexOf(Object value, int startIndex) {
if (startIndex < 0)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (startIndex > _baseSize)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
InternalUpdateRange();
@@ -2369,10 +2361,10 @@ namespace System.Collections {
public override int IndexOf(Object value, int startIndex, int count) {
if (startIndex < 0 || startIndex > _baseSize)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count < 0 || (startIndex > _baseSize - count))
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
Contract.EndContractBlock();
InternalUpdateRange();
@@ -2382,7 +2374,7 @@ namespace System.Collections {
}
public override void Insert(int index, Object value) {
- if (index < 0 || index > _baseSize) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index > _baseSize) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
InternalUpdateRange();
@@ -2392,9 +2384,9 @@ namespace System.Collections {
}
public override void InsertRange(int index, ICollection c) {
- if (index < 0 || index > _baseSize) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index > _baseSize) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if( c == null) {
- throw new ArgumentNullException("c");
+ throw new ArgumentNullException(nameof(c));
}
Contract.EndContractBlock();
@@ -2426,9 +2418,9 @@ namespace System.Collections {
return -1;
if (startIndex >= _baseSize)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (startIndex < 0)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
int i = _baseList.LastIndexOf(value, _baseIndex + startIndex, count);
if (i >= 0) return i - _baseIndex;
@@ -2438,7 +2430,7 @@ namespace System.Collections {
// Don't need to override Remove
public override void RemoveAt(int index) {
- if (index < 0 || index >= _baseSize) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= _baseSize) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
InternalUpdateRange();
@@ -2449,7 +2441,7 @@ namespace System.Collections {
public override void RemoveRange(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_baseSize - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -2466,7 +2458,7 @@ namespace System.Collections {
public override void Reverse(int index, int count) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_baseSize - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -2479,7 +2471,7 @@ namespace System.Collections {
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void SetRange(int index, ICollection c) {
InternalUpdateRange();
- if (index < 0 || index >= _baseSize) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= _baseSize) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
_baseList.SetRange(_baseIndex + index, c);
if( c.Count > 0) {
InternalUpdateVersion();
@@ -2488,7 +2480,7 @@ namespace System.Collections {
public override void Sort(int index, int count, IComparer comparer) {
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_baseSize - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -2501,12 +2493,12 @@ namespace System.Collections {
public override Object this[int index] {
get {
InternalUpdateRange();
- if (index < 0 || index >= _baseSize) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= _baseSize) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
return _baseList[_baseIndex + index];
}
set {
InternalUpdateRange();
- if (index < 0 || index >= _baseSize) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= _baseSize) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
_baseList[_baseIndex + index] = value;
InternalUpdateVersion();
}
@@ -2519,10 +2511,9 @@ namespace System.Collections {
return array;
}
- [SecuritySafeCritical]
public override Array ToArray(Type type) {
if (type==null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
InternalUpdateRange();
@@ -2619,7 +2610,7 @@ namespace System.Collections {
public ArrayListDebugView( ArrayList arrayList) {
if( arrayList == null)
- throw new ArgumentNullException("arrayList");
+ throw new ArgumentNullException(nameof(arrayList));
this.arrayList = arrayList;
}
diff --git a/src/mscorlib/src/System/Collections/BitArray.cs b/src/mscorlib/src/System/Collections/BitArray.cs
deleted file mode 100644
index 2f565f83af..0000000000
--- a/src/mscorlib/src/System/Collections/BitArray.cs
+++ /dev/null
@@ -1,524 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-**
-**
-** Purpose: The BitArray class manages a compact array of bit values.
-**
-**
-=============================================================================*/
-namespace System.Collections {
-
- using System;
- using System.Security.Permissions;
- using System.Diagnostics.Contracts;
- // A vector of bits. Use this to store bits efficiently, without having to do bit
- // shifting yourself.
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable()] public sealed class BitArray : ICollection, ICloneable {
- private BitArray() {
- }
-
- /*=========================================================================
- ** Allocates space to hold length bit values. All of the values in the bit
- ** array are set to false.
- **
- ** Exceptions: ArgumentException if length < 0.
- =========================================================================*/
- public BitArray(int length)
- : this(length, false) {
- }
-
- /*=========================================================================
- ** Allocates space to hold length bit values. All of the values in the bit
- ** array are set to defaultValue.
- **
- ** Exceptions: ArgumentOutOfRangeException if length < 0.
- =========================================================================*/
- public BitArray(int length, bool defaultValue) {
- if (length < 0) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- m_array = new int[GetArrayLength(length, BitsPerInt32)];
- m_length = length;
-
- int fillValue = defaultValue ? unchecked(((int)0xffffffff)) : 0;
- for (int i = 0; i < m_array.Length; i++) {
- m_array[i] = fillValue;
- }
-
- _version = 0;
- }
-
- /*=========================================================================
- ** Allocates space to hold the bit values in bytes. bytes[0] represents
- ** bits 0 - 7, bytes[1] represents bits 8 - 15, etc. The LSB of each byte
- ** represents the lowest index value; bytes[0] & 1 represents bit 0,
- ** bytes[0] & 2 represents bit 1, bytes[0] & 4 represents bit 2, etc.
- **
- ** Exceptions: ArgumentException if bytes == null.
- =========================================================================*/
- public BitArray(byte[] bytes) {
- if (bytes == null) {
- throw new ArgumentNullException(nameof(bytes));
- }
- Contract.EndContractBlock();
- // this value is chosen to prevent overflow when computing m_length.
- // m_length is of type int32 and is exposed as a property, so
- // type of m_length can't be changed to accommodate.
- if (bytes.Length > Int32.MaxValue / BitsPerByte) {
- throw new ArgumentException(Environment.GetResourceString("Argument_ArrayTooLarge", BitsPerByte), nameof(bytes));
- }
-
- m_array = new int[GetArrayLength(bytes.Length, BytesPerInt32)];
- m_length = bytes.Length * BitsPerByte;
-
- int i = 0;
- int j = 0;
- while (bytes.Length - j >= 4) {
- m_array[i++] = (bytes[j] & 0xff) |
- ((bytes[j + 1] & 0xff) << 8) |
- ((bytes[j + 2] & 0xff) << 16) |
- ((bytes[j + 3] & 0xff) << 24);
- j += 4;
- }
-
- Contract.Assert(bytes.Length - j >= 0, "BitArray byteLength problem");
- Contract.Assert(bytes.Length - j < 4, "BitArray byteLength problem #2");
-
- switch (bytes.Length - j) {
- case 3:
- m_array[i] = ((bytes[j + 2] & 0xff) << 16);
- goto case 2;
- // fall through
- case 2:
- m_array[i] |= ((bytes[j + 1] & 0xff) << 8);
- goto case 1;
- // fall through
- case 1:
- m_array[i] |= (bytes[j] & 0xff);
- break;
- }
-
- _version = 0;
- }
-
- public BitArray(bool[] values) {
- if (values == null) {
- throw new ArgumentNullException(nameof(values));
- }
- Contract.EndContractBlock();
-
- m_array = new int[GetArrayLength(values.Length, BitsPerInt32)];
- m_length = values.Length;
-
- for (int i = 0;i<values.Length;i++) {
- if (values[i])
- m_array[i/32] |= (1 << (i%32));
- }
-
- _version = 0;
-
- }
-
- /*=========================================================================
- ** Allocates space to hold the bit values in values. values[0] represents
- ** bits 0 - 31, values[1] represents bits 32 - 63, etc. The LSB of each
- ** integer represents the lowest index value; values[0] & 1 represents bit
- ** 0, values[0] & 2 represents bit 1, values[0] & 4 represents bit 2, etc.
- **
- ** Exceptions: ArgumentException if values == null.
- =========================================================================*/
- public BitArray(int[] values) {
- if (values == null) {
- throw new ArgumentNullException(nameof(values));
- }
- Contract.EndContractBlock();
- // this value is chosen to prevent overflow when computing m_length
- if (values.Length > Int32.MaxValue / BitsPerInt32) {
- throw new ArgumentException(Environment.GetResourceString("Argument_ArrayTooLarge", BitsPerInt32), nameof(values));
- }
-
- m_array = new int[values.Length];
- m_length = values.Length * BitsPerInt32;
-
- Array.Copy(values, m_array, values.Length);
-
- _version = 0;
- }
-
- /*=========================================================================
- ** Allocates a new BitArray with the same length and bit values as bits.
- **
- ** Exceptions: ArgumentException if bits == null.
- =========================================================================*/
- public BitArray(BitArray bits) {
- if (bits == null) {
- throw new ArgumentNullException(nameof(bits));
- }
- Contract.EndContractBlock();
-
- int arrayLength = GetArrayLength(bits.m_length, BitsPerInt32);
- m_array = new int[arrayLength];
- m_length = bits.m_length;
-
- Array.Copy(bits.m_array, m_array, arrayLength);
-
- _version = bits._version;
- }
-
- public bool this[int index] {
- get {
- return Get(index);
- }
- set {
- Set(index,value);
- }
- }
-
- /*=========================================================================
- ** Returns the bit value at position index.
- **
- ** Exceptions: ArgumentOutOfRangeException if index < 0 or
- ** index >= GetLength().
- =========================================================================*/
- public bool Get(int index) {
- if (index < 0 || index >= Length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- Contract.EndContractBlock();
-
- return (m_array[index / 32] & (1 << (index % 32))) != 0;
- }
-
- /*=========================================================================
- ** Sets the bit value at position index to value.
- **
- ** Exceptions: ArgumentOutOfRangeException if index < 0 or
- ** index >= GetLength().
- =========================================================================*/
- public void Set(int index, bool value) {
- if (index < 0 || index >= Length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- Contract.EndContractBlock();
-
- if (value) {
- m_array[index / 32] |= (1 << (index % 32));
- } else {
- m_array[index / 32] &= ~(1 << (index % 32));
- }
-
- _version++;
- }
-
- /*=========================================================================
- ** Sets all the bit values to value.
- =========================================================================*/
- public void SetAll(bool value) {
- int fillValue = value ? unchecked(((int)0xffffffff)) : 0;
- int ints = GetArrayLength(m_length, BitsPerInt32);
- for (int i = 0; i < ints; i++) {
- m_array[i] = fillValue;
- }
-
- _version++;
- }
-
- /*=========================================================================
- ** Returns a reference to the current instance ANDed with value.
- **
- ** Exceptions: ArgumentException if value == null or
- ** value.Length != this.Length.
- =========================================================================*/
- public BitArray And(BitArray value) {
- if (value==null)
- throw new ArgumentNullException(nameof(value));
- if (Length != value.Length)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"));
- Contract.EndContractBlock();
-
- int ints = GetArrayLength(m_length, BitsPerInt32);
- for (int i = 0; i < ints; i++) {
- m_array[i] &= value.m_array[i];
- }
-
- _version++;
- return this;
- }
-
- /*=========================================================================
- ** Returns a reference to the current instance ORed with value.
- **
- ** Exceptions: ArgumentException if value == null or
- ** value.Length != this.Length.
- =========================================================================*/
- public BitArray Or(BitArray value) {
- if (value==null)
- throw new ArgumentNullException(nameof(value));
- if (Length != value.Length)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"));
- Contract.EndContractBlock();
-
- int ints = GetArrayLength(m_length, BitsPerInt32);
- for (int i = 0; i < ints; i++) {
- m_array[i] |= value.m_array[i];
- }
-
- _version++;
- return this;
- }
-
- /*=========================================================================
- ** Returns a reference to the current instance XORed with value.
- **
- ** Exceptions: ArgumentException if value == null or
- ** value.Length != this.Length.
- =========================================================================*/
- public BitArray Xor(BitArray value) {
- if (value==null)
- throw new ArgumentNullException(nameof(value));
- if (Length != value.Length)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"));
- Contract.EndContractBlock();
-
- int ints = GetArrayLength(m_length, BitsPerInt32);
- for (int i = 0; i < ints; i++) {
- m_array[i] ^= value.m_array[i];
- }
-
- _version++;
- return this;
- }
-
- /*=========================================================================
- ** Inverts all the bit values. On/true bit values are converted to
- ** off/false. Off/false bit values are turned on/true. The current instance
- ** is updated and returned.
- =========================================================================*/
- public BitArray Not() {
- int ints = GetArrayLength(m_length, BitsPerInt32);
- for (int i = 0; i < ints; i++) {
- m_array[i] = ~m_array[i];
- }
-
- _version++;
- return this;
- }
-
- public int Length {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- return m_length;
- }
- set {
- if (value < 0) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- int newints = GetArrayLength(value, BitsPerInt32);
- if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length) {
- // grow or shrink (if wasting more than _ShrinkThreshold ints)
- int[] newarray = new int[newints];
- Array.Copy(m_array, newarray, newints > m_array.Length ? m_array.Length : newints);
- m_array = newarray;
- }
-
- if (value > m_length) {
- // clear high bit values in the last int
- int last = GetArrayLength(m_length, BitsPerInt32) - 1;
- int bits = m_length % 32;
- if (bits > 0) {
- m_array[last] &= (1 << bits) - 1;
- }
-
- // clear remaining int values
- Array.Clear(m_array, last + 1, newints - last - 1);
- }
-
- m_length = value;
- _version++;
- }
- }
-
- // ICollection implementation
- public void CopyTo(Array array, int index)
- {
- if (array == null)
- throw new ArgumentNullException(nameof(array));
-
- if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
-
- if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"), nameof(array));
-
- Contract.EndContractBlock();
-
- if (array is int[])
- {
- Array.Copy(m_array, 0, array, index, GetArrayLength(m_length, BitsPerInt32));
- }
- else if (array is byte[])
- {
- int arrayLength = GetArrayLength(m_length, BitsPerByte);
- if ((array.Length - index) < arrayLength)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
-
- byte [] b = (byte[])array;
- for (int i = 0; i < arrayLength; i++)
- b[index + i] = (byte)((m_array[i/4] >> ((i%4)*8)) & 0x000000FF); // Shift to bring the required byte to LSB, then mask
- }
- else if (array is bool[])
- {
- if (array.Length - index < m_length)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
-
- bool [] b = (bool[])array;
- for (int i = 0;i<m_length;i++)
- b[index + i] = ((m_array[i/32] >> (i%32)) & 0x00000001) != 0;
- }
- else
- throw new ArgumentException(Environment.GetResourceString("Arg_BitArrayTypeUnsupported"), nameof(array));
- }
-
- public int Count
- {
- get
- {
- Contract.Ensures(Contract.Result<int>() >= 0);
-
- return m_length;
- }
- }
-
- public Object Clone()
- {
- Contract.Ensures(Contract.Result<Object>() != null);
- Contract.Ensures(((BitArray)Contract.Result<Object>()).Length == this.Length);
-
- return new BitArray(this);
- }
-
- public Object SyncRoot
- {
- get
- {
- if( _syncRoot == null) {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
- }
- return _syncRoot;
- }
- }
-
- public bool IsReadOnly
- {
- get
- {
- return false;
- }
- }
-
- public bool IsSynchronized
- {
- get
- {
- return false;
- }
- }
-
- public IEnumerator GetEnumerator()
- {
- return new BitArrayEnumeratorSimple(this);
- }
-
- // XPerY=n means that n Xs can be stored in 1 Y.
- private const int BitsPerInt32 = 32;
- private const int BytesPerInt32 = 4;
- private const int BitsPerByte = 8;
-
- /// <summary>
- /// Used for conversion between different representations of bit array.
- /// Returns (n+(div-1))/div, rearranged to avoid arithmetic overflow.
- /// For example, in the bit to int case, the straightforward calc would
- /// be (n+31)/32, but that would cause overflow. So instead it's
- /// rearranged to ((n-1)/32) + 1, with special casing for 0.
- ///
- /// Usage:
- /// GetArrayLength(77, BitsPerInt32): returns how many ints must be
- /// allocated to store 77 bits.
- /// </summary>
- /// <param name="n"></param>
- /// <param name="div">use a conversion constant, e.g. BytesPerInt32 to get
- /// how many ints are required to store n bytes</param>
- /// <returns></returns>
- private static int GetArrayLength(int n, int div) {
- Contract.Assert(div > 0, "GetArrayLength: div arg must be greater than 0");
- return n > 0 ? (((n - 1) / div) + 1) : 0;
- }
-
- [Serializable]
- private class BitArrayEnumeratorSimple : IEnumerator, ICloneable
- {
- private BitArray bitarray;
- private int index;
- private int version;
- private bool currentElement;
-
- internal BitArrayEnumeratorSimple(BitArray bitarray) {
- this.bitarray = bitarray;
- this.index = -1;
- version = bitarray._version;
- }
-
- public Object Clone() {
- return MemberwiseClone();
- }
-
- public virtual bool MoveNext() {
- if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- if (index < (bitarray.Count-1)) {
- index++;
- currentElement = bitarray.Get(index);
- return true;
- }
- else
- index = bitarray.Count;
-
- return false;
- }
-
- public virtual Object Current {
- get {
- if (index == -1)
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- if (index >= bitarray.Count)
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
- return currentElement;
- }
- }
-
- public void Reset() {
- if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- index = -1;
- }
- }
-
- private int[] m_array;
- private int m_length;
- private int _version;
- [NonSerialized]
- private Object _syncRoot;
-
- private const int _ShrinkThreshold = 256;
- }
-
-}
diff --git a/src/mscorlib/src/System/Collections/CollectionBase.cs b/src/mscorlib/src/System/Collections/CollectionBase.cs
index 1bb08af27a..ae0c0d302d 100644
--- a/src/mscorlib/src/System/Collections/CollectionBase.cs
+++ b/src/mscorlib/src/System/Collections/CollectionBase.cs
@@ -62,7 +62,7 @@ namespace System.Collections {
public void RemoveAt(int index) {
if (index < 0 || index >= Count)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
Object temp = InnerList[index];
OnValidate(temp);
@@ -101,13 +101,13 @@ namespace System.Collections {
Object IList.this[int index] {
get {
if (index < 0 || index >= Count)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return InnerList[index];
}
set {
if (index < 0 || index >= Count)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
OnValidate(value);
Object temp = InnerList[index];
@@ -163,7 +163,7 @@ namespace System.Collections {
void IList.Insert(int index, Object value) {
if (index < 0 || index > Count)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
OnValidate(value);
OnInsert(index, value);
@@ -194,7 +194,7 @@ namespace System.Collections {
}
protected virtual void OnValidate(Object value) {
- if (value == null) throw new ArgumentNullException("value");
+ if (value == null) throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
}
diff --git a/src/mscorlib/src/System/Collections/Comparer.cs b/src/mscorlib/src/System/Collections/Comparer.cs
index 11e26252a8..0e3c78b529 100644
--- a/src/mscorlib/src/System/Collections/Comparer.cs
+++ b/src/mscorlib/src/System/Collections/Comparer.cs
@@ -36,7 +36,7 @@ namespace System.Collections {
public Comparer(CultureInfo culture) {
if (culture==null) {
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
}
Contract.EndContractBlock();
m_compareInfo = culture.CompareInfo;
@@ -83,10 +83,9 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Collections/CompatibleComparer.cs b/src/mscorlib/src/System/Collections/CompatibleComparer.cs
index 85e6c3f0f3..e5d3961245 100644
--- a/src/mscorlib/src/System/Collections/CompatibleComparer.cs
+++ b/src/mscorlib/src/System/Collections/CompatibleComparer.cs
@@ -39,7 +39,7 @@ namespace System.Collections {
public int GetHashCode(Object obj) {
if( obj == null) {
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
index d805dc8be7..c1a6f7564c 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
@@ -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
@@ -229,7 +203,7 @@ namespace System.Collections.Concurrent
public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
: this(comparer)
{
- if (collection == null) throw new ArgumentNullException("collection");
+ if (collection == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
InitializeFromCollection(collection);
}
@@ -259,8 +233,8 @@ namespace System.Collections.Concurrent
int concurrencyLevel, IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
: this(concurrencyLevel, DEFAULT_CAPACITY, false, comparer)
{
- if (collection == null) throw new ArgumentNullException("collection");
- if (comparer == null) throw new ArgumentNullException("comparer");
+ if (collection == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
+ if (comparer == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer);
InitializeFromCollection(collection);
}
@@ -270,11 +244,11 @@ namespace System.Collections.Concurrent
TValue dummy;
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
- if (pair.Key == null) throw new ArgumentNullException("key");
+ if (pair.Key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
if (!TryAddInternal(pair.Key, pair.Value, false, false, out dummy))
{
- throw new ArgumentException(GetResource("ConcurrentDictionary_SourceContainsDuplicateKeys"));
+ ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_SourceContainsDuplicateKeys);
}
}
@@ -312,13 +286,13 @@ namespace System.Collections.Concurrent
{
if (concurrencyLevel < 1)
{
- throw new ArgumentOutOfRangeException("concurrencyLevel", GetResource("ConcurrentDictionary_ConcurrencyLevelMustBePositive"));
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.concurrencyLevel, ExceptionResource.ConcurrentDictionary_ConcurrencyLevelMustBePositive);
}
if (capacity < 0)
{
- throw new ArgumentOutOfRangeException("capacity", GetResource("ConcurrentDictionary_CapacityMustNotBeNegative"));
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ConcurrentDictionary_CapacityMustNotBeNegative);
}
- if (comparer == null) throw new ArgumentNullException("comparer");
+ if (comparer == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer);
// The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard
// any buckets.
@@ -358,7 +332,7 @@ namespace System.Collections.Concurrent
/// contains too many elements.</exception>
public bool TryAdd(TKey key, TValue value)
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
TValue dummy;
return TryAddInternal(key, value, false, true, out dummy);
}
@@ -375,7 +349,7 @@ namespace System.Collections.Concurrent
/// (Nothing in Visual Basic).</exception>
public bool ContainsKey(TKey key)
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
TValue throwAwayValue;
return TryGetValue(key, out throwAwayValue);
@@ -395,7 +369,7 @@ namespace System.Collections.Concurrent
/// (Nothing in Visual Basic).</exception>
public bool TryRemove(TKey key, out TValue value)
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
return TryRemoveInternal(key, out value, false, default(TValue));
}
@@ -486,7 +460,7 @@ namespace System.Collections.Concurrent
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
public bool TryGetValue(TKey key, out TValue value)
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
int bucketNo, lockNoUnused;
@@ -531,7 +505,7 @@ namespace System.Collections.Concurrent
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue)
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
IEqualityComparer<TValue> valueComparer = EqualityComparer<TValue>.Default;
@@ -642,8 +616,8 @@ namespace System.Collections.Concurrent
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
- if (array == null) throw new ArgumentNullException("array");
- if (index < 0) throw new ArgumentOutOfRangeException("index", GetResource("ConcurrentDictionary_IndexIsNegative"));
+ if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (index < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ConcurrentDictionary_IndexIsNegative);
int locksAcquired = 0;
try
@@ -659,7 +633,7 @@ namespace System.Collections.Concurrent
if (array.Length - count < index || count < 0) //"count" itself or "count + index" can overflow
{
- throw new ArgumentException(GetResource("ConcurrentDictionary_ArrayNotLargeEnough"));
+ ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_ArrayNotLargeEnough);
}
CopyToPairs(array, index);
@@ -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,23 +827,7 @@ 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]));
@@ -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
@@ -956,13 +894,13 @@ namespace System.Collections.Concurrent
TValue value;
if (!TryGetValue(key, out value))
{
- throw new KeyNotFoundException();
+ ThrowHelper.ThrowKeyNotFoundException();
}
return value;
}
set
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
TValue dummy;
TryAddInternal(key, value, true, true, out dummy);
}
@@ -1026,8 +964,8 @@ namespace System.Collections.Concurrent
/// if the key was not in the dictionary.</returns>
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
- if (key == null) throw new ArgumentNullException("key");
- if (valueFactory == null) throw new ArgumentNullException("valueFactory");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (valueFactory == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.valueFactory);
TValue resultingValue;
if (TryGetValue(key, out resultingValue))
@@ -1052,7 +990,7 @@ namespace System.Collections.Concurrent
/// key is already in the dictionary, or the new value if the key was not in the dictionary.</returns>
public TValue GetOrAdd(TKey key, TValue value)
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
TValue resultingValue;
TryAddInternal(key, value, false, true, out resultingValue);
@@ -1080,9 +1018,9 @@ namespace System.Collections.Concurrent
/// absent) or the result of updateValueFactory (if the key was present).</returns>
public TValue AddOrUpdate(TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
{
- if (key == null) throw new ArgumentNullException("key");
- if (addValueFactory == null) throw new ArgumentNullException("addValueFactory");
- if (updateValueFactory == null) throw new ArgumentNullException("updateValueFactory");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (addValueFactory == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.addValueFactory);
+ if (updateValueFactory == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.updateValueFactory);
TValue newValue, resultingValue;
while (true)
@@ -1127,8 +1065,8 @@ namespace System.Collections.Concurrent
/// absent) or the result of updateValueFactory (if the key was present).</returns>
public TValue AddOrUpdate(TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
{
- if (key == null) throw new ArgumentNullException("key");
- if (updateValueFactory == null) throw new ArgumentNullException("updateValueFactory");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (updateValueFactory == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.updateValueFactory);
TValue newValue, resultingValue;
while (true)
{
@@ -1207,7 +1145,7 @@ namespace System.Collections.Concurrent
{
if (!TryAdd(key, value))
{
- throw new ArgumentException(GetResource("ConcurrentDictionary_KeyAlreadyExisted"));
+ ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_KeyAlreadyExisted);
}
}
@@ -1340,8 +1278,7 @@ namespace System.Collections.Concurrent
/// name="keyValuePair"/> is a null reference (Nothing in Visual Basic).</exception>
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
- if (keyValuePair.Key == null) throw new ArgumentNullException(GetResource("ConcurrentDictionary_ItemKeyIsNull"));
-
+ if (keyValuePair.Key == null) ThrowHelper.ThrowArgumentNullException(ExceptionResource.ConcurrentDictionary_ItemKeyIsNull);
TValue throwAwayValue;
return TryRemoveInternal(keyValuePair.Key, out throwAwayValue, true, keyValuePair.Value);
}
@@ -1387,17 +1324,17 @@ namespace System.Collections.Concurrent
/// </exception>
void IDictionary.Add(object key, object value)
{
- if (key == null) throw new ArgumentNullException("key");
- if (!(key is TKey)) throw new ArgumentException(GetResource("ConcurrentDictionary_TypeOfKeyIncorrect"));
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (!(key is TKey)) ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfKeyIncorrect);
- TValue typedValue;
+ TValue typedValue = default(TValue);
try
{
typedValue = (TValue)value;
}
catch (InvalidCastException)
{
- throw new ArgumentException(GetResource("ConcurrentDictionary_TypeOfValueIncorrect"));
+ ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfValueIncorrect);
}
((IDictionary<TKey, TValue>)this).Add((TKey)key, typedValue);
@@ -1415,7 +1352,7 @@ namespace System.Collections.Concurrent
/// (Nothing in Visual Basic).</exception>
bool IDictionary.Contains(object key)
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
return (key is TKey) && ((ConcurrentDictionary<TKey, TValue>)this).ContainsKey((TKey)key);
}
@@ -1475,7 +1412,7 @@ namespace System.Collections.Concurrent
/// (Nothing in Visual Basic).</exception>
void IDictionary.Remove(object key)
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
TValue throwAwayValue;
if (key is TKey)
@@ -1517,7 +1454,7 @@ namespace System.Collections.Concurrent
{
get
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
TValue value;
if (key is TKey && this.TryGetValue((TKey)key, out value))
@@ -1529,10 +1466,10 @@ namespace System.Collections.Concurrent
}
set
{
- if (key == null) throw new ArgumentNullException("key");
+ if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- if (!(key is TKey)) throw new ArgumentException(GetResource("ConcurrentDictionary_TypeOfKeyIncorrect"));
- if (!(value is TValue)) throw new ArgumentException(GetResource("ConcurrentDictionary_TypeOfValueIncorrect"));
+ if (!(key is TKey)) ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfKeyIncorrect);
+ if (!(value is TValue)) ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfValueIncorrect);
((ConcurrentDictionary<TKey, TValue>)this)[(TKey)key] = (TValue)value;
}
@@ -1563,8 +1500,8 @@ namespace System.Collections.Concurrent
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
void ICollection.CopyTo(Array array, int index)
{
- if (array == null) throw new ArgumentNullException("array");
- if (index < 0) throw new ArgumentOutOfRangeException("index", GetResource("ConcurrentDictionary_IndexIsNegative"));
+ if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (index < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ConcurrentDictionary_IndexIsNegative);
int locksAcquired = 0;
try
@@ -1581,7 +1518,7 @@ namespace System.Collections.Concurrent
if (array.Length - count < index || count < 0) //"count" itself or "count + index" can overflow
{
- throw new ArgumentException(GetResource("ConcurrentDictionary_ArrayNotLargeEnough"));
+ ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_ArrayNotLargeEnough);
}
// To be consistent with the behavior of ICollection.CopyTo() in Dictionary<TKey,TValue>,
@@ -1611,7 +1548,7 @@ namespace System.Collections.Concurrent
return;
}
- throw new ArgumentException(GetResource("ConcurrentDictionary_ArrayIncorrectType"), "array");
+ ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_ArrayIncorrectType, ExceptionArgument.array);
}
finally
{
@@ -1641,7 +1578,8 @@ namespace System.Collections.Concurrent
{
get
{
- throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported"));
+ ThrowHelper.ThrowNotSupportedException(ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported);
+ return default(object);
}
}
@@ -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,19 +1904,7 @@ namespace System.Collections.Concurrent
[Conditional("DEBUG")]
private void Assert(bool condition)
{
- Contract.Assert(condition);
- }
-
- /// <summary>
- /// A helper function to obtain the string for a particular resource key.
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- private string GetResource(string key)
- {
- Assert(key != null);
-
- return Environment.GetResourceString(key);
+ Debug.Assert(condition);
}
/// <summary>
@@ -2050,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
}
}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
index 9164eadad1..7aa5971690 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
@@ -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++;
@@ -103,7 +102,7 @@ namespace System.Collections.Concurrent
{
if (collection == null)
{
- throw new ArgumentNullException("collection");
+ throw new ArgumentNullException(nameof(collection));
}
InitializeFromCollection(collection);
@@ -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;
}
@@ -160,7 +159,7 @@ namespace System.Collections.Concurrent
// Validate arguments.
if (array == null)
{
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
@@ -441,7 +440,7 @@ namespace System.Collections.Concurrent
{
if (array == null)
{
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
@@ -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;
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
index 15d4176cff..c36d96c26c 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
@@ -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>
@@ -101,7 +90,7 @@ namespace System.Collections.Concurrent
{
if (collection == null)
{
- throw new ArgumentNullException("collection");
+ throw new ArgumentNullException(nameof(collection));
}
InitializeFromCollection(collection);
}
@@ -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.
@@ -293,7 +237,7 @@ namespace System.Collections.Concurrent
// Validate arguments.
if (array == null)
{
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
@@ -327,7 +271,7 @@ namespace System.Collections.Concurrent
{
if (array == null)
{
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
@@ -379,7 +323,7 @@ namespace System.Collections.Concurrent
{
if (items == null)
{
- throw new ArgumentNullException("items");
+ throw new ArgumentNullException(nameof(items));
}
PushRange(items, 0, items.Length);
}
@@ -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>
@@ -471,16 +408,16 @@ namespace System.Collections.Concurrent
{
if (items == null)
{
- throw new ArgumentNullException("items");
+ throw new ArgumentNullException(nameof(items));
}
if (count < 0)
{
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ConcurrentStack_PushPopRange_CountOutOfRange"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ConcurrentStack_PushPopRange_CountOutOfRange"));
}
int length = items.Length;
if (startIndex >= length || startIndex < 0)
{
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ConcurrentStack_PushPopRange_StartOutOfRange"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ConcurrentStack_PushPopRange_StartOutOfRange"));
}
if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow
{
@@ -584,7 +521,7 @@ namespace System.Collections.Concurrent
{
if (items == null)
{
- throw new ArgumentNullException("items");
+ throw new ArgumentNullException(nameof(items));
}
return TryPopRange(items, 0, items.Length);
@@ -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;
diff --git a/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs b/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs
index a74f69069a..56be7759c9 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs
@@ -97,7 +97,7 @@ namespace System.Collections.Concurrent
{
if (collection == null)
{
- throw new ArgumentNullException("collection");
+ throw new ArgumentNullException(nameof(collection));
}
m_collection = collection;
diff --git a/src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs b/src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs
index 02263b7f97..33e3c88e9a 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/OrderablePartitioner.cs
@@ -61,7 +61,6 @@ namespace System.Collections.Concurrent
/// </ol>
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public abstract class OrderablePartitioner<TSource> : Partitioner<TSource>
{
/// <summary>
diff --git a/src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs b/src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs
index 3d54c1471b..0192b1942c 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/Partitioner.cs
@@ -44,7 +44,6 @@ namespace System.Collections.Concurrent
/// </ol>
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public abstract class Partitioner<TSource>
{
/// <summary>
diff --git a/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs b/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs
index 2169c6dee7..9b36c053ad 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/PartitionerStatic.cs
@@ -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>
@@ -91,7 +88,7 @@ namespace System.Collections.Concurrent
{
if (list == null)
{
- throw new ArgumentNullException("list");
+ throw new ArgumentNullException(nameof(list));
}
if (loadBalance)
{
@@ -122,7 +119,7 @@ namespace System.Collections.Concurrent
if (array == null)
{
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
}
if (loadBalance)
{
@@ -172,11 +169,11 @@ namespace System.Collections.Concurrent
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if ((partitionerOptions & (~EnumerablePartitionerOptions.NoBuffering)) != 0)
- throw new ArgumentOutOfRangeException("partitionerOptions");
+ throw new ArgumentOutOfRangeException(nameof(partitionerOptions));
return (new DynamicPartitionerForIEnumerable<TSource>(source, partitionerOptions));
}
@@ -194,7 +191,7 @@ namespace System.Collections.Concurrent
// load balancing on a busy system if you make it higher than 1.
int coreOversubscriptionRate = 3;
- if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException("toExclusive");
+ if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive));
long rangeSize = (toExclusive - fromInclusive) /
(PlatformHelper.ProcessorCount * coreOversubscriptionRate);
if (rangeSize == 0) rangeSize = 1;
@@ -212,8 +209,8 @@ namespace System.Collections.Concurrent
/// less than or equal to 0.</exception>
public static OrderablePartitioner<Tuple<long, long>> Create(long fromInclusive, long toExclusive, long rangeSize)
{
- if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException("toExclusive");
- if (rangeSize <= 0) throw new ArgumentOutOfRangeException("rangeSize");
+ if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive));
+ if (rangeSize <= 0) throw new ArgumentOutOfRangeException(nameof(rangeSize));
return Partitioner.Create(CreateRanges(fromInclusive, toExclusive, rangeSize), EnumerablePartitionerOptions.NoBuffering); // chunk one range at a time
}
@@ -251,7 +248,7 @@ namespace System.Collections.Concurrent
// load balancing on a busy system if you make it higher than 1.
int coreOversubscriptionRate = 3;
- if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException("toExclusive");
+ if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive));
int rangeSize = (toExclusive - fromInclusive) /
(PlatformHelper.ProcessorCount * coreOversubscriptionRate);
if (rangeSize == 0) rangeSize = 1;
@@ -269,8 +266,8 @@ namespace System.Collections.Concurrent
/// less than or equal to 0.</exception>
public static OrderablePartitioner<Tuple<int, int>> Create(int fromInclusive, int toExclusive, int rangeSize)
{
- if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException("toExclusive");
- if (rangeSize <= 0) throw new ArgumentOutOfRangeException("rangeSize");
+ if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive));
+ if (rangeSize <= 0) throw new ArgumentOutOfRangeException(nameof(rangeSize));
return Partitioner.Create(CreateRanges(fromInclusive, toExclusive, rangeSize), EnumerablePartitionerOptions.NoBuffering); // chunk one range at a time
}
@@ -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;
}
@@ -517,7 +514,7 @@ namespace System.Collections.Concurrent
{
if (partitionCount <= 0)
{
- throw new ArgumentOutOfRangeException("partitionCount");
+ throw new ArgumentOutOfRangeException(nameof(partitionCount));
}
IEnumerator<KeyValuePair<long, TSource>>[] partitions
= new IEnumerator<KeyValuePair<long, TSource>>[partitionCount];
@@ -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]);
}
}
@@ -1053,7 +1050,7 @@ namespace System.Collections.Concurrent
{
if (partitionCount <= 0)
{
- throw new ArgumentOutOfRangeException("partitionCount");
+ throw new ArgumentOutOfRangeException(nameof(partitionCount));
}
IEnumerator<KeyValuePair<long, TSource>>[] partitions
= new IEnumerator<KeyValuePair<long, TSource>>[partitionCount];
@@ -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]);
}
@@ -1417,7 +1414,7 @@ namespace System.Collections.Concurrent
{
if (partitionCount <= 0)
{
- throw new ArgumentOutOfRangeException("partitionCount");
+ throw new ArgumentOutOfRangeException(nameof(partitionCount));
}
int quotient, remainder;
@@ -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
-
}
}
diff --git a/src/mscorlib/src/System/Collections/DictionaryEntry.cs b/src/mscorlib/src/System/Collections/DictionaryEntry.cs
index fc1d57fe55..3ee392bb0d 100644
--- a/src/mscorlib/src/System/Collections/DictionaryEntry.cs
+++ b/src/mscorlib/src/System/Collections/DictionaryEntry.cs
@@ -51,5 +51,12 @@ namespace System.Collections {
_value = value;
}
}
+
+ // BLOCKED (do not add now): [EditorBrowsable(EditorBrowsableState.Never)]
+ public void Deconstruct(out object key, out object value)
+ {
+ key = Key;
+ value = Value;
+ }
}
}
diff --git a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
index 6e28493ef8..a610fce016 100644
--- a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
+++ b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
@@ -36,16 +36,16 @@ namespace System.Collections {
public void CopyTo(Array array, int index) {
if (array==null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ( array.Length - index < this.Count )
- throw new ArgumentException( Environment.GetResourceString("ArgumentOutOfRange_Index"), "index");
+ throw new ArgumentException( Environment.GetResourceString("ArgumentOutOfRange_Index"), nameof(index));
Contract.EndContractBlock();
// the actual copy is a NOP
@@ -74,21 +74,21 @@ namespace System.Collections {
public Object this[Object key] {
get {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
return null;
}
set {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "key");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key));
if( (value != null) && (!value.GetType().IsSerializable ) )
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
Contract.EndContractBlock();
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
@@ -113,14 +113,14 @@ namespace System.Collections {
public void Add(Object key, Object value) {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "key" );
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key) );
if( (value != null) && (!value.GetType().IsSerializable) )
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
Contract.EndContractBlock();
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
diff --git a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
index b2fed9d78f..298ac3e177 100644
--- a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
+++ b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
@@ -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;
@@ -49,16 +50,7 @@ namespace System.Collections.Generic
}
internal static void ThrowOrIgnoreBadComparer(Object comparer) {
- // This is hit when an invarant of QuickSort is violated due to a bad IComparer implementation (for
- // example, imagine an IComparer that returns 0 when items are equal but -1 all other times).
- //
- // We could have thrown this exception on v4, but due to changes in v4.5 around how we partition arrays
- // there are different sets of input where we would throw this exception. In order to reduce overall risk from
- // an app compat persective, we're changing to never throw on v4. Instead, we'll return with a partially
- // sorted array.
- if(BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) {
- throw new ArgumentException(Environment.GetResourceString("Arg_BogusIComparer", comparer));
- }
+ throw new ArgumentException(Environment.GetResourceString("Arg_BogusIComparer", comparer));
}
}
@@ -81,7 +73,6 @@ namespace System.Collections.Generic
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
private static IArraySortHelper<T> CreateArraySortHelper()
{
if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
@@ -99,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.
@@ -111,22 +102,7 @@ namespace System.Collections.Generic
comparer = Comparer<T>.Default;
}
-#if FEATURE_CORECLR
- // Since QuickSort and IntrospectiveSort produce different sorting sequence for equal keys the upgrade
- // to IntrospectiveSort was quirked. However since the phone builds always shipped with the new sort aka
- // IntrospectiveSort and we would want to continue using this sort moving forward CoreCLR always uses the new sort.
-
- IntrospectiveSort(keys, index, length, comparer);
-#else
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
- {
- IntrospectiveSort(keys, index, length, comparer);
- }
- else
- {
- DepthLimitedQuickSort(keys, index, length + index - 1, comparer, IntrospectiveSortUtilities.QuickSortDepthThreshold);
- }
-#endif
+ IntrospectiveSort(keys, index, length, comparer.Compare);
}
catch (IndexOutOfRangeException)
{
@@ -157,6 +133,27 @@ namespace System.Collections.Generic
#endregion
+ internal static void Sort(T[] keys, int index, int length, Comparison<T> comparer)
+ {
+ 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
+ {
+ IntrospectiveSort(keys, index, length, comparer);
+ }
+ catch (IndexOutOfRangeException)
+ {
+ IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
+ }
+ catch (Exception e)
+ {
+ throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed"), e);
+ }
+ }
+
internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
Contract.Requires(array != null, "Check the arguments in the caller!");
@@ -183,11 +180,11 @@ namespace System.Collections.Generic
return ~lo;
}
- private static void SwapIfGreater(T[] keys, IComparer<T> comparer, int a, int b)
+ private static void SwapIfGreater(T[] keys, Comparison<T> comparer, int a, int b)
{
if (a != b)
{
- if (comparer.Compare(keys[a], keys[b]) > 0)
+ if (comparer(keys[a], keys[b]) > 0)
{
T key = keys[a];
keys[a] = keys[b];
@@ -198,7 +195,7 @@ namespace System.Collections.Generic
private static void Swap(T[] a, int i, int j)
{
- if(i != j)
+ if (i != j)
{
T t = a[i];
a[i] = a[j];
@@ -206,63 +203,7 @@ namespace System.Collections.Generic
}
}
- internal static void DepthLimitedQuickSort(T[] keys, int left, int right, IComparer<T> comparer, int depthLimit)
- {
- do
- {
- if (depthLimit == 0)
- {
- Heapsort(keys, left, right, comparer);
- return;
- }
-
- int i = left;
- int j = right;
-
- // pre-sort the low, middle (pivot), and high values in place.
- // this improves performance in the face of already sorted data, or
- // data that is made up of multiple sorted runs appended together.
- int middle = i + ((j - i) >> 1);
- SwapIfGreater(keys, comparer, i, middle); // swap the low with the mid point
- SwapIfGreater(keys, comparer, i, j); // swap the low with the high
- SwapIfGreater(keys, comparer, middle, j); // swap the middle with the high
-
- T x = keys[middle];
- do
- {
- while (comparer.Compare(keys[i], x) < 0) i++;
- while (comparer.Compare(x, keys[j]) < 0) j--;
- Contract.Assert(i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?");
- if (i > j) break;
- if (i < j)
- {
- T key = keys[i];
- keys[i] = keys[j];
- keys[j] = key;
- }
- i++;
- j--;
- } while (i <= j);
-
- // The next iteration of the while loop is to "recursively" sort the larger half of the array and the
- // following calls recursively sort the smaller half. So we subtract one from depthLimit here so
- // both sorts see the new value.
- depthLimit--;
-
- if (j - left <= right - i)
- {
- if (left < j) DepthLimitedQuickSort(keys, left, j, comparer, depthLimit);
- left = i;
- }
- else
- {
- if (i < right) DepthLimitedQuickSort(keys, i, right, comparer, depthLimit);
- right = j;
- }
- } while (left < right);
- }
-
- internal static void IntrospectiveSort(T[] keys, int left, int length, IComparer<T> comparer)
+ internal static void IntrospectiveSort(T[] keys, int left, int length, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
@@ -277,7 +218,7 @@ namespace System.Collections.Generic
IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2(keys.Length), comparer);
}
- private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, IComparer<T> comparer)
+ private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
@@ -324,7 +265,7 @@ namespace System.Collections.Generic
}
}
- private static int PickPivotAndPartition(T[] keys, int lo, int hi, IComparer<T> comparer)
+ private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
@@ -347,8 +288,8 @@ namespace System.Collections.Generic
while (left < right)
{
- while (comparer.Compare(keys[++left], pivot) < 0) ;
- while (comparer.Compare(pivot, keys[--right]) < 0) ;
+ while (comparer(keys[++left], pivot) < 0) ;
+ while (comparer(pivot, keys[--right]) < 0) ;
if (left >= right)
break;
@@ -361,7 +302,7 @@ namespace System.Collections.Generic
return left;
}
- private static void Heapsort(T[] keys, int lo, int hi, IComparer<T> comparer)
+ private static void Heapsort(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
@@ -381,7 +322,7 @@ namespace System.Collections.Generic
}
}
- private static void DownHeap(T[] keys, int i, int n, int lo, IComparer<T> comparer)
+ private static void DownHeap(T[] keys, int i, int n, int lo, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
@@ -393,11 +334,11 @@ namespace System.Collections.Generic
while (i <= n / 2)
{
child = 2 * i;
- if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0)
+ if (child < n && comparer(keys[lo + child - 1], keys[lo + child]) < 0)
{
child++;
}
- if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
+ if (!(comparer(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
i = child;
@@ -405,7 +346,7 @@ namespace System.Collections.Generic
keys[lo + i - 1] = d;
}
- private static void InsertionSort(T[] keys, int lo, int hi, IComparer<T> comparer)
+ private static void InsertionSort(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(lo >= 0);
@@ -418,7 +359,7 @@ namespace System.Collections.Generic
{
j = i;
t = keys[i + 1];
- while (j >= lo && comparer.Compare(t, keys[j]) < 0)
+ while (j >= lo && comparer(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
j--;
@@ -439,49 +380,18 @@ 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
{
- if (comparer == null || comparer == Comparer<T>.Default) {
-
-#if FEATURE_CORECLR
- // Since QuickSort and IntrospectiveSort produce different sorting sequence for equal keys the upgrade
- // to IntrospectiveSort was quirked. However since the phone builds always shipped with the new sort aka
- // IntrospectiveSort and we would want to continue using this sort moving forward CoreCLR always uses the new sort.
-
+ if (comparer == null || comparer == Comparer<T>.Default)
+ {
IntrospectiveSort(keys, index, length);
-#else
- // call the faster version of our sort algorithm if the user doesn't provide a comparer
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
- {
- IntrospectiveSort(keys, index, length);
- }
- else
- {
- DepthLimitedQuickSort(keys, index, length + index - 1, IntrospectiveSortUtilities.QuickSortDepthThreshold);
- }
-#endif
}
else
{
-#if FEATURE_CORECLR
- // Since QuickSort and IntrospectiveSort produce different sorting sequence for equal keys the upgrade
- // to IntrospectiveSort was quirked. However since the phone builds always shipped with the new sort aka
- // IntrospectiveSort and we would want to continue using this sort moving forward CoreCLR always uses the new sort.
-
- ArraySortHelper<T>.IntrospectiveSort(keys, index, length, comparer);
-#else
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
- {
- ArraySortHelper<T>.IntrospectiveSort(keys, index, length, comparer);
- }
- else
- {
- ArraySortHelper<T>.DepthLimitedQuickSort(keys, index, length + index - 1, comparer, IntrospectiveSortUtilities.QuickSortDepthThreshold);
- }
-#endif
+ ArraySortHelper<T>.IntrospectiveSort(keys, index, length, comparer.Compare);
}
}
catch (IndexOutOfRangeException)
@@ -496,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
{
@@ -583,78 +493,6 @@ namespace System.Collections.Generic
}
}
- private static void DepthLimitedQuickSort(T[] keys, int left, int right, int depthLimit)
- {
- Contract.Requires(keys != null);
- Contract.Requires(0 <= left && left < keys.Length);
- Contract.Requires(0 <= right && right < keys.Length);
-
- // The code in this function looks very similar to QuickSort in ArraySortHelper<T> class.
- // The difference is that T is constrainted to IComparable<T> here.
- // So the IL code will be different. This function is faster than the one in ArraySortHelper<T>.
-
- do
- {
- if (depthLimit == 0)
- {
- Heapsort(keys, left, right);
- return;
- }
-
- int i = left;
- int j = right;
-
- // pre-sort the low, middle (pivot), and high values in place.
- // this improves performance in the face of already sorted data, or
- // data that is made up of multiple sorted runs appended together.
- int middle = i + ((j - i) >> 1);
- SwapIfGreaterWithItems(keys, i, middle); // swap the low with the mid point
- SwapIfGreaterWithItems(keys, i, j); // swap the low with the high
- SwapIfGreaterWithItems(keys, middle, j); // swap the middle with the high
-
- T x = keys[middle];
- do
- {
- if (x == null)
- {
- // if x null, the loop to find two elements to be switched can be reduced.
- while (keys[j] != null) j--;
- }
- else
- {
- while (x.CompareTo(keys[i]) > 0) i++;
- while (x.CompareTo(keys[j]) < 0) j--;
- }
- Contract.Assert(i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?");
- if (i > j) break;
- if (i < j)
- {
- T key = keys[i];
- keys[i] = keys[j];
- keys[j] = key;
- }
- i++;
- j--;
- } while (i <= j);
-
- // The next iteration of the while loop is to "recursively" sort the larger half of the array and the
- // following calls recursively sort the smaller half. So we subtract one from depthLimit here so
- // both sorts see the new value.
- depthLimit--;
-
- if (j - left <= right - i)
- {
- if (left < j) DepthLimitedQuickSort(keys, left, j, depthLimit);
- left = i;
- }
- else
- {
- if (i < right) DepthLimitedQuickSort(keys, i, right, depthLimit);
- right = j;
- }
- } while (left < right);
- }
-
internal static void IntrospectiveSort(T[] keys, int left, int length)
{
Contract.Requires(keys != null);
@@ -824,7 +662,7 @@ namespace System.Collections.Generic
}
}
- #endregion
+#endregion
#region ArraySortHelper for paired key and value arrays
@@ -851,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)))
@@ -867,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.
@@ -879,22 +716,7 @@ namespace System.Collections.Generic
comparer = Comparer<TKey>.Default;
}
-#if FEATURE_CORECLR
- // Since QuickSort and IntrospectiveSort produce different sorting sequence for equal keys the upgrade
- // to IntrospectiveSort was quirked. However since the phone builds always shipped with the new sort aka
- // IntrospectiveSort and we would want to continue using this sort moving forward CoreCLR always uses the new sort.
-
IntrospectiveSort(keys, values, index, length, comparer);
-#else
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
- {
- IntrospectiveSort(keys, values, index, length, comparer);
- }
- else
- {
- DepthLimitedQuickSort(keys, values, index, length + index - 1, comparer, IntrospectiveSortUtilities.QuickSortDepthThreshold);
- }
-#endif
}
catch (IndexOutOfRangeException)
{
@@ -947,68 +769,6 @@ namespace System.Collections.Generic
}
}
- internal static void DepthLimitedQuickSort(TKey[] keys, TValue[] values, int left, int right, IComparer<TKey> comparer, int depthLimit)
- {
- do
- {
- if (depthLimit == 0)
- {
- Heapsort(keys, values, left, right, comparer);
- return;
- }
-
- int i = left;
- int j = right;
-
- // pre-sort the low, middle (pivot), and high values in place.
- // this improves performance in the face of already sorted data, or
- // data that is made up of multiple sorted runs appended together.
- int middle = i + ((j - i) >> 1);
- SwapIfGreaterWithItems(keys, values, comparer, i, middle); // swap the low with the mid point
- SwapIfGreaterWithItems(keys, values, comparer, i, j); // swap the low with the high
- SwapIfGreaterWithItems(keys, values, comparer, middle, j); // swap the middle with the high
-
- TKey x = keys[middle];
- do
- {
- while (comparer.Compare(keys[i], x) < 0) i++;
- while (comparer.Compare(x, keys[j]) < 0) j--;
- Contract.Assert(i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?");
- if (i > j) break;
- if (i < j)
- {
- TKey key = keys[i];
- keys[i] = keys[j];
- keys[j] = key;
- if (values != null)
- {
- TValue value = values[i];
- values[i] = values[j];
- values[j] = value;
- }
- }
- i++;
- j--;
- } while (i <= j);
-
- // The next iteration of the while loop is to "recursively" sort the larger half of the array and the
- // following calls recursively sort the smaller half. So we subtract one from depthLimit here so
- // both sorts see the new value.
- depthLimit--;
-
- if (j - left <= right - i)
- {
- if (left < j) DepthLimitedQuickSort(keys, values, left, j, comparer, depthLimit);
- left = i;
- }
- else
- {
- if (i < right) DepthLimitedQuickSort(keys, values, i, right, comparer, depthLimit);
- right = j;
- }
- } while (left < right);
- }
-
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
@@ -1199,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.
@@ -1208,44 +968,12 @@ namespace System.Collections.Generic
{
if (comparer == null || comparer == Comparer<TKey>.Default)
{
-#if FEATURE_CORECLR
- // Since QuickSort and IntrospectiveSort produce different sorting sequence for equal keys the upgrade
- // to IntrospectiveSort was quirked. However since the phone builds always shipped with the new sort aka
- // IntrospectiveSort and we would want to continue using this sort moving forward CoreCLR always uses the new sort.
-
IntrospectiveSort(keys, values, index, length);
-#else
- // call the faster version of our sort algorithm if the user doesn't provide a comparer
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
- {
- IntrospectiveSort(keys, values, index, length);
- }
- else
- {
- DepthLimitedQuickSort(keys, values, index, length + index - 1, IntrospectiveSortUtilities.QuickSortDepthThreshold);
- }
-#endif
}
else
{
-#if FEATURE_CORECLR
- // Since QuickSort and IntrospectiveSort produce different sorting sequence for equal keys the upgrade
- // to IntrospectiveSort was quirked. However since the phone builds always shipped with the new sort aka
- // IntrospectiveSort and we would want to continue using this sort moving forward CoreCLR always uses the new sort.
-
ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, index, length, comparer);
-#else
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
- {
- ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, index, length, comparer);
- }
- else
- {
- ArraySortHelper<TKey, TValue>.DepthLimitedQuickSort(keys, values, index, length + index - 1, comparer, IntrospectiveSortUtilities.QuickSortDepthThreshold);
- }
-#endif
}
-
}
catch (IndexOutOfRangeException)
{
@@ -1292,80 +1020,6 @@ namespace System.Collections.Generic
}
}
- private static void DepthLimitedQuickSort(TKey[] keys, TValue[] values, int left, int right, int depthLimit)
- {
- // The code in this function looks very similar to QuickSort in ArraySortHelper<T> class.
- // The difference is that T is constrainted to IComparable<T> here.
- // So the IL code will be different. This function is faster than the one in ArraySortHelper<T>.
-
- do
- {
- if (depthLimit == 0)
- {
- Heapsort(keys, values, left, right);
- return;
- }
-
- int i = left;
- int j = right;
-
- // pre-sort the low, middle (pivot), and high values in place.
- // this improves performance in the face of already sorted data, or
- // data that is made up of multiple sorted runs appended together.
- int middle = i + ((j - i) >> 1);
- SwapIfGreaterWithItems(keys, values, i, middle); // swap the low with the mid point
- SwapIfGreaterWithItems(keys, values, i, j); // swap the low with the high
- SwapIfGreaterWithItems(keys, values, middle, j); // swap the middle with the high
-
- TKey x = keys[middle];
- do
- {
- if (x == null)
- {
- // if x null, the loop to find two elements to be switched can be reduced.
- while (keys[j] != null) j--;
- }
- else
- {
- while (x.CompareTo(keys[i]) > 0) i++;
- while (x.CompareTo(keys[j]) < 0) j--;
- }
- Contract.Assert(i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?");
- if (i > j) break;
- if (i < j)
- {
- TKey key = keys[i];
- keys[i] = keys[j];
- keys[j] = key;
- if (values != null)
- {
- TValue value = values[i];
- values[i] = values[j];
- values[j] = value;
- }
- }
- i++;
- j--;
- } while (i <= j);
-
- // The next iteration of the while loop is to "recursively" sort the larger half of the array and the
- // following calls recursively sort the smaller half. So we subtract one from depthLimit here so
- // both sorts see the new value.
- depthLimit--;
-
- if (j - left <= right - i)
- {
- if (left < j) DepthLimitedQuickSort(keys, values, left, j, depthLimit);
- left = i;
- }
- else
- {
- if (i < right) DepthLimitedQuickSort(keys, values, i, right, depthLimit);
- right = j;
- }
- } while (left < right);
- }
-
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length)
{
Contract.Requires(keys != null);
@@ -1554,5 +1208,3 @@ namespace System.Collections.Generic
#endregion
}
-
-
diff --git a/src/mscorlib/src/System/Collections/Generic/Comparer.cs b/src/mscorlib/src/System/Collections/Generic/Comparer.cs
index 9f1a8bff6f..4f06b0af69 100644
--- a/src/mscorlib/src/System/Collections/Generic/Comparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Comparer.cs
@@ -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;
@@ -33,7 +34,7 @@ namespace System.Collections.Generic
Contract.Ensures(Contract.Result<Comparer<T>>() != null);
if (comparison == null)
- throw new ArgumentNullException("comparison");
+ throw new ArgumentNullException(nameof(comparison));
return new ComparisonComparer<T>(comparison);
}
@@ -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;
@@ -139,7 +139,7 @@ namespace System.Collections.Generic
[Serializable]
internal sealed class NullableComparer<T> : Comparer<T?> where T : struct, IComparable<T>
{
- public override int Compare(Nullable<T> x, Nullable<T> y) {
+ public override int Compare(T? x, T? y) {
if (x.HasValue) {
if (y.HasValue) return x.value.CompareTo(y.value);
return 1;
@@ -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>));
diff --git a/src/mscorlib/src/System/Collections/Generic/DebugView.cs b/src/mscorlib/src/System/Collections/Generic/DebugView.cs
index 57b91eff51..d0711e551e 100644
--- a/src/mscorlib/src/System/Collections/Generic/DebugView.cs
+++ b/src/mscorlib/src/System/Collections/Generic/DebugView.cs
@@ -110,7 +110,7 @@ namespace System.Collections.Generic {
public Mscorlib_KeyedCollectionDebugView(KeyedCollection<K, T> keyedCollection) {
if (keyedCollection == null) {
- throw new ArgumentNullException("keyedCollection");
+ throw new ArgumentNullException(nameof(keyedCollection));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
index 9cbfff5a57..c2b2da9ad2 100644
--- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
@@ -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) {}
@@ -129,6 +129,21 @@ namespace System.Collections.Generic {
}
}
+ public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection):
+ this(collection, null) { }
+
+ public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer):
+ this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer)
+ {
+ if (collection == null) {
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
+ }
+
+ foreach (KeyValuePair<TKey, TValue> pair in collection) {
+ Add(pair.Key, pair.Value);
+ }
+ }
+
protected Dictionary(SerializationInfo info, StreamingContext context) {
//We can't do anything with the keys and values until the entire graph has been deserialized
//and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
@@ -263,7 +278,7 @@ namespace System.Collections.Generic {
}
if (index < 0 || index > array.Length ) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count) {
@@ -287,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);
@@ -347,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++;
@@ -386,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
@@ -398,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
}
@@ -459,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];
@@ -523,16 +523,19 @@ namespace System.Collections.Generic {
return false;
}
- // This is a convenience method for the internal callers that were converted from using Hashtable.
- // Many were combining key doesn't exist and key exists but null value (for non-value types) checks.
- // This allows them to continue getting that behavior with minimal code delta. This is basically
- // TryGetValue without the out param
- internal TValue GetValueOrDefault(TKey key) {
+ // Method similar to TryGetValue that returns the value instead of putting it in an out param.
+ public TValue GetValueOrDefault(TKey key) => GetValueOrDefault(key, default(TValue));
+
+ // Method similar to TryGetValue that returns the value instead of putting it in an out param. If the entry
+ // doesn't exist, returns the defaultValue instead.
+ public TValue GetValueOrDefault(TKey key, TValue defaultValue)
+ {
int i = FindEntry(key);
- if (i >= 0) {
+ if (i >= 0)
+ {
return entries[i].value;
}
- return default(TValue);
+ return defaultValue;
}
bool ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly {
@@ -557,7 +560,7 @@ namespace System.Collections.Generic {
}
if (index < 0 || index > array.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count) {
@@ -580,7 +583,7 @@ namespace System.Collections.Generic {
else {
object[] objects = array as object[];
if (objects == null) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try {
@@ -593,7 +596,7 @@ namespace System.Collections.Generic {
}
}
catch(ArrayTypeMismatchException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
@@ -733,7 +736,7 @@ namespace System.Collections.Generic {
public bool MoveNext() {
if (version != dictionary.version) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
@@ -762,7 +765,7 @@ namespace System.Collections.Generic {
object IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
if (getEnumeratorRetType == DictEntry) {
@@ -775,7 +778,7 @@ namespace System.Collections.Generic {
void IEnumerator.Reset() {
if (version != dictionary.version) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
@@ -785,7 +788,7 @@ namespace System.Collections.Generic {
DictionaryEntry IDictionaryEnumerator.Entry {
get {
if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return new DictionaryEntry(current.Key, current.Value);
@@ -795,7 +798,7 @@ namespace System.Collections.Generic {
object IDictionaryEnumerator.Key {
get {
if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return current.Key;
@@ -805,7 +808,7 @@ namespace System.Collections.Generic {
object IDictionaryEnumerator.Value {
get {
if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return current.Value;
@@ -837,7 +840,7 @@ namespace System.Collections.Generic {
}
if (index < 0 || index > array.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count) {
@@ -898,7 +901,7 @@ namespace System.Collections.Generic {
}
if (index < 0 || index > array.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count) {
@@ -912,7 +915,7 @@ namespace System.Collections.Generic {
else {
object[] objects = array as object[];
if (objects == null) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = dictionary.count;
@@ -923,7 +926,7 @@ namespace System.Collections.Generic {
}
}
catch(ArrayTypeMismatchException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
@@ -956,7 +959,7 @@ namespace System.Collections.Generic {
public bool MoveNext() {
if (version != dictionary.version) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)index < (uint)dictionary.count) {
@@ -982,7 +985,7 @@ namespace System.Collections.Generic {
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return currentKey;
@@ -991,7 +994,7 @@ namespace System.Collections.Generic {
void System.Collections.IEnumerator.Reset() {
if (version != dictionary.version) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
@@ -1024,7 +1027,7 @@ namespace System.Collections.Generic {
}
if (index < 0 || index > array.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count) {
@@ -1085,7 +1088,7 @@ namespace System.Collections.Generic {
}
if (index < 0 || index > array.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
@@ -1098,7 +1101,7 @@ namespace System.Collections.Generic {
else {
object[] objects = array as object[];
if (objects == null) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = dictionary.count;
@@ -1109,7 +1112,7 @@ namespace System.Collections.Generic {
}
}
catch(ArrayTypeMismatchException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
@@ -1142,7 +1145,7 @@ namespace System.Collections.Generic {
public bool MoveNext() {
if (version != dictionary.version) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)index < (uint)dictionary.count) {
@@ -1167,7 +1170,7 @@ namespace System.Collections.Generic {
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return currentValue;
@@ -1176,7 +1179,7 @@ namespace System.Collections.Generic {
void System.Collections.IEnumerator.Reset() {
if (version != dictionary.version) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
currentValue = default(TValue);
diff --git a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
index b845d64fed..3731114119 100644
--- a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
@@ -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);
@@ -144,10 +143,7 @@ namespace System.Collections.Generic
}
[Pure]
- public override int GetHashCode(T obj) {
- if (obj == null) return 0;
- return obj.GetHashCode();
- }
+ public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0;
internal override int IndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex + count;
@@ -179,22 +175,21 @@ namespace System.Collections.Generic
return -1;
}
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- GenericEqualityComparer<T> comparer = obj as GenericEqualityComparer<T>;
- return comparer != null;
- }
+ // Equals method for the comparer itself.
+ // If in the future this type is made sealed, change the is check to obj != null && GetType() == obj.GetType().
+ public override bool Equals(Object obj) =>
+ obj is GenericEqualityComparer<T>;
- public override int GetHashCode() {
- return this.GetType().Name.GetHashCode();
- }
+ // If in the future this type is made sealed, change typeof(...) to GetType().
+ public override int GetHashCode() =>
+ typeof(GenericEqualityComparer<T>).GetHashCode();
}
[Serializable]
- internal class NullableEqualityComparer<T> : EqualityComparer<Nullable<T>> where T : struct, IEquatable<T>
+ internal sealed class NullableEqualityComparer<T> : EqualityComparer<T?> where T : struct, IEquatable<T>
{
[Pure]
- public override bool Equals(Nullable<T> x, Nullable<T> y) {
+ public override bool Equals(T? x, T? y) {
if (x.HasValue) {
if (y.HasValue) return x.value.Equals(y.value);
return false;
@@ -204,11 +199,9 @@ namespace System.Collections.Generic
}
[Pure]
- public override int GetHashCode(Nullable<T> obj) {
- return obj.GetHashCode();
- }
+ public override int GetHashCode(T? obj) => obj.GetHashCode();
- internal override int IndexOf(Nullable<T>[] array, Nullable<T> value, int startIndex, int count) {
+ internal override int IndexOf(T?[] array, T? value, int startIndex, int count) {
int endIndex = startIndex + count;
if (!value.HasValue) {
for (int i = startIndex; i < endIndex; i++) {
@@ -223,7 +216,7 @@ namespace System.Collections.Generic
return -1;
}
- internal override int LastIndexOf(Nullable<T>[] array, Nullable<T> value, int startIndex, int count) {
+ internal override int LastIndexOf(T?[] array, T? value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
if (!value.HasValue) {
for (int i = startIndex; i >= endIndex; i--) {
@@ -238,19 +231,16 @@ namespace System.Collections.Generic
return -1;
}
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- NullableEqualityComparer<T> comparer = obj as NullableEqualityComparer<T>;
- return comparer != null;
- }
+ // Equals method for the comparer itself.
+ public override bool Equals(Object obj) =>
+ obj != null && GetType() == obj.GetType();
- public override int GetHashCode() {
- return this.GetType().Name.GetHashCode();
- }
+ public override int GetHashCode() =>
+ GetType().GetHashCode();
}
[Serializable]
- internal class ObjectEqualityComparer<T>: EqualityComparer<T>
+ internal sealed class ObjectEqualityComparer<T>: EqualityComparer<T>
{
[Pure]
public override bool Equals(T x, T y) {
@@ -263,10 +253,7 @@ namespace System.Collections.Generic
}
[Pure]
- public override int GetHashCode(T obj) {
- if (obj == null) return 0;
- return obj.GetHashCode();
- }
+ public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0;
internal override int IndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex + count;
@@ -298,25 +285,21 @@ namespace System.Collections.Generic
return -1;
}
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- ObjectEqualityComparer<T> comparer = obj as ObjectEqualityComparer<T>;
- return comparer != null;
- }
+ // Equals method for the comparer itself.
+ public override bool Equals(Object obj) =>
+ obj != null && GetType() == obj.GetType();
- public override int GetHashCode() {
- return this.GetType().Name.GetHashCode();
- }
+ public override int GetHashCode() =>
+ 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,>
// We use NonRandomizedStringEqualityComparer as default comparer as it doesnt use the randomized string hashing which
// keep the perofrmance not affected till we hit collision threshold and then we switch to the comparer which is using
// randomized string hashing GenericEqualityComparer<string>
-
+ [Serializable]
internal class NonRandomizedStringEqualityComparer : GenericEqualityComparer<string> {
static IEqualityComparer<string> s_nonRandomizedComparer;
@@ -335,12 +318,11 @@ 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.
[Serializable]
- internal class ByteEqualityComparer: EqualityComparer<byte>
+ internal sealed class ByteEqualityComparer: EqualityComparer<byte>
{
[Pure]
public override bool Equals(byte x, byte y) {
@@ -352,14 +334,13 @@ 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("array");
+ throw new ArgumentNullException(nameof(array));
if (startIndex < 0)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
if (count > array.Length - startIndex)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -377,15 +358,12 @@ namespace System.Collections.Generic
return -1;
}
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- ByteEqualityComparer comparer = obj as ByteEqualityComparer;
- return comparer != null;
- }
+ // Equals method for the comparer itself.
+ public override bool Equals(Object obj) =>
+ obj != null && GetType() == obj.GetType();
- public override int GetHashCode() {
- return this.GetType().Name.GetHashCode();
- }
+ public override int GetHashCode() =>
+ GetType().GetHashCode();
}
[Serializable]
@@ -409,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) {
@@ -417,14 +394,35 @@ namespace System.Collections.Generic
}
}
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- EnumEqualityComparer<T> comparer = obj as EnumEqualityComparer<T>;
- return comparer != null;
+ // Equals method for the comparer itself.
+ public override bool Equals(Object obj) =>
+ obj != null && GetType() == obj.GetType();
+
+ public override int GetHashCode() =>
+ GetType().GetHashCode();
+
+ internal override int IndexOf(T[] array, T value, int startIndex, int count)
+ {
+ int toFind = JitHelpers.UnsafeEnumCast(value);
+ int endIndex = startIndex + count;
+ for (int i = startIndex; i < endIndex; i++)
+ {
+ int current = JitHelpers.UnsafeEnumCast(array[i]);
+ if (toFind == current) return i;
+ }
+ return -1;
}
- public override int GetHashCode() {
- return this.GetType().Name.GetHashCode();
+ internal override int LastIndexOf(T[] array, T value, int startIndex, int count)
+ {
+ int toFind = JitHelpers.UnsafeEnumCast(value);
+ int endIndex = startIndex - count + 1;
+ for (int i = startIndex; i >= endIndex; i--)
+ {
+ int current = JitHelpers.UnsafeEnumCast(array[i]);
+ if (toFind == current) return i;
+ }
+ return -1;
}
}
@@ -474,28 +472,48 @@ namespace System.Collections.Generic
return x_final.GetHashCode();
}
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- LongEnumEqualityComparer<T> comparer = obj as LongEnumEqualityComparer<T>;
- return comparer != null;
- }
+ // Equals method for the comparer itself.
+ public override bool Equals(Object obj) =>
+ obj != null && GetType() == obj.GetType();
- public override int GetHashCode() {
- return this.GetType().Name.GetHashCode();
- }
+ public override int GetHashCode() =>
+ GetType().GetHashCode();
public LongEnumEqualityComparer() { }
// 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
// to allow for roundtrip between 4.0 and 4.5.
info.SetType(typeof(ObjectEqualityComparer<T>));
}
+
+ internal override int IndexOf(T[] array, T value, int startIndex, int count)
+ {
+ long toFind = JitHelpers.UnsafeEnumCastLong(value);
+ int endIndex = startIndex + count;
+ for (int i = startIndex; i < endIndex; i++)
+ {
+ long current = JitHelpers.UnsafeEnumCastLong(array[i]);
+ if (toFind == current) return i;
+ }
+ return -1;
+ }
+
+ internal override int LastIndexOf(T[] array, T value, int startIndex, int count)
+ {
+ long toFind = JitHelpers.UnsafeEnumCastLong(value);
+ int endIndex = startIndex - count + 1;
+ for (int i = startIndex; i >= endIndex; i--)
+ {
+ long current = JitHelpers.UnsafeEnumCastLong(array[i]);
+ if (toFind == current) return i;
+ }
+ return -1;
+ }
}
#if FEATURE_RANDOMIZED_STRING_HASHING
@@ -528,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;
@@ -552,7 +568,7 @@ namespace System.Collections.Generic
}
public override int GetHashCode() {
- return (this.GetType().Name.GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
+ return (this.GetType().GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
}
@@ -587,7 +603,6 @@ namespace System.Collections.Generic
}
[Pure]
- [SecuritySafeCritical]
public int GetHashCode(Object obj) {
if(obj == null) return 0;
@@ -604,7 +619,7 @@ namespace System.Collections.Generic
}
public override int GetHashCode() {
- return (this.GetType().Name.GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
+ return (this.GetType().GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
}
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
diff --git a/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs b/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
index 17e1c531f1..ad9f7472aa 100644
--- a/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
+++ b/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
@@ -18,6 +18,16 @@ namespace System.Collections.Generic {
using System;
using System.Text;
+ // Provides the Create factory method for KeyValuePair<TKey, TValue>.
+ public static class KeyValuePair
+ {
+ // Creates a new KeyValuePair<TKey, TValue> from the given values.
+ public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value)
+ {
+ return new KeyValuePair<TKey, TValue>(key, value);
+ }
+ }
+
// A KeyValuePair holds a key and a value from a dictionary.
// It is used by the IEnumerable<T> implementation for both IDictionary<TKey, TValue>
// and IReadOnlyDictionary<TKey, TValue>.
@@ -52,5 +62,12 @@ namespace System.Collections.Generic {
s.Append(']');
return StringBuilderCache.GetStringAndRelease(s);
}
+
+ // BLOCKED (do not add now): [EditorBrowsable(EditorBrowsableState.Never)]
+ public void Deconstruct(out TKey key, out TValue value)
+ {
+ key = Key;
+ value = Value;
+ }
}
}
diff --git a/src/mscorlib/src/System/Collections/Generic/List.cs b/src/mscorlib/src/System/Collections/Generic/List.cs
index ae3356d372..3e2947f5f9 100644
--- a/src/mscorlib/src/System/Collections/Generic/List.cs
+++ b/src/mscorlib/src/System/Collections/Generic/List.cs
@@ -91,14 +91,7 @@ namespace System.Collections.Generic {
else {
_size = 0;
_items = _emptyArray;
- // This enumerable could be empty. Let Add allocate a new array, if needed.
- // Note it will also go to _defaultCapacity first, not 1, then 2, etc.
-
- using(IEnumerator<T> en = collection.GetEnumerator()) {
- while(en.MoveNext()) {
- Add(en.Current);
- }
- }
+ AddEnumerable(collection);
}
}
@@ -274,7 +267,7 @@ namespace System.Collections.Generic {
//
public int BinarySearch(int index, int count, T item, IComparer<T> comparer) {
if (index < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (count < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (_size - index < count)
@@ -369,7 +362,7 @@ namespace System.Collections.Generic {
Array.Copy(_items, 0, array, arrayIndex, _size);
}
catch(ArrayTypeMismatchException){
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
@@ -393,7 +386,7 @@ namespace System.Collections.Generic {
}
// Ensures that the capacity of this list is at least the given minimum
- // value. If the currect capacity of the list is less than min, the
+ // value. If the current capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min) {
@@ -454,11 +447,11 @@ namespace System.Collections.Generic {
public int FindIndex(int startIndex, int count, Predicate<T> match) {
if( (uint)startIndex > (uint)_size ) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (count < 0 || startIndex > _size - count) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
if( match == null) {
@@ -512,19 +505,19 @@ namespace System.Collections.Generic {
if(_size == 0) {
// Special case for 0 length List
if( startIndex != -1) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
else {
// Make sure we're not out of range
if ( (uint)startIndex >= (uint)_size) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
int endIndex = startIndex - count;
@@ -545,14 +538,14 @@ namespace System.Collections.Generic {
int version = _version;
for(int i = 0 ; i < _size; i++) {
- if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) {
+ if (version != _version) {
break;
}
action(_items[i]);
}
- if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ if (version != _version)
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Returns an enumerator for this list with the given
@@ -575,7 +568,7 @@ namespace System.Collections.Generic {
public List<T> GetRange(int index, int count) {
if (index < 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0) {
@@ -628,7 +621,7 @@ namespace System.Collections.Generic {
//
public int IndexOf(T item, int index) {
if (index > _size)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
@@ -646,9 +639,9 @@ namespace System.Collections.Generic {
//
public int IndexOf(T item, int index, int count) {
if (index > _size)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- if (count <0 || index > _size - count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
+ if (count <0 || index > _size - count) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
@@ -698,7 +691,7 @@ namespace System.Collections.Generic {
}
if ((uint)index > (uint)_size) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
Contract.EndContractBlock();
@@ -719,20 +712,24 @@ namespace System.Collections.Generic {
Array.Copy(_items, index+count, _items, index*2, _size-index);
}
else {
- T[] itemsToInsert = new T[count];
- c.CopyTo(itemsToInsert, 0);
- itemsToInsert.CopyTo(_items, index);
+ c.CopyTo(_items, index);
}
_size += count;
}
}
- else {
+ else if (index < _size) {
+ // We're inserting a lazy enumerable. Call Insert on each of the constituent items.
using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Insert(index++, en.Current);
}
}
}
+ else
+ {
+ // We're adding a lazy enumerable because the index is at the end of this list.
+ AddEnumerable(collection);
+ }
_version++;
}
@@ -768,7 +765,7 @@ namespace System.Collections.Generic {
public int LastIndexOf(T item, int index)
{
if (index >= _size)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
+ ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
@@ -786,7 +783,7 @@ namespace System.Collections.Generic {
//
public int LastIndexOf(T item, int index, int count) {
if ((Count != 0) && (index < 0)) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if ((Count !=0) && (count < 0)) {
@@ -885,7 +882,7 @@ namespace System.Collections.Generic {
//
public void RemoveRange(int index, int count) {
if (index < 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0) {
@@ -919,7 +916,7 @@ namespace System.Collections.Generic {
//
public void Reverse(int index, int count) {
if (index < 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0) {
@@ -930,22 +927,7 @@ namespace System.Collections.Generic {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
- // The non-generic Array.Reverse is not used because it does not perform
- // well for non-primitive value types.
- // If/when a generic Array.Reverse<T> becomes available, the below code
- // can be deleted and replaced with a call to Array.Reverse<T>.
- int i = index;
- int j = index + count - 1;
- T[] array = _items;
- while (i < j)
- {
- T temp = array[i];
- array[i] = array[j];
- array[j] = temp;
- i++;
- j--;
- }
-
+ Array.Reverse(_items, index, count);
_version++;
}
@@ -973,7 +955,7 @@ namespace System.Collections.Generic {
//
public void Sort(int index, int count, IComparer<T> comparer) {
if (index < 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0) {
@@ -995,8 +977,7 @@ namespace System.Collections.Generic {
Contract.EndContractBlock();
if( _size > 0) {
- IComparer<T> comparer = Comparer<T>.Create(comparison);
- Array.Sort(_items, 0, _size, comparer);
+ ArraySortHelper<T>.Sort(_items, 0, _size, comparison);
}
}
@@ -1006,12 +987,10 @@ namespace System.Collections.Generic {
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == Count);
-#if FEATURE_CORECLR
if (_size == 0)
{
return _emptyArray;
}
-#endif
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
@@ -1048,6 +1027,31 @@ namespace System.Collections.Generic {
return true;
}
+ private void AddEnumerable(IEnumerable<T> enumerable)
+ {
+ Debug.Assert(enumerable != null);
+ Debug.Assert(!(enumerable is ICollection<T>), "We should have optimized for this beforehand.");
+
+ using (IEnumerator<T> en = enumerable.GetEnumerator())
+ {
+ _version++; // Even if the enumerable has no items, we can update _version.
+
+ while (en.MoveNext())
+ {
+ // Capture Current before doing anything else. If this throws
+ // an exception, we want to make a clean break.
+ T current = en.Current;
+
+ if (_size == _items.Length)
+ {
+ EnsureCapacity(_size + 1);
+ }
+
+ _items[_size++] = current;
+ }
+ }
+ }
+
[Serializable]
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
@@ -1082,7 +1086,7 @@ namespace System.Collections.Generic {
private bool MoveNextRare()
{
if (version != list._version) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = list._size + 1;
@@ -1099,7 +1103,7 @@ namespace System.Collections.Generic {
Object System.Collections.IEnumerator.Current {
get {
if( index == 0 || index == list._size + 1) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return Current;
}
@@ -1107,7 +1111,7 @@ namespace System.Collections.Generic {
void System.Collections.IEnumerator.Reset() {
if (version != list._version) {
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
diff --git a/src/mscorlib/src/System/Collections/Hashtable.cs b/src/mscorlib/src/System/Collections/Hashtable.cs
index 262ccedea6..d4c7d8d673 100644
--- a/src/mscorlib/src/System/Collections/Hashtable.cs
+++ b/src/mscorlib/src/System/Collections/Hashtable.cs
@@ -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.
//
@@ -271,9 +268,9 @@ namespace System.Collections {
//
public Hashtable(int capacity, float loadFactor) {
if (capacity < 0)
- throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (!(loadFactor >= 0.1f && loadFactor <= 1.0f))
- throw new ArgumentOutOfRangeException("loadFactor", Environment.GetResourceString("ArgumentOutOfRange_HashtableLoadFactor", .1, 1.0));
+ throw new ArgumentOutOfRangeException(nameof(loadFactor), Environment.GetResourceString("ArgumentOutOfRange_HashtableLoadFactor", .1, 1.0));
Contract.EndContractBlock();
// Based on perf work, .72 is the optimal load factor for this table.
@@ -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
@@ -375,7 +372,7 @@ namespace System.Collections {
public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer)
: this((d != null ? d.Count : 0), loadFactor, hcp, comparer) {
if (d==null)
- throw new ArgumentNullException("d", Environment.GetResourceString("ArgumentNull_Dictionary"));
+ throw new ArgumentNullException(nameof(d), Environment.GetResourceString("ArgumentNull_Dictionary"));
Contract.EndContractBlock();
IDictionaryEnumerator e = d.GetEnumerator();
@@ -385,7 +382,7 @@ namespace System.Collections {
public Hashtable(IDictionary d, float loadFactor, IEqualityComparer equalityComparer)
: this((d != null ? d.Count : 0), loadFactor, equalityComparer) {
if (d==null)
- throw new ArgumentNullException("d", Environment.GetResourceString("ArgumentNull_Dictionary"));
+ throw new ArgumentNullException(nameof(d), Environment.GetResourceString("ArgumentNull_Dictionary"));
Contract.EndContractBlock();
IDictionaryEnumerator e = d.GetEnumerator();
@@ -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
@@ -501,7 +492,7 @@ namespace System.Collections {
//
public virtual bool ContainsKey(Object key) {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
@@ -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
@@ -590,11 +579,11 @@ namespace System.Collections {
public virtual void CopyTo(Array array, int arrayIndex)
{
if (array == null)
- throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Array"));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - arrayIndex < Count)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
Contract.EndContractBlock();
@@ -643,7 +632,7 @@ namespace System.Collections {
public virtual Object this[Object key] {
get {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
@@ -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;
}
@@ -872,7 +856,7 @@ namespace System.Collections {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private void Insert (Object key, Object nvalue, bool add) {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
if (count >= loadsize) {
@@ -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);
}
@@ -1069,10 +990,10 @@ namespace System.Collections {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public virtual void Remove(Object key) {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ 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,10 +1046,9 @@ 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("table");
+ throw new ArgumentNullException(nameof(table));
Contract.EndContractBlock();
return new SyncHashtable(table);
}
@@ -1143,10 +1057,9 @@ namespace System.Collections {
// The ISerializable Implementation
//
- [System.Security.SecurityCritical]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
// This is imperfect - it only works well if all other writes are
@@ -1302,11 +1215,11 @@ namespace System.Collections {
public virtual void CopyTo(Array array, int arrayIndex) {
if (array==null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (array.Length - arrayIndex < _hashtable.count)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
@@ -1343,11 +1256,11 @@ namespace System.Collections {
public virtual void CopyTo(Array array, int arrayIndex) {
if (array==null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (array.Length - arrayIndex < _hashtable.count)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
@@ -1399,10 +1312,9 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
// Our serialization code hasn't been fully tweaked to be safe
@@ -1461,7 +1373,7 @@ namespace System.Collections {
public override bool ContainsKey(Object key) {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
return _table.ContainsKey(key);
@@ -1630,7 +1542,7 @@ namespace System.Collections {
public HashtableDebugView( Hashtable hashtable) {
if( hashtable == null) {
- throw new ArgumentNullException( "hashtable");
+ throw new ArgumentNullException(nameof(hashtable));
}
Contract.EndContractBlock();
@@ -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;
}
diff --git a/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs b/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
index 944523c475..be5490b194 100644
--- a/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
+++ b/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
@@ -30,7 +30,7 @@ namespace System.Collections {
public Object this[Object key] {
get {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
DictionaryNode node = head;
@@ -45,16 +45,16 @@ namespace System.Collections {
}
set {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
#if FEATURE_SERIALIZATION
if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "key");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key));
if( (value != null) && (!value.GetType().IsSerializable ) )
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
#endif
version++;
@@ -132,16 +132,16 @@ namespace System.Collections {
public void Add(Object key, Object value) {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
#if FEATURE_SERIALIZATION
if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "key" );
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key) );
if( (value != null) && (!value.GetType().IsSerializable) )
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
#endif
version++;
@@ -179,7 +179,7 @@ namespace System.Collections {
public bool Contains(Object key) {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
for (DictionaryNode node = head; node != null; node = node.next) {
@@ -192,16 +192,16 @@ namespace System.Collections {
public void CopyTo(Array array, int index) {
if (array==null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ( array.Length - index < this.Count )
- throw new ArgumentException( Environment.GetResourceString("ArgumentOutOfRange_Index"), "index");
+ throw new ArgumentException( Environment.GetResourceString("ArgumentOutOfRange_Index"), nameof(index));
Contract.EndContractBlock();
for (DictionaryNode node = head; node != null; node = node.next) {
@@ -220,7 +220,7 @@ namespace System.Collections {
public void Remove(Object key) {
if (key == null) {
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
version++;
@@ -328,14 +328,14 @@ namespace System.Collections {
void ICollection.CopyTo(Array array, int index) {
if (array==null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (array.Length - index < list.Count)
- throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Index"), "index");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Index"), nameof(index));
for (DictionaryNode node = list.head; node != null; node = node.next) {
array.SetValue(isKeys ? node.key : node.value, index);
index++;
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs b/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
index 54aa7bb09d..a3804ad7ab 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
@@ -183,7 +183,7 @@ namespace System.Collections.ObjectModel
}
if (index < 0 ) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count) {
@@ -204,7 +204,7 @@ namespace System.Collections.ObjectModel
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
//
@@ -213,7 +213,7 @@ namespace System.Collections.ObjectModel
//
object[] objects = array as object[];
if( objects == null) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = items.Count;
@@ -223,7 +223,7 @@ namespace System.Collections.ObjectModel
}
}
catch(ArrayTypeMismatchException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs b/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
index 7313d71950..b6fe6ded29 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
@@ -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);
}
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
index ec7149e4f5..a0b8b3b459 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
@@ -128,7 +128,7 @@ namespace System.Collections.ObjectModel
}
if (index < 0) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count) {
@@ -149,7 +149,7 @@ namespace System.Collections.ObjectModel
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
//
@@ -158,7 +158,7 @@ namespace System.Collections.ObjectModel
//
object[] objects = array as object[];
if( objects == null) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = list.Count;
@@ -168,7 +168,7 @@ namespace System.Collections.ObjectModel
}
}
catch(ArrayTypeMismatchException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
index 11833c2c1b..5c9e8c44c6 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
@@ -34,7 +34,7 @@ namespace System.Collections.ObjectModel
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary) {
if (dictionary == null) {
- throw new ArgumentNullException("dictionary");
+ throw new ArgumentNullException(nameof(dictionary));
}
Contract.EndContractBlock();
m_dictionary = dictionary;
@@ -240,7 +240,7 @@ namespace System.Collections.ObjectModel
}
if (index < 0 || index > array.Length) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count) {
@@ -261,7 +261,7 @@ namespace System.Collections.ObjectModel
else {
object[] objects = array as object[];
if (objects == null) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try {
@@ -270,7 +270,7 @@ namespace System.Collections.ObjectModel
}
}
catch (ArrayTypeMismatchException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
@@ -596,7 +596,7 @@ namespace System.Collections.ObjectModel
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
//
@@ -605,7 +605,7 @@ namespace System.Collections.ObjectModel
//
object[] objects = array as object[];
if (objects == null) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try {
@@ -614,7 +614,7 @@ namespace System.Collections.ObjectModel
}
}
catch (ArrayTypeMismatchException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
diff --git a/src/mscorlib/src/System/Collections/SortedList.cs b/src/mscorlib/src/System/Collections/SortedList.cs
index 8e3926af01..4a480a2c37 100644
--- a/src/mscorlib/src/System/Collections/SortedList.cs
+++ b/src/mscorlib/src/System/Collections/SortedList.cs
@@ -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
{
@@ -107,7 +105,7 @@ namespace System.Collections {
//
public SortedList(int initialCapacity) {
if (initialCapacity < 0)
- throw new ArgumentOutOfRangeException("initialCapacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(initialCapacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
keys = new Object[initialCapacity];
values = new Object[initialCapacity];
@@ -164,7 +162,7 @@ namespace System.Collections {
public SortedList(IDictionary d, IComparer comparer)
: this(comparer, (d != null ? d.Count : 0)) {
if (d==null)
- throw new ArgumentNullException("d", Environment.GetResourceString("ArgumentNull_Dictionary"));
+ throw new ArgumentNullException(nameof(d), Environment.GetResourceString("ArgumentNull_Dictionary"));
Contract.EndContractBlock();
d.Keys.CopyTo(keys, 0);
d.Values.CopyTo(values, 0);
@@ -176,7 +174,7 @@ namespace System.Collections {
// ArgumentException is thrown if the key is already present in the sorted list.
//
public virtual void Add(Object key, Object value) {
- if (key == null) throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ if (key == null) throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
int i = Array.BinarySearch(keys, 0, _size, key, comparer);
if (i >= 0)
@@ -196,7 +194,7 @@ namespace System.Collections {
}
set {
if (value < Count) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
Contract.EndContractBlock();
@@ -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;
}
@@ -325,11 +323,11 @@ namespace System.Collections {
// Copies the values in this SortedList to an array.
public virtual void CopyTo(Array array, int arrayIndex) {
if (array == null)
- throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Array"));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - arrayIndex < Count)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
Contract.EndContractBlock();
@@ -368,7 +366,7 @@ namespace System.Collections {
//
public virtual Object GetByIndex(int index) {
if (index < 0 || index >= Count)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return values[index];
}
@@ -394,7 +392,7 @@ namespace System.Collections {
// Returns the key of the entry at the given index.
//
public virtual Object GetKey(int index) {
- if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return keys[index];
}
@@ -442,7 +440,7 @@ namespace System.Collections {
return null;
}
set {
- if (key == null) throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ if (key == null) throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
int i = Array.BinarySearch(keys, 0, _size, key, comparer);
if (i >= 0) {
@@ -463,7 +461,7 @@ namespace System.Collections {
//
public virtual int IndexOfKey(Object key) {
if (key == null)
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
int ret = Array.BinarySearch(keys, 0, _size, key, comparer);
return ret >=0 ? ret : -1;
@@ -496,7 +494,7 @@ namespace System.Collections {
// decreased by one.
//
public virtual void RemoveAt(int index) {
- if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
_size--;
if (index < _size) {
@@ -522,7 +520,7 @@ namespace System.Collections {
// the given entry is overwritten.
//
public virtual void SetByIndex(int index, Object value) {
- if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
values[index] = value;
version++;
@@ -530,10 +528,9 @@ namespace System.Collections {
// Returns a thread-safe SortedList.
//
- [HostProtection(Synchronization=true)]
public static SortedList Synchronized(SortedList list) {
if (list==null)
- throw new ArgumentNullException("list");
+ throw new ArgumentNullException(nameof(list));
Contract.EndContractBlock();
return new SyncSortedList(list);
}
@@ -677,7 +674,7 @@ namespace System.Collections {
public override int IndexOfKey(Object key) {
if (key == null)
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
lock(_root) {
@@ -888,7 +885,7 @@ namespace System.Collections {
public virtual int IndexOf(Object key) {
if (key==null)
- throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
Contract.EndContractBlock();
int i = Array.BinarySearch(sortedList.keys, 0,
@@ -993,7 +990,7 @@ namespace System.Collections {
public SortedListDebugView( SortedList sortedList) {
if( sortedList == null) {
- throw new ArgumentNullException("sortedList");
+ throw new ArgumentNullException(nameof(sortedList));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Collections/Stack.cs b/src/mscorlib/src/System/Collections/Stack.cs
index 0384a4ee81..c3ad15abd8 100644
--- a/src/mscorlib/src/System/Collections/Stack.cs
+++ b/src/mscorlib/src/System/Collections/Stack.cs
@@ -44,7 +44,7 @@ namespace System.Collections {
// must be a non-negative number.
public Stack(int initialCapacity) {
if (initialCapacity < 0)
- throw new ArgumentOutOfRangeException("initialCapacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(initialCapacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (initialCapacity < _defaultCapacity)
initialCapacity = _defaultCapacity; // Simplify doubling logic in Push.
@@ -59,7 +59,7 @@ namespace System.Collections {
public Stack(ICollection col) : this((col==null ? 32 : col.Count))
{
if (col==null)
- throw new ArgumentNullException("col");
+ throw new ArgumentNullException(nameof(col));
Contract.EndContractBlock();
IEnumerator en = col.GetEnumerator();
while(en.MoveNext())
@@ -121,11 +121,11 @@ namespace System.Collections {
// Copies the stack into an array.
public virtual void CopyTo(Array array, int index) {
if (array==null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - index < _size)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -189,10 +189,9 @@ namespace System.Collections {
// Returns a synchronized Stack.
//
- [HostProtection(Synchronization=true)]
public static Stack Synchronized(Stack stack) {
if (stack==null)
- throw new ArgumentNullException("stack");
+ throw new ArgumentNullException(nameof(stack));
Contract.Ensures(Contract.Result<Stack>() != null);
Contract.EndContractBlock();
return new SyncStack(stack);
@@ -363,7 +362,7 @@ namespace System.Collections {
public StackDebugView( Stack stack) {
if( stack == null)
- throw new ArgumentNullException("stack");
+ throw new ArgumentNullException(nameof(stack));
Contract.EndContractBlock();
this.stack = stack;
diff --git a/src/mscorlib/src/System/CompatibilitySwitches.cs b/src/mscorlib/src/System/CompatibilitySwitches.cs
index 7facf85df3..bb2f02a679 100644
--- a/src/mscorlib/src/System/CompatibilitySwitches.cs
+++ b/src/mscorlib/src/System/CompatibilitySwitches.cs
@@ -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,67 +28,14 @@ namespace System
internal static void InitializeSwitches()
{
-#if FEATURE_CORECLR
- s_useLatestBehaviorWhenTFMNotSpecified = IsCompatibilitySwitchSet("UseLatestBehaviorWhenTFMNotSpecified");
-#endif //FEATURE_CORECLR
-
-#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
- /// <summary>
- /// This property returns whether to give the latest behavior when the TFM is missing
- /// </summary>
- internal static bool UseLatestBehaviorWhenTFMNotSpecified
- {
- get
- {
- return s_useLatestBehaviorWhenTFMNotSpecified;
- }
- }
-#else //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
}
}
@@ -107,11 +43,7 @@ namespace System
{
get
{
-#if !FEATURE_CORECLR
- return s_isNetFx40LegacySecurityPolicy;
-#else
return false;
-#endif //!FEATURE_CORECLR
}
}
@@ -119,11 +51,7 @@ namespace System
{
get
{
-#if !FEATURE_CORECLR
- return s_isNetFx45LegacyManagedDeflateStream;
-#else
return false;
-#endif //!FEATURE_CORECLR
}
}
}
diff --git a/src/mscorlib/src/System/ContextBoundObject.cs b/src/mscorlib/src/System/ContextBoundObject.cs
deleted file mode 100644
index 01929dabe3..0000000000
--- a/src/mscorlib/src/System/ContextBoundObject.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-** Purpose: Defines the root type for all context bound types
-**
-**
-===========================================================*/
-namespace System {
-
- using System;
- using System.Security.Permissions;
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_REMOTING
- public abstract class ContextBoundObject : MarshalByRefObject {
-#else // FEATURE_REMOTING
- public abstract class ContextBoundObject {
-#endif // FEATURE_REMOTING
- }
-}
diff --git a/src/mscorlib/src/System/ContextStaticAttribute.cs b/src/mscorlib/src/System/ContextStaticAttribute.cs
deleted file mode 100644
index b875aa33f5..0000000000
--- a/src/mscorlib/src/System/ContextStaticAttribute.cs
+++ /dev/null
@@ -1,32 +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: Custom attribute to indicate that the field should be treated
-** as a static relative to a context.
-**
-**
-**
-===========================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Remoting;
-[Serializable]
- [AttributeUsage(AttributeTargets.Field, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
- [Obsolete("ContextStaticAttribute is not supported in this release. It has been left in so that legacy tools can be used with this release, but it cannot be used in your code.", true)]
-#endif // FEATURE_CORECLR
- public class ContextStaticAttribute : Attribute
- {
- public ContextStaticAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Convert.cs b/src/mscorlib/src/System/Convert.cs
index d1468314f2..0e14f93fee 100644
--- a/src/mscorlib/src/System/Convert.cs
+++ b/src/mscorlib/src/System/Convert.cs
@@ -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;
}
@@ -259,7 +260,7 @@ namespace System {
internal static Object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) {
Contract.Requires(value != null, "[Convert.DefaultToType]value!=null");
if (targetType==null) {
- throw new ArgumentNullException("targetType");
+ throw new ArgumentNullException(nameof(targetType));
}
Contract.EndContractBlock();
@@ -322,7 +323,7 @@ namespace System {
public static Object ChangeType(Object value, Type conversionType, IFormatProvider provider) {
if( conversionType == null) {
- throw new ArgumentNullException("conversionType");
+ throw new ArgumentNullException(nameof(conversionType));
}
Contract.EndContractBlock();
@@ -575,7 +576,7 @@ namespace System {
public static char ToChar(String value, IFormatProvider provider) {
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
if (value.Length != 1)
@@ -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"));
@@ -2155,7 +2151,7 @@ namespace System {
public static String ToBase64String(byte[] inArray) {
if (inArray==null) {
- throw new ArgumentNullException("inArray");
+ throw new ArgumentNullException(nameof(inArray));
}
Contract.Ensures(Contract.Result<string>() != null);
Contract.EndContractBlock();
@@ -2165,7 +2161,7 @@ namespace System {
[System.Runtime.InteropServices.ComVisible(false)]
public static String ToBase64String(byte[] inArray, Base64FormattingOptions options) {
if (inArray==null) {
- throw new ArgumentNullException("inArray");
+ throw new ArgumentNullException(nameof(inArray));
}
Contract.Ensures(Contract.Result<string>() != null);
Contract.EndContractBlock();
@@ -2176,16 +2172,15 @@ 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
if (inArray==null)
- throw new ArgumentNullException("inArray");
+ throw new ArgumentNullException(nameof(inArray));
if (length<0)
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (offset<0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options));
Contract.Ensures(Contract.Result<string>() != null);
@@ -2196,7 +2191,7 @@ namespace System {
inArrayLength = inArray.Length;
if (offset > (inArrayLength - length))
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
if (inArrayLength == 0)
return String.Empty;
@@ -2223,20 +2218,19 @@ 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
if (inArray==null)
- throw new ArgumentNullException("inArray");
+ throw new ArgumentNullException(nameof(inArray));
if (outArray==null)
- throw new ArgumentNullException("outArray");
+ throw new ArgumentNullException(nameof(outArray));
if (length<0)
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (offsetIn<0)
- throw new ArgumentOutOfRangeException("offsetIn", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(offsetIn), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (offsetOut<0)
- throw new ArgumentOutOfRangeException("offsetOut", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(offsetOut), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if( options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) {
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options));
@@ -2255,7 +2249,7 @@ namespace System {
inArrayLength = inArray.Length;
if (offsetIn > (int)(inArrayLength - length))
- throw new ArgumentOutOfRangeException("offsetIn", Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
+ throw new ArgumentOutOfRangeException(nameof(offsetIn), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
if (inArrayLength == 0)
return 0;
@@ -2268,7 +2262,7 @@ namespace System {
numElementsToCopy = ToBase64_CalculateAndValidateOutputLength(length, insertLineBreaks);
if (offsetOut > (int)(outArrayLength - numElementsToCopy))
- throw new ArgumentOutOfRangeException("offsetOut", Environment.GetResourceString("ArgumentOutOfRange_OffsetOut"));
+ throw new ArgumentOutOfRangeException(nameof(offsetOut), Environment.GetResourceString("ArgumentOutOfRange_OffsetOut"));
fixed (char* outChars = &outArray[offsetOut]) {
fixed (byte* inData = inArray) {
@@ -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,13 +2359,12 @@ 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.
if (s == null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
Contract.EndContractBlock();
@@ -2392,20 +2384,19 @@ 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)
- throw new ArgumentNullException("inArray");
+ throw new ArgumentNullException(nameof(inArray));
if (length < 0)
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (offset > inArray.Length - length)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
Contract.EndContractBlock();
@@ -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’s 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 '=':
diff --git a/src/mscorlib/src/System/Currency.cs b/src/mscorlib/src/System/Currency.cs
index d29ad2452c..05a09802cd 100644
--- a/src/mscorlib/src/System/Currency.cs
+++ b/src/mscorlib/src/System/Currency.cs
@@ -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);
}
diff --git a/src/mscorlib/src/System/CurrentTimeZone.cs b/src/mscorlib/src/System/CurrentTimeZone.cs
index f015c05b33..804bbcccc4 100644
--- a/src/mscorlib/src/System/CurrentTimeZone.cs
+++ b/src/mscorlib/src/System/CurrentTimeZone.cs
@@ -21,36 +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;
- //
- // Currently, this is the only supported timezone.
- // The values of the timezone is from the current system timezone setting in the
- // control panel.
- //
-#if FEATURE_CORECLR
[Obsolete("System.CurrentSystemTimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo.Local instead.")]
-#endif
[Serializable]
- internal class CurrentSystemTimeZone : TimeZone {
- // <BUGBUG>BUGBUG :
- // One problem is when user changes the current timezone. We
- // are not able to update currentStandardName/currentDaylightName/
- // currentDaylightChanges.
- // We need WM_TIMECHANGE to do this or use
- // RegNotifyChangeKeyValue() to monitor </BUGBUG>
- //
- private const long TicksPerMillisecond = 10000;
- private const long TicksPerSecond = TicksPerMillisecond * 1000;
- private const long TicksPerMinute = TicksPerSecond * 60;
-
+ 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.
@@ -60,43 +42,40 @@ namespace System {
private String m_standardName;
private String m_daylightName;
- [System.Security.SecuritySafeCritical] // auto-generated
- internal CurrentSystemTimeZone() {
- m_ticksOffset = nativeGetTimeZoneMinuteOffset() * TicksPerMinute;
- m_standardName = null;
- m_daylightName = null;
+ internal CurrentSystemTimeZone()
+ {
+ TimeZoneInfo local = TimeZoneInfo.Local;
+
+ m_ticksOffset = local.BaseUtcOffset.Ticks;
+ m_standardName = local.StandardName;
+ m_daylightName = local.DaylightName;
}
- public override String StandardName {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- if (m_standardName == null) {
- m_standardName = nativeGetStandardName();
- }
- return (m_standardName);
+ public override String StandardName
+ {
+ get
+ {
+ return m_standardName;
}
}
- public override String DaylightName {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- if (m_daylightName == null) {
- m_daylightName = nativeGetDaylightName();
- if (m_daylightName == null) {
- m_daylightName = this.StandardName;
- }
- }
- return (m_daylightName);
+ public override String DaylightName
+ {
+ get
+ {
+ return m_daylightName;
}
}
- internal long GetUtcOffsetFromUniversalTime(DateTime time, ref Boolean isAmbiguousLocalDst) {
+ internal long GetUtcOffsetFromUniversalTime(DateTime time, ref Boolean isAmbiguousLocalDst)
+ {
// Get the daylight changes for the year of the specified time.
TimeSpan offset = new TimeSpan(m_ticksOffset);
DaylightTime daylightTime = GetDaylightChanges(time.Year);
isAmbiguousLocalDst= false;
- if (daylightTime == null || daylightTime.Delta.Ticks == 0) {
+ if (daylightTime == null || daylightTime.Delta.Ticks == 0)
+ {
return offset.Ticks;
}
@@ -107,119 +86,109 @@ namespace System {
DateTime endTime = daylightTime.End - offset - daylightTime.Delta;
DateTime ambiguousStart;
DateTime ambiguousEnd;
- if (daylightTime.Delta.Ticks > 0) {
+
+ if (daylightTime.Delta.Ticks > 0)
+ {
ambiguousStart = endTime - daylightTime.Delta;
ambiguousEnd = endTime;
- } else {
+ }
+ else
+ {
ambiguousStart = startTime;
ambiguousEnd = startTime - daylightTime.Delta;
}
Boolean isDst = false;
- if (startTime > endTime) {
+ if (startTime > endTime)
+ {
// In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
// Note, the summer in the southern hemisphere begins late in the year.
isDst = (time < endTime || time >= startTime);
}
- else {
+ else
+ {
// In northern hemisphere, the daylight saving time starts in the middle of the year.
- isDst = (time>=startTime && time<endTime);
+ isDst = (time >= startTime && time < endTime);
}
- if (isDst) {
+
+ if (isDst)
+ {
offset += daylightTime.Delta;
// See if the resulting local time becomes ambiguous. This must be captured here or the
// DateTime will not be able to round-trip back to UTC accurately.
- if (time >= ambiguousStart && time < ambiguousEnd ) {
+ if (time >= ambiguousStart && time < ambiguousEnd )
+ {
isAmbiguousLocalDst = true;
}
}
return offset.Ticks;
}
- public override DateTime ToLocalTime(DateTime time) {
- if (time.Kind == DateTimeKind.Local) {
+ public override DateTime ToLocalTime(DateTime time)
+ {
+ if (time.Kind == DateTimeKind.Local)
+ {
return time;
}
Boolean isAmbiguousLocalDst = false;
Int64 offset = GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst);
long tick = time.Ticks + offset;
- if (tick>DateTime.MaxTicks) {
+ if (tick > DateTime.MaxTicks)
+ {
return new DateTime(DateTime.MaxTicks, DateTimeKind.Local);
}
- if (tick<DateTime.MinTicks) {
+ if (tick < DateTime.MinTicks)
+ {
return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
}
- 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;
- }
+ return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
}
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override DaylightTime GetDaylightChanges(int year) {
- if (year < 1 || year > 9999) {
- throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 9999));
+ public override DaylightTime GetDaylightChanges(int year)
+ {
+ if (year < 1 || year > 9999)
+ {
+ throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 9999));
}
Contract.EndContractBlock();
- Object objYear = (Object)year;
-
- if (!m_CachedDaylightChanges.Contains(objYear)) {
- lock (InternalSyncObject) {
+ Object objYear = (Object) year;
- if (!m_CachedDaylightChanges.Contains(objYear)) {
+ if (!m_CachedDaylightChanges.Contains(objYear))
+ {
+ DaylightTime currentDaylightChanges = null;
- //
- // rawData is an array of 17 short (16 bit) numbers.
- // The first 8 numbers contains the
- // year/month/day/dayOfWeek/hour/minute/second/millisecond for the starting time of daylight saving time.
- // The next 8 numbers contains the
- // year/month/day/dayOfWeek/hour/minute/second/millisecond for the ending time of daylight saving time.
- // The last short number is the delta to the standard offset in minutes.
- //
- short[] rawData = nativeGetDaylightChanges(year);
+ if (TimeZoneInfo.Local.SupportsDaylightSavingTime)
+ {
+ DateTime start;
+ DateTime end;
+ TimeSpan delta;
- if (rawData == null) {
- //
- // If rawData is null, it means that daylight saving time is not used
- // in this timezone. So keep currentDaylightChanges as the empty array.
- //
- m_CachedDaylightChanges.Add(objYear, new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero));
- } else {
- DateTime start;
- DateTime end;
- TimeSpan delta;
+ foreach (var rule in TimeZoneInfo.Local.GetAdjustmentRules())
+ {
+ if (rule.DateStart.Year <= year && rule.DateEnd.Year >= year && rule.DaylightDelta != TimeSpan.Zero)
+ {
+ start = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
+ end = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
+ delta = rule.DaylightDelta;
- //
- // Store the start of daylight saving time.
- //
-
- start = GetDayOfWeek(year, (rawData[0] != 0), rawData[1], rawData[2],
- rawData[3],
- rawData[4], rawData[5], rawData[6], rawData[7]);
+ currentDaylightChanges = new DaylightTime(start, end, delta);
+ break;
+ }
+ }
+ }
- //
- // Store the end of daylight saving time.
- //
- end = GetDayOfWeek(year, (rawData[8] != 0), rawData[9], rawData[10],
- rawData[11],
- rawData[12], rawData[13], rawData[14], rawData[15]);
+ if (currentDaylightChanges == null)
+ {
+ currentDaylightChanges = new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero);
+ }
- delta = new TimeSpan(rawData[16] * TicksPerMinute);
- DaylightTime currentDaylightChanges = new DaylightTime(start, end, delta);
- m_CachedDaylightChanges.Add(objYear, currentDaylightChanges);
- }
+ lock (m_CachedDaylightChanges)
+ {
+ if (!m_CachedDaylightChanges.Contains(objYear))
+ {
+ m_CachedDaylightChanges.Add(objYear, currentDaylightChanges);
}
}
}
@@ -229,82 +198,17 @@ namespace System {
return result;
}
- public override TimeSpan GetUtcOffset(DateTime time) {
- if (time.Kind == DateTimeKind.Utc) {
+ public override TimeSpan GetUtcOffset(DateTime time)
+ {
+ if (time.Kind == DateTimeKind.Utc)
+ {
return TimeSpan.Zero;
}
- else {
+ else
+ {
return new TimeSpan(TimeZone.CalculateUtcOffset(time, GetDaylightChanges(time.Year)).Ticks + m_ticksOffset);
}
}
- //
- // Return the (numberOfSunday)th day of week in a particular year/month.
- //
- private static DateTime GetDayOfWeek(int year, bool fixedDate, int month, int targetDayOfWeek, int numberOfSunday, int hour, int minute, int second, int millisecond) {
- DateTime time;
-
- if (fixedDate) {
- //
- // Create a Fixed-Date transition time based on the supplied parameters
- // For Fixed-Dated transition times, the 'numberOfSunday' parameter actually
- // represents the day of the month.
- //
-
- // if the day is out of range for the month then use the last day of the month
- int day = DateTime.DaysInMonth(year, month);
-
- time = new DateTime(year, month, (day < numberOfSunday) ? day : numberOfSunday,
- hour, minute, second, millisecond, DateTimeKind.Local);
- }
- else if (numberOfSunday <= 4) {
- //
- // Get the (numberOfSunday)th Sunday.
- //
-
- time = new DateTime(year, month, 1, hour, minute, second, millisecond, DateTimeKind.Local);
-
- int dayOfWeek = (int)time.DayOfWeek;
- int delta = targetDayOfWeek - dayOfWeek;
- if (delta < 0) {
- delta += 7;
- }
- delta += 7 * (numberOfSunday - 1);
-
- if (delta > 0) {
- time = time.AddDays(delta);
- }
- } else {
- //
- // If numberOfSunday is greater than 4, we will get the last sunday.
- //
- Calendar cal = GregorianCalendar.GetDefaultInstance();
- time = new DateTime(year, month, cal.GetDaysInMonth(year, month), hour, minute, second, millisecond, DateTimeKind.Local);
- // This is the day of week for the last day of the month.
- int dayOfWeek = (int)time.DayOfWeek;
- int delta = dayOfWeek - targetDayOfWeek;
- if (delta < 0) {
- delta += 7;
- }
-
- if (delta > 0) {
- time = time.AddDays(-delta);
- }
- }
- return (time);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static int nativeGetTimeZoneMinuteOffset();
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static String nativeGetDaylightName();
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static String nativeGetStandardName();
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static short[] nativeGetDaylightChanges(int year);
} // class CurrentSystemTimeZone
}
diff --git a/src/mscorlib/src/System/DBNull.cs b/src/mscorlib/src/System/DBNull.cs
index 130366d86d..6f80af7e21 100644
--- a/src/mscorlib/src/System/DBNull.cs
+++ b/src/mscorlib/src/System/DBNull.cs
@@ -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);
}
diff --git a/src/mscorlib/src/System/DateTime.cs b/src/mscorlib/src/System/DateTime.cs
index c464549333..e93346c42f 100644
--- a/src/mscorlib/src/System/DateTime.cs
+++ b/src/mscorlib/src/System/DateTime.cs
@@ -143,7 +143,7 @@ namespace System {
//
public DateTime(long ticks) {
if (ticks < MinTicks || ticks > MaxTicks)
- throw new ArgumentOutOfRangeException("ticks", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
+ throw new ArgumentOutOfRangeException(nameof(ticks), Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
Contract.EndContractBlock();
dateData = (UInt64)ticks;
}
@@ -154,10 +154,10 @@ namespace System {
public DateTime(long ticks, DateTimeKind kind) {
if (ticks < MinTicks || ticks > MaxTicks) {
- throw new ArgumentOutOfRangeException("ticks", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
+ throw new ArgumentOutOfRangeException(nameof(ticks), Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
}
if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), "kind");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
}
Contract.EndContractBlock();
this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
@@ -165,7 +165,7 @@ namespace System {
internal DateTime(long ticks, DateTimeKind kind, Boolean isAmbiguousDst) {
if (ticks < MinTicks || ticks > MaxTicks) {
- throw new ArgumentOutOfRangeException("ticks", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
+ throw new ArgumentOutOfRangeException(nameof(ticks), Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
}
Contract.Requires(kind == DateTimeKind.Local, "Internal Constructor is for local times only");
Contract.EndContractBlock();
@@ -196,7 +196,7 @@ namespace System {
public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind) {
if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), "kind");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
}
Contract.EndContractBlock();
Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
@@ -208,7 +208,7 @@ namespace System {
//
public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar) {
if (calendar == null)
- throw new ArgumentNullException("calendar");
+ throw new ArgumentNullException(nameof(calendar));
Contract.EndContractBlock();
this.dateData = (UInt64)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
}
@@ -218,7 +218,7 @@ namespace System {
//
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) {
if (millisecond < 0 || millisecond >= MillisPerSecond) {
- throw new ArgumentOutOfRangeException("millisecond", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
+ throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
}
Contract.EndContractBlock();
Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
@@ -230,10 +230,10 @@ namespace System {
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind) {
if (millisecond < 0 || millisecond >= MillisPerSecond) {
- throw new ArgumentOutOfRangeException("millisecond", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
+ throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
}
if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), "kind");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
}
Contract.EndContractBlock();
Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
@@ -248,9 +248,9 @@ namespace System {
//
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar) {
if (calendar == null)
- throw new ArgumentNullException("calendar");
+ throw new ArgumentNullException(nameof(calendar));
if (millisecond < 0 || millisecond >= MillisPerSecond) {
- throw new ArgumentOutOfRangeException("millisecond", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
+ throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
}
Contract.EndContractBlock();
Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
@@ -262,12 +262,12 @@ namespace System {
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind) {
if (calendar == null)
- throw new ArgumentNullException("calendar");
+ throw new ArgumentNullException(nameof(calendar));
if (millisecond < 0 || millisecond >= MillisPerSecond) {
- throw new ArgumentOutOfRangeException("millisecond", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
+ throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
}
if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), "kind");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
}
Contract.EndContractBlock();
Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
@@ -279,7 +279,7 @@ namespace System {
private DateTime(SerializationInfo info, StreamingContext context) {
if (info==null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
Boolean foundTicks = false;
@@ -346,7 +346,7 @@ namespace System {
private DateTime Add(double value, int scale) {
long millis = (long)(value * scale + (value >= 0? 0.5: -0.5));
if (millis <= -MaxMillis || millis >= MaxMillis)
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
return AddTicks(millis * TicksPerMillisecond);
}
@@ -408,7 +408,7 @@ namespace System {
// y1.
//
public DateTime AddMonths(int months) {
- if (months < -120000 || months > 120000) throw new ArgumentOutOfRangeException("months", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadMonths"));
+ if (months < -120000 || months > 120000) throw new ArgumentOutOfRangeException(nameof(months), Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadMonths"));
Contract.EndContractBlock();
int y = GetDatePart(DatePartYear);
int m = GetDatePart(DatePartMonth);
@@ -423,7 +423,7 @@ namespace System {
y = y + (i - 11) / 12;
}
if (y < 1 || y > 9999) {
- throw new ArgumentOutOfRangeException("months", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
+ throw new ArgumentOutOfRangeException(nameof(months), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
}
int days = DaysInMonth(y, m);
if (d > days) d = days;
@@ -447,7 +447,7 @@ namespace System {
public DateTime AddTicks(long value) {
long ticks = InternalTicks;
if (value > MaxTicks - ticks || value < MinTicks - ticks) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
}
return new DateTime((UInt64)(ticks + value) | InternalKind);
}
@@ -527,7 +527,7 @@ namespace System {
// month arguments.
//
public static int DaysInMonth(int year, int month) {
- if (month < 1 || month > 12) throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ if (month < 1 || month > 12) throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
Contract.EndContractBlock();
// IsLeapYear checks the year argument
int[] days = IsLeapYear(year)? DaysToMonth366: DaysToMonth365;
@@ -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
@@ -629,7 +615,7 @@ namespace System {
ticks += TicksPerDay;
}
if (ticks < MinTicks || ticks > MaxTicks) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), "dateData");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), nameof(dateData));
}
return new DateTime(ticks, DateTimeKind.Local, isAmbiguousLocalDst);
}
@@ -643,7 +629,7 @@ namespace System {
internal static DateTime FromBinaryRaw(Int64 dateData) {
Int64 ticks = dateData & (Int64)TicksMask;
if (ticks < MinTicks || ticks > MaxTicks)
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), "dateData");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), nameof(dateData));
return new DateTime((UInt64)dateData);
}
@@ -657,7 +643,7 @@ namespace System {
public static DateTime FromFileTimeUtc(long fileTime) {
if (fileTime < 0 || fileTime > MaxTicks - FileTimeOffset) {
- throw new ArgumentOutOfRangeException("fileTime", Environment.GetResourceString("ArgumentOutOfRange_FileTimeInvalid"));
+ throw new ArgumentOutOfRangeException(nameof(fileTime), Environment.GetResourceString("ArgumentOutOfRange_FileTimeInvalid"));
}
Contract.EndContractBlock();
@@ -675,7 +661,7 @@ namespace System {
[System.Security.SecurityCritical /*auto-generated_required*/]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -775,7 +761,7 @@ namespace System {
int[] days = leapYear? DaysToMonth366: DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
- int m = n >> 5 + 1;
+ int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
@@ -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();
@@ -985,7 +969,7 @@ namespace System {
//
public static bool IsLeapYear(int year) {
if (year < 1 || year > 9999) {
- throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Year"));
+ throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Year"));
}
Contract.EndContractBlock();
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
@@ -1008,7 +992,7 @@ namespace System {
}
public static DateTime Parse(String s, IFormatProvider provider, DateTimeStyles styles) {
- DateTimeFormatInfo.ValidateStyles(styles, "styles");
+ DateTimeFormatInfo.ValidateStyles(styles, nameof(styles));
return (DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), styles));
}
@@ -1025,12 +1009,12 @@ namespace System {
// Leading and trailing whitespace characters are allowed.
//
public static DateTime ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style) {
- DateTimeFormatInfo.ValidateStyles(style, "style");
+ DateTimeFormatInfo.ValidateStyles(style, nameof(style));
return (DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style));
}
public static DateTime ParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style) {
- DateTimeFormatInfo.ValidateStyles(style, "style");
+ DateTimeFormatInfo.ValidateStyles(style, nameof(style));
return DateTimeParse.ParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style);
}
@@ -1042,7 +1026,7 @@ namespace System {
long ticks = InternalTicks;
long valueTicks = value._ticks;
if (ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
}
return new DateTime((UInt64)(ticks - valueTicks) | InternalKind);
}
@@ -1166,17 +1150,17 @@ namespace System {
}
public static Boolean TryParse(String s, IFormatProvider provider, DateTimeStyles styles, out DateTime result) {
- DateTimeFormatInfo.ValidateStyles(styles, "styles");
+ DateTimeFormatInfo.ValidateStyles(styles, nameof(styles));
return DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), styles, out result);
}
public static Boolean TryParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
- DateTimeFormatInfo.ValidateStyles(style, "style");
+ DateTimeFormatInfo.ValidateStyles(style, nameof(style));
return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result);
}
public static Boolean TryParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
- DateTimeFormatInfo.ValidateStyles(style, "style");
+ DateTimeFormatInfo.ValidateStyles(style, nameof(style));
return DateTimeParse.TryParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style, out result);
}
@@ -1184,7 +1168,7 @@ namespace System {
long ticks = d.InternalTicks;
long valueTicks = t._ticks;
if (valueTicks > MaxTicks - ticks || valueTicks < MinTicks - ticks) {
- throw new ArgumentOutOfRangeException("t", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
+ throw new ArgumentOutOfRangeException(nameof(t), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
}
return new DateTime((UInt64)(ticks + valueTicks) | d.InternalKind);
}
@@ -1193,7 +1177,7 @@ namespace System {
long ticks = d.InternalTicks;
long valueTicks = t._ticks;
if (ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) {
- throw new ArgumentOutOfRangeException("t", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
+ throw new ArgumentOutOfRangeException(nameof(t), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
}
return new DateTime((UInt64)(ticks - valueTicks) | d.InternalKind);
}
diff --git a/src/mscorlib/src/System/DateTimeOffset.cs b/src/mscorlib/src/System/DateTimeOffset.cs
index 3e63c76124..5bdaa18aaa 100644
--- a/src/mscorlib/src/System/DateTimeOffset.cs
+++ b/src/mscorlib/src/System/DateTimeOffset.cs
@@ -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,
@@ -87,12 +88,12 @@ namespace System {
public DateTimeOffset(DateTime dateTime, TimeSpan offset) {
if (dateTime.Kind == DateTimeKind.Local) {
if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetLocalMismatch"), "offset");
+ throw new ArgumentException(Environment.GetResourceString("Argument_OffsetLocalMismatch"), nameof(offset));
}
}
else if (dateTime.Kind == DateTimeKind.Utc) {
if (offset != TimeSpan.Zero) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetUtcMismatch"), "offset");
+ throw new ArgumentException(Environment.GetResourceString("Argument_OffsetUtcMismatch"), nameof(offset));
}
}
m_offsetMinutes = ValidateOffset(offset);
@@ -479,7 +480,7 @@ namespace System {
public static DateTimeOffset FromUnixTimeSeconds(long seconds) {
if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds) {
- throw new ArgumentOutOfRangeException("seconds",
+ throw new ArgumentOutOfRangeException(nameof(seconds),
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), UnixMinSeconds, UnixMaxSeconds));
}
@@ -492,7 +493,7 @@ namespace System {
const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) {
- throw new ArgumentOutOfRangeException("milliseconds",
+ throw new ArgumentOutOfRangeException(nameof(milliseconds),
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), MinMilliseconds, MaxMilliseconds));
}
@@ -513,10 +514,9 @@ namespace System {
}
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -528,7 +528,7 @@ namespace System {
DateTimeOffset(SerializationInfo info, StreamingContext context) {
if (info == null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
m_dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime));
@@ -563,7 +563,7 @@ namespace System {
}
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) {
- styles = ValidateStyles(styles, "styles");
+ styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input,
DateTimeFormatInfo.GetInstance(formatProvider),
@@ -585,7 +585,7 @@ namespace System {
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) {
- styles = ValidateStyles(styles, "styles");
+ styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExact(input,
format,
@@ -596,7 +596,7 @@ namespace System {
}
public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) {
- styles = ValidateStyles(styles, "styles");
+ styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExactMultiple(input,
formats,
@@ -693,7 +693,7 @@ namespace System {
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) {
- styles = ValidateStyles(styles, "styles");
+ styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input,
@@ -707,7 +707,7 @@ namespace System {
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result) {
- styles = ValidateStyles(styles, "styles");
+ styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExact(input,
@@ -722,7 +722,7 @@ namespace System {
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result) {
- styles = ValidateStyles(styles, "styles");
+ styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExactMultiple(input,
@@ -739,10 +739,10 @@ namespace System {
private static Int16 ValidateOffset(TimeSpan offset) {
Int64 ticks = offset.Ticks;
if (ticks % TimeSpan.TicksPerMinute != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetPrecision"), "offset");
+ throw new ArgumentException(Environment.GetResourceString("Argument_OffsetPrecision"), nameof(offset));
}
if (ticks < MinOffset || ticks > MaxOffset) {
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_OffsetOutOfRange"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("Argument_OffsetOutOfRange"));
}
return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute);
}
@@ -751,12 +751,12 @@ 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;
if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) {
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_UTCOutOfRange"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("Argument_UTCOutOfRange"));
}
// make sure the Kind is set to Unspecified
//
diff --git a/src/mscorlib/src/System/Decimal.cs b/src/mscorlib/src/System/Decimal.cs
index 8a2c30ffa8..fd16697199 100644
--- a/src/mscorlib/src/System/Decimal.cs
+++ b/src/mscorlib/src/System/Decimal.cs
@@ -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);
@@ -264,7 +262,7 @@ namespace System {
private void SetBits(int[] bits) {
if (bits==null)
- throw new ArgumentNullException("bits");
+ throw new ArgumentNullException(nameof(bits));
Contract.EndContractBlock();
if (bits.Length == 4) {
int f = bits[3];
@@ -283,7 +281,7 @@ namespace System {
//
public Decimal(int lo, int mid, int hi, bool isNegative, byte scale) {
if (scale > 28)
- throw new ArgumentOutOfRangeException("scale", Environment.GetResourceString("ArgumentOutOfRange_DecimalScale"));
+ throw new ArgumentOutOfRangeException(nameof(scale), Environment.GetResourceString("ArgumentOutOfRange_DecimalScale"));
Contract.EndContractBlock();
this.lo = lo;
this.mid = mid;
@@ -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,12 +729,11 @@ 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("decimals", Environment.GetResourceString("ArgumentOutOfRange_DecimalRound"));
+ throw new ArgumentOutOfRangeException(nameof(decimals), Environment.GetResourceString("ArgumentOutOfRange_DecimalRound"));
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, "MidpointRounding"), "mode");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, nameof(MidpointRounding)), nameof(mode));
}
Contract.EndContractBlock();
@@ -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;
}
diff --git a/src/mscorlib/src/System/DefaultBinder.cs b/src/mscorlib/src/System/DefaultBinder.cs
index 405055e844..b4681c406d 100644
--- a/src/mscorlib/src/System/DefaultBinder.cs
+++ b/src/mscorlib/src/System/DefaultBinder.cs
@@ -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,13 +34,12 @@ 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)
{
if (match == null || match.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match));
Contract.EndContractBlock();
MethodBase[] candidates = (MethodBase[]) match.Clone();
@@ -437,11 +437,10 @@ 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) {
- throw new ArgumentNullException("match");
+ throw new ArgumentNullException(nameof(match));
}
int i;
@@ -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;
@@ -524,13 +522,13 @@ namespace System {
for (i=0;i<types.Length;i++) {
realTypes[i] = types[i].UnderlyingSystemType;
if (!(realTypes[i] is RuntimeType))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"types");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(types));
}
types = realTypes;
// We don't automatically jump out on exact match.
if (match == null || match.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match));
MethodBase[] candidates = (MethodBase[]) match.Clone();
@@ -589,17 +587,16 @@ 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)
{
// Allow a null indexes array. But if it is not null, every element must be non-null as well.
if (indexes != null && !Contract.ForAll(indexes, delegate(Type t) { return t != null; }))
{
- throw new ArgumentNullException("indexes");
+ throw new ArgumentNullException(nameof(indexes));
}
if (match == null || match.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match));
Contract.EndContractBlock();
PropertyInfo[] candidates = (PropertyInfo[]) match.Clone();
@@ -732,7 +729,7 @@ namespace System {
public static MethodBase ExactBinding(MethodBase[] match,Type[] types,ParameterModifier[] modifiers)
{
if (match==null)
- throw new ArgumentNullException("match");
+ throw new ArgumentNullException(nameof(match));
Contract.EndContractBlock();
MethodBase[] aExactMatches = new MethodBase[match.Length];
int cExactMatches = 0;
@@ -772,7 +769,7 @@ namespace System {
public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match,Type returnType,Type[] types,ParameterModifier[] modifiers)
{
if (match==null)
- throw new ArgumentNullException("match");
+ throw new ArgumentNullException(nameof(match));
Contract.EndContractBlock();
PropertyInfo bestMatch = null;
@@ -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);
diff --git a/src/mscorlib/src/System/Delegate.cs b/src/mscorlib/src/System/Delegate.cs
index 110555423c..bca88c18e9 100644
--- a/src/mscorlib/src/System/Delegate.cs
+++ b/src/mscorlib/src/System/Delegate.cs
@@ -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,36 +21,31 @@ 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)
- throw new ArgumentNullException("target");
+ throw new ArgumentNullException(nameof(target));
if (method == null)
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
// This API existed in v1/v1.1 and only expected to create closed
@@ -67,22 +63,21 @@ 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)
- throw new ArgumentNullException("target");
+ throw new ArgumentNullException(nameof(target));
if (target.IsGenericType && target.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), "target");
+ throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), nameof(target));
if (method == null)
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtTarget = target as RuntimeType;
if (rtTarget == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "target");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(target));
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
@@ -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,22 +341,21 @@ 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)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
if (target == null)
- throw new ArgumentNullException("target");
+ throw new ArgumentNullException(nameof(target));
if (method == null)
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create closed
@@ -402,27 +392,26 @@ 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)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
if (target == null)
- throw new ArgumentNullException("target");
+ throw new ArgumentNullException(nameof(target));
if (target.IsGenericType && target.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), "target");
+ throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), nameof(target));
if (method == null)
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
RuntimeType rtTarget = target as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
if (rtTarget == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "target");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(target));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create open
@@ -443,27 +432,26 @@ 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)
{
// Validate the parameters.
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
if (method == null)
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(method));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
@@ -494,27 +482,26 @@ 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)
{
// Validate the parameters.
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
if (method == null)
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(method));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
@@ -555,7 +542,6 @@ namespace System {
// Implementation of ISerializable
//
- [System.Security.SecurityCritical]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException();
@@ -566,23 +552,22 @@ 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.
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
if (method.IsNullHandle())
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
// Initialize the method...
Delegate d = InternalAlloc(rtType);
@@ -600,23 +585,22 @@ 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.
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
if (method == null)
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo;
if (rtMethod == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(method));
if (!type.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
// This API is used by the formatters when deserializing a delegate.
// They pass us the specific target method (that was already the
@@ -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);
}
diff --git a/src/mscorlib/src/System/DelegateSerializationHolder.cs b/src/mscorlib/src/System/DelegateSerializationHolder.cs
index a6280333db..83fe35ad1e 100644
--- a/src/mscorlib/src/System/DelegateSerializationHolder.cs
+++ b/src/mscorlib/src/System/DelegateSerializationHolder.cs
@@ -17,14 +17,13 @@ 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)
{
// Used for MulticastDelegate
if (method == null)
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
if (!method.IsPublic || (method.DeclaringType != null && !method.DeclaringType.IsVisible))
@@ -116,11 +115,10 @@ namespace System
#endregion
#region Constructor
- [System.Security.SecurityCritical] // auto-generated
private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
bool bNewWire = true;
@@ -182,7 +180,7 @@ namespace System
private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
String delegateType = info.GetString("DelegateType");
@@ -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"));
diff --git a/src/mscorlib/src/System/Diagnostics/Assert.cs b/src/mscorlib/src/System/Diagnostics/Assert.cs
index 40efe753af..77cc6d8e46 100644
--- a/src/mscorlib/src/System/Diagnostics/Assert.cs
+++ b/src/mscorlib/src/System/Diagnostics/Assert.cs
@@ -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);
}
diff --git a/src/mscorlib/src/System/Diagnostics/AssertFilter.cs b/src/mscorlib/src/System/Diagnostics/AssertFilter.cs
index b441fc326b..ab60ee4cff 100644
--- a/src/mscorlib/src/System/Diagnostics/AssertFilter.cs
+++ b/src/mscorlib/src/System/Diagnostics/AssertFilter.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
index e002e6a5c1..27f4f4cdaa 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
@@ -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")]
@@ -654,7 +655,7 @@ namespace System.Diagnostics.Contracts {
throw new ArgumentException("fromInclusive must be less than or equal to toExclusive.");
#endif
if (predicate == null)
- throw new ArgumentNullException("predicate");
+ throw new ArgumentNullException(nameof(predicate));
Contract.EndContractBlock();
for (int i = fromInclusive; i < toExclusive; i++)
@@ -679,9 +680,9 @@ namespace System.Diagnostics.Contracts {
public static bool ForAll<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
- throw new ArgumentNullException("collection");
+ throw new ArgumentNullException(nameof(collection));
if (predicate == null)
- throw new ArgumentNullException("predicate");
+ throw new ArgumentNullException(nameof(predicate));
Contract.EndContractBlock();
foreach (T t in collection)
@@ -716,7 +717,7 @@ namespace System.Diagnostics.Contracts {
throw new ArgumentException("fromInclusive must be less than or equal to toExclusive.");
#endif
if (predicate == null)
- throw new ArgumentNullException("predicate");
+ throw new ArgumentNullException(nameof(predicate));
Contract.EndContractBlock();
for (int i = fromInclusive; i < toExclusive; i++)
@@ -740,9 +741,9 @@ namespace System.Diagnostics.Contracts {
public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
- throw new ArgumentNullException("collection");
+ throw new ArgumentNullException(nameof(collection));
if (predicate == null)
- throw new ArgumentNullException("predicate");
+ throw new ArgumentNullException(nameof(predicate));
Contract.EndContractBlock();
foreach (T t in collection)
@@ -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
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
index 804318e702..d5e3f29e6c 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
@@ -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)
@@ -99,7 +98,7 @@ namespace System.Diagnostics.Contracts {
static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), "failureKind");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), nameof(failureKind));
Contract.EndContractBlock();
// displayMessage == null means: yes we handled it. Otherwise it is the localized failure message
@@ -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,12 +313,11 @@ 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)
{
if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), "failureKind");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), nameof(failureKind));
Contract.EndContractBlock();
string returnValue;
@@ -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
diff --git a/src/mscorlib/src/System/Diagnostics/Debugger.cs b/src/mscorlib/src/System/Diagnostics/Debugger.cs
index 339c89eecf..8ebbc0a354 100644
--- a/src/mscorlib/src/System/Diagnostics/Debugger.cs
+++ b/src/mscorlib/src/System/Diagnostics/Debugger.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
index 6adcf34eda..e75b653a0b 100644
--- a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
+++ b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
@@ -142,7 +142,7 @@ namespace System.Diagnostics {
public DebuggerBrowsableAttribute(DebuggerBrowsableState state)
{
if( state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden)
- throw new ArgumentOutOfRangeException("state");
+ throw new ArgumentOutOfRangeException(nameof(state));
Contract.EndContractBlock();
this.state = state;
@@ -166,7 +166,7 @@ namespace System.Diagnostics {
public DebuggerTypeProxyAttribute(Type type)
{
if (type == null) {
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
@@ -186,7 +186,7 @@ namespace System.Diagnostics {
{
set {
if( value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -257,7 +257,7 @@ namespace System.Diagnostics {
{
set {
if( value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -302,7 +302,7 @@ namespace System.Diagnostics {
public DebuggerVisualizerAttribute(string visualizerTypeName, Type visualizerObjectSource)
{
if (visualizerObjectSource == null) {
- throw new ArgumentNullException("visualizerObjectSource");
+ throw new ArgumentNullException(nameof(visualizerObjectSource));
}
Contract.EndContractBlock();
this.visualizerName = visualizerTypeName;
@@ -311,7 +311,7 @@ namespace System.Diagnostics {
public DebuggerVisualizerAttribute(Type visualizer)
{
if (visualizer == null) {
- throw new ArgumentNullException("visualizer");
+ throw new ArgumentNullException(nameof(visualizer));
}
Contract.EndContractBlock();
this.visualizerName = visualizer.AssemblyQualifiedName;
@@ -319,10 +319,10 @@ namespace System.Diagnostics {
public DebuggerVisualizerAttribute(Type visualizer, Type visualizerObjectSource)
{
if (visualizer == null) {
- throw new ArgumentNullException("visualizer");
+ throw new ArgumentNullException(nameof(visualizer));
}
if (visualizerObjectSource == null) {
- throw new ArgumentNullException("visualizerObjectSource");
+ throw new ArgumentNullException(nameof(visualizerObjectSource));
}
Contract.EndContractBlock();
this.visualizerName = visualizer.AssemblyQualifiedName;
@@ -331,7 +331,7 @@ namespace System.Diagnostics {
public DebuggerVisualizerAttribute(Type visualizer, string visualizerObjectSourceTypeName)
{
if (visualizer == null) {
- throw new ArgumentNullException("visualizer");
+ throw new ArgumentNullException(nameof(visualizer));
}
Contract.EndContractBlock();
this.visualizerName = visualizer.AssemblyQualifiedName;
@@ -356,7 +356,7 @@ namespace System.Diagnostics {
{
set {
if( value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs b/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs
index a7124a26ff..1a1f5fa2c0 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
index 6ea8d98d92..ce0fcb6acb 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
@@ -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)
{
//
@@ -175,16 +172,31 @@ namespace System.Diagnostics.Tracing
// Disable the provider.
m_enabled = false;
- // Do most of the work under a lock to avoid shutdown race.
+ // Do most of the work under a lock to avoid shutdown race.
+
+ long registrationHandle = 0;
lock (EventListener.EventListenersLock)
{
// Double check
if (m_disposed)
return;
- Deregister();
+ registrationHandle = m_regHandle;
+ m_regHandle = 0;
m_disposed = true;
}
+
+ // We do the Unregistration outside the EventListenerLock because there is a lock
+ // inside the ETW routines. This lock is taken before ETW issues commands
+ // Thus the ETW lock gets taken first and then our EventListenersLock gets taken
+ // in SendCommand(), and also here. If we called EventUnregister after taking
+ // the EventListenersLock then the take-lock order is reversed and we can have
+ // deadlocks in race conditions (dispose racing with an ETW command).
+ //
+ // We solve by Unregistering after releasing the EventListenerLock.
+ if (registrationHandle != 0)
+ EventUnregister(registrationHandle);
+
}
/// <summary>
@@ -201,33 +213,10 @@ namespace System.Diagnostics.Tracing
Dispose(false);
}
- /// <summary>
- /// This method un-registers from ETW.
- /// </summary>
- // <SecurityKernel Critical="True" Ring="0">
- // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" />
- // </SecurityKernel>
- // TODO Check return code from UnsafeNativeMethods.ManifestEtw.EventUnregister
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical]
- private unsafe void Deregister()
- {
- //
- // Unregister from ETW using the RegHandle saved from
- // the register call.
- //
-
- if (m_regHandle != 0)
- {
- EventUnregister();
- m_regHandle = 0;
- }
- }
-
// <SecurityKernel Critical="True" Ring="0">
// <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,
@@ -348,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;
@@ -424,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.
@@ -470,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];
}
@@ -552,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)
{
@@ -685,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)
/*++
@@ -934,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;
@@ -1131,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);
@@ -1154,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,
@@ -1183,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;
@@ -1191,12 +1172,9 @@ namespace System.Diagnostics.Tracing
return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
}
- [SecurityCritical]
- private uint EventUnregister()
+ private uint EventUnregister(long registrationHandle)
{
- uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle);
- m_regHandle = 0;
- return status;
+ return UnsafeNativeMethods.ManifestEtw.EventUnregister(registrationHandle);
}
static int[] nibblebits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
@@ -1209,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++;
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
index 8c2edfdec2..aa0d8d72d1 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
@@ -529,7 +529,6 @@ namespace System.Diagnostics.Tracing
/// </summary>
internal static Guid InternalCurrentThreadActivityId
{
- [System.Security.SecurityCritical]
get
{
Guid retval = CurrentThreadActivityId;
@@ -543,12 +542,11 @@ namespace System.Diagnostics.Tracing
internal static Guid FallbackActivityId
{
- [System.Security.SecurityCritical]
get
{
#pragma warning disable 612, 618
int threadID = AppDomain.GetCurrentThreadId();
-
+
// Managed thread IDs are more aggressively re-used than native thread IDs,
// so we'll use the latter...
return new Guid(unchecked((uint)threadID),
@@ -608,7 +606,7 @@ namespace System.Diagnostics.Tracing
add
{
m_eventCommandExecuted += value;
-
+
// If we have an EventHandler<EventCommandEventArgs> attached to the EventSource before the first command arrives
// It should get a chance to handle the deferred commands.
EventCommandEventArgs deferredCommands = m_deferredCommands;
@@ -706,7 +704,7 @@ namespace System.Diagnostics.Tracing
return;
}
-
+
/// <summary>
/// This method is called when the eventSource is updated by the controller.
/// </summary>
@@ -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)
{
@@ -977,70 +960,68 @@ 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)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- if (arg1 == null || arg1.Length == 0)
- {
- int blobSize = 0;
- descrs[0].DataPointer = (IntPtr)(&blobSize);
- descrs[0].Size = 4;
- descrs[1].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty content
- descrs[1].Size = 0;
- WriteEventCore(eventId, 2, descrs);
- }
- else
- {
- int blobSize = arg1.Length;
- fixed (byte* blob = &arg1[0])
- {
- descrs[0].DataPointer = (IntPtr)(&blobSize);
- descrs[0].Size = 4;
- descrs[1].DataPointer = (IntPtr)blob;
- descrs[1].Size = blobSize;
- WriteEventCore(eventId, 2, descrs);
- }
- }
- }
- }
-
- [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)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 8;
- if (arg2 == null || arg2.Length == 0)
- {
- int blobSize = 0;
- descrs[1].DataPointer = (IntPtr)(&blobSize);
- descrs[1].Size = 4;
- descrs[2].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty contents
- descrs[2].Size = 0;
- WriteEventCore(eventId, 3, descrs);
- }
- else
- {
- int blobSize = arg2.Length;
- fixed (byte* blob = &arg2[0])
- {
- descrs[1].DataPointer = (IntPtr)(&blobSize);
- descrs[1].Size = 4;
- descrs[2].DataPointer = (IntPtr)blob;
- descrs[2].Size = blobSize;
- WriteEventCore(eventId, 3, descrs);
- }
- }
- }
- }
+
+ [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)
+ {
+ if (m_eventSourceEnabled)
+ {
+ EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
+ if (arg1 == null || arg1.Length == 0)
+ {
+ int blobSize = 0;
+ descrs[0].DataPointer = (IntPtr)(&blobSize);
+ descrs[0].Size = 4;
+ descrs[1].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty content
+ descrs[1].Size = 0;
+ WriteEventCore(eventId, 2, descrs);
+ }
+ else
+ {
+ int blobSize = arg1.Length;
+ fixed (byte* blob = &arg1[0])
+ {
+ descrs[0].DataPointer = (IntPtr)(&blobSize);
+ descrs[0].Size = 4;
+ descrs[1].DataPointer = (IntPtr)blob;
+ descrs[1].Size = blobSize;
+ WriteEventCore(eventId, 2, descrs);
+ }
+ }
+ }
+ }
+
+ [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)
+ {
+ if (m_eventSourceEnabled)
+ {
+ EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
+ descrs[0].DataPointer = (IntPtr)(&arg1);
+ descrs[0].Size = 8;
+ if (arg2 == null || arg2.Length == 0)
+ {
+ int blobSize = 0;
+ descrs[1].DataPointer = (IntPtr)(&blobSize);
+ descrs[1].Size = 4;
+ descrs[2].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty contents
+ descrs[2].Size = 0;
+ WriteEventCore(eventId, 3, descrs);
+ }
+ else
+ {
+ int blobSize = arg2.Length;
+ fixed (byte* blob = &arg2[0])
+ {
+ descrs[1].DataPointer = (IntPtr)(&blobSize);
+ descrs[1].Size = 4;
+ descrs[2].DataPointer = (IntPtr)blob;
+ descrs[2].Size = blobSize;
+ WriteEventCore(eventId, 3, descrs);
+ }
+ }
+ }
+ }
#pragma warning restore 1591
@@ -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,36 +1127,37 @@ 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);
-#if FEATURE_MANAGED_ETW
- if (m_eventData[eventId].EnabledForETW)
+ EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
+ EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions;
+ Guid* pActivityId = null;
+ Guid activityId = Guid.Empty;
+ Guid relActivityId = Guid.Empty;
+
+ if (opcode != EventOpcode.Info && relatedActivityId == null &&
+ ((activityOptions & EventActivityOptions.Disable) == 0))
{
- EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
- EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions;
- Guid* pActivityId = null;
- Guid activityId = Guid.Empty;
- Guid relActivityId = Guid.Empty;
-
- if (opcode != EventOpcode.Info && relatedActivityId == null &&
- ((activityOptions & EventActivityOptions.Disable) == 0))
+ if (opcode == EventOpcode.Start)
{
- if (opcode == EventOpcode.Start)
- {
- m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relActivityId, m_eventData[eventId].ActivityOptions);
- }
- else if (opcode == EventOpcode.Stop)
- {
- m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId);
- }
-
- if (activityId != Guid.Empty)
- pActivityId = &activityId;
- if (relActivityId != Guid.Empty)
- relatedActivityId = &relActivityId;
+ m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relActivityId, m_eventData[eventId].ActivityOptions);
}
+ else if (opcode == EventOpcode.Stop)
+ {
+ m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId);
+ }
+
+ if (activityId != Guid.Empty)
+ pActivityId = &activityId;
+ if (relActivityId != Guid.Empty)
+ relatedActivityId = &relActivityId;
+ }
+
+#if FEATURE_MANAGED_ETW
+ if (m_eventData[eventId].EnabledForETW)
+ {
#if FEATURE_ACTIVITYSAMPLING
// this code should be kept in sync with WriteEventVarargs().
@@ -1298,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)
{
@@ -1313,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);
@@ -1380,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)
{
@@ -1390,18 +1367,18 @@ namespace System.Diagnostics.Tracing
}
else
{
- List<object> arg = new List<object>();
- arg.Add(msg);
EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
eventCallbackArgs.EventId = 0;
- eventCallbackArgs.Payload = new ReadOnlyCollection<object>(arg);
+ eventCallbackArgs.Message = msg;
+ eventCallbackArgs.Payload = new ReadOnlyCollection<object>(new List<object>() { msg });
+ eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>(new List<string> { "message" });
+ eventCallbackArgs.EventName = "EventSourceMessage";
listener.OnEventWritten(eventCallbackArgs);
}
}
}
#endif
- [SecurityCritical]
private unsafe void WriteEventRaw(
string eventName,
ref EventDescriptor eventDescriptor,
@@ -1443,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
@@ -1500,7 +1476,7 @@ namespace System.Diagnostics.Tracing
#endif
{
int setInformationResult;
- System.Runtime.InteropServices.GCHandle metadataHandle =
+ System.Runtime.InteropServices.GCHandle metadataHandle =
System.Runtime.InteropServices.GCHandle.Alloc(this.providerMetadata, System.Runtime.InteropServices.GCHandleType.Pinned);
IntPtr providerMetadata = metadataHandle.AddrOfPinnedObject();
@@ -1513,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;
}
@@ -1742,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
@@ -1754,7 +1729,7 @@ namespace System.Diagnostics.Tracing
Type dataType = GetDataType(m_eventData[eventId], parameterId);
- Again:
+ Again:
if (dataType == typeof(IntPtr))
{
return *((IntPtr*)dataPointer);
@@ -1889,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);
@@ -1916,33 +1890,34 @@ namespace System.Diagnostics.Tracing
}
LogEventArgsMismatches(m_eventData[eventId].Parameters, args);
-#if FEATURE_MANAGED_ETW
- if (m_eventData[eventId].EnabledForETW)
+
+ Guid* pActivityId = null;
+ Guid activityId = Guid.Empty;
+ Guid relatedActivityId = Guid.Empty;
+ EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
+ EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions;
+
+ if (childActivityID == null &&
+ ((activityOptions & EventActivityOptions.Disable) == 0))
{
- Guid* pActivityId = null;
- Guid activityId = Guid.Empty;
- Guid relatedActivityId = Guid.Empty;
- EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
- EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions;
-
- if (childActivityID == null &&
- ((activityOptions & EventActivityOptions.Disable) == 0))
+ if (opcode == EventOpcode.Start)
{
- if (opcode == EventOpcode.Start)
- {
- m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relatedActivityId, m_eventData[eventId].ActivityOptions);
- }
- else if (opcode == EventOpcode.Stop)
- {
- m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId);
- }
-
- if (activityId != Guid.Empty)
- pActivityId = &activityId;
- if (relatedActivityId != Guid.Empty)
- childActivityID = &relatedActivityId;
+ m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relatedActivityId, m_eventData[eventId].ActivityOptions);
+ }
+ else if (opcode == EventOpcode.Stop)
+ {
+ m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId);
}
+ if (activityId != Guid.Empty)
+ pActivityId = &activityId;
+ if (relatedActivityId != Guid.Empty)
+ childActivityID = &relatedActivityId;
+ }
+
+#if FEATURE_MANAGED_ETW
+ if (m_eventData[eventId].EnabledForETW)
+ {
#if FEATURE_ACTIVITYSAMPLING
// this code should be kept in sync with WriteEventWithRelatedActivityIdCore().
SessionMask etwSessions = SessionMask.All;
@@ -2059,7 +2034,6 @@ namespace System.Diagnostics.Tracing
}
}
- [SecurityCritical]
unsafe private object[] SerializeEventArgs(int eventId, object[] args)
{
TraceLoggingEventTypes eventTypes = m_eventData[eventId].TraceLoggingEventTypes;
@@ -2120,9 +2094,9 @@ namespace System.Diagnostics.Tracing
private int GetParamLenghtIncludingByteArray(ParameterInfo[] parameters)
{
int sum = 0;
- foreach(ParameterInfo info in parameters)
+ foreach (ParameterInfo info in parameters)
{
- if(info.ParameterType == typeof(byte[]))
+ if (info.ParameterType == typeof(byte[]))
{
sum += 2;
}
@@ -2135,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
@@ -2159,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);
@@ -2173,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
@@ -2214,8 +2185,7 @@ namespace System.Diagnostics.Tracing
throw new EventSourceException(lastThrownException);
}
}
-
- [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)
{
@@ -2310,7 +2280,6 @@ namespace System.Diagnostics.Tracing
}
#if FEATURE_ACTIVITYSAMPLING
- [SecurityCritical]
unsafe private SessionMask GetEtwSessionMask(int eventId, Guid* childActivityID)
{
SessionMask etwSessions = new SessionMask();
@@ -2429,9 +2398,9 @@ namespace System.Diagnostics.Tracing
try
{
m_EventSourceExceptionRecurenceCount++;
-
+
string errorPrefix = "EventSourceException";
- if(eventName != null)
+ if (eventName != null)
{
errorPrefix += " while processing event \"" + eventName + "\"";
}
@@ -2473,7 +2442,7 @@ namespace System.Diagnostics.Tracing
private void ValidateEventOpcodeForTransfer(ref EventMetadata eventData, string eventName)
{
if ((EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Send &&
- (EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Receive &&
+ (EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Receive &&
(EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Start)
{
ThrowEventSourceException(eventName);
@@ -2545,7 +2514,7 @@ namespace System.Diagnostics.Tracing
public TraceLoggingEventTypes TraceLoggingEventTypes;
public EventActivityOptions ActivityOptions;
-
+
#if PROJECTN
public EventParameterType[] ParameterTypes;
#endif
@@ -2611,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
@@ -2623,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);
@@ -2682,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)
@@ -2737,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;
}
@@ -2825,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;
@@ -3017,16 +2986,15 @@ namespace System.Diagnostics.Tracing
return false;
}
- private bool IsDisposed
+ private bool IsDisposed
{
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)
{
@@ -3042,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
@@ -3089,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;
@@ -3097,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)
@@ -3124,7 +3091,7 @@ namespace System.Diagnostics.Tracing
dataDescrs[1].Reserved = 0;
int chunkSize = ManifestEnvelope.MaxChunkSize;
- TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE:
+ TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE:
envelope.TotalChunks = (ushort)((dataLeft + (chunkSize - 1)) / chunkSize);
while (dataLeft > 0)
{
@@ -3153,10 +3120,10 @@ namespace System.Diagnostics.Tracing
dataLeft -= chunkSize;
dataDescrs[1].Ptr += (uint)chunkSize;
envelope.ChunkNumber++;
-
+
// For large manifests we want to not overflow any receiver's buffer. Most manifests will fit within
// 5 chunks, so only the largest manifests will hit the pause.
- if((envelope.ChunkNumber % 5) == 0)
+ if ((envelope.ChunkNumber % 5) == 0)
Thread.Sleep(15);
}
}
@@ -3201,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)
{
@@ -3236,7 +3203,7 @@ namespace System.Diagnostics.Tracing
return null;
#else // ES_BUILD_PCL && PROJECTN
- throw new ArgumentException(Resources.GetResourceString("EventSource", "EventSource_PCLPlatformNotSupportedReflection"));
+ throw new ArgumentException(Resources.GetResourceString("EventSource", nameof(EventSource_PCLPlatformNotSupportedReflection)));
#endif
}
@@ -3256,8 +3223,8 @@ namespace System.Diagnostics.Tracing
attributeType == reflectedAttributeType ||
// are the full typenames equal?
string.Equals(attributeType.FullName, reflectedAttributeType.FullName, StringComparison.Ordinal) ||
- // are the typenames equal and the namespaces under "Diagnostics.Tracing" (typically
- // either Microsoft.Diagnostics.Tracing or System.Diagnostics.Tracing)?
+ // are the typenames equal and the namespaces under "Diagnostics.Tracing" (typically
+ // either Microsoft.Diagnostics.Tracing or System.Diagnostics.Tracing)?
string.Equals(attributeType.Name, reflectedAttributeType.Name, StringComparison.Ordinal) &&
attributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) &&
(reflectedAttributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal)
@@ -3488,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?
@@ -3535,7 +3502,7 @@ namespace System.Diagnostics.Tracing
{
unchecked
{
- eventAttribute.Keywords |= (EventKeywords)manifest.GetChannelKeyword(eventAttribute.Channel, (ulong) eventAttribute.Keywords);
+ eventAttribute.Keywords |= (EventKeywords)manifest.GetChannelKeyword(eventAttribute.Channel, (ulong)eventAttribute.Keywords);
}
}
#endif
@@ -3658,7 +3625,7 @@ namespace System.Diagnostics.Tracing
}
#endif
return;
- Error:
+ Error:
manifest.ManifestError(Resources.GetResourceString("EventSource_EnumKindMismatch", staticField.Name, staticField.FieldType.Name, providerEnumKind));
}
@@ -3751,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.
@@ -3821,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)
{
@@ -3840,7 +3806,7 @@ namespace System.Diagnostics.Tracing
(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)).Assert();
byte[] instrs = method.GetMethodBody().GetILAsByteArray();
int retVal = -1;
- for (int idx = 0; idx < instrs.Length; )
+ for (int idx = 0; idx < instrs.Length;)
{
switch (instrs[idx])
{
@@ -3934,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;
}
@@ -3968,7 +3934,7 @@ namespace System.Diagnostics.Tracing
{
#if (!ES_BUILD_PCL && !PROJECTN)
// send message to debugger without delay
- System.Diagnostics.Debugger.Log(0, null, String.Format("EventSource Error: {0}{1}", msg , Environment.NewLine));
+ System.Diagnostics.Debugger.Log(0, null, String.Format("EventSource Error: {0}{1}", msg, Environment.NewLine));
#endif
// Send it to all listeners.
@@ -4017,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;
}
@@ -4039,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)
{
@@ -4050,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
@@ -4090,7 +4056,7 @@ namespace System.Diagnostics.Tracing
private EventSourceSettings m_config; // configuration information
private bool m_eventSourceDisposed; // has Dispose been called.
-
+
// Enabling bits
private bool m_eventSourceEnabled; // am I enabled (any of my events are enabled for any dispatcher)
internal EventLevel m_level; // highest level enabled by any output dispatcher
@@ -4229,7 +4195,7 @@ namespace System.Diagnostics.Tracing
/// events for a particular eventSource to occur BEFORE the EventSourceCreatedCallback is issued.
/// </summary>
public event EventHandler<EventSourceCreatedEventArgs> EventSourceCreated
- {
+ {
add
{
CallBackForExistingEventSources(false, value);
@@ -4255,7 +4221,7 @@ namespace System.Diagnostics.Tracing
public EventListener()
{
// This will cause the OnEventSourceCreated callback to fire.
- CallBackForExistingEventSources(true, (obj, args) => args.EventSource.AddListener(this) );
+ CallBackForExistingEventSources(true, (obj, args) => args.EventSource.AddListener(this));
}
/// <summary>
@@ -4283,7 +4249,7 @@ namespace System.Diagnostics.Tracing
{
// Find 'this' from the s_Listeners linked list.
EventListener prev = s_Listeners;
- for (; ; )
+ for (;;)
{
EventListener cur = prev.m_Next;
if (cur == null)
@@ -4397,7 +4363,7 @@ namespace System.Diagnostics.Tracing
internal protected virtual void OnEventSourceCreated(EventSource eventSource)
{
EventHandler<EventSourceCreatedEventArgs> callBack = this._EventSourceCreated;
- if(callBack != null)
+ if (callBack != null)
{
EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs();
args.EventSource = eventSource;
@@ -4443,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
}
@@ -4492,7 +4454,7 @@ namespace System.Diagnostics.Tracing
// See bug 724140 for more
private static void DisposeOnShutdown(object sender, EventArgs e)
{
- lock(EventListenersLock)
+ lock (EventListenersLock)
{
foreach (var esRef in s_EventSources)
{
@@ -4512,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)
@@ -4527,12 +4489,12 @@ namespace System.Diagnostics.Tracing
{
// Remove 'listenerToRemove' from the eventSource.m_Dispatchers linked list.
EventDispatcher prev = eventSource.m_Dispatchers;
- for (; ; )
+ for (;;)
{
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)
@@ -4572,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;
}
@@ -4586,9 +4548,9 @@ namespace System.Diagnostics.Tracing
foreach (EventListener listener in allListeners.Keys)
{
dispatcher = eventSource.m_Dispatchers;
- for (; ; )
+ 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;
@@ -4818,7 +4780,6 @@ namespace System.Diagnostics.Tracing
/// </summary>
public Guid ActivityId
{
- [System.Security.SecurityCritical]
get { return EventSource.CurrentThreadActivityId; }
}
@@ -4827,7 +4788,6 @@ namespace System.Diagnostics.Tracing
/// </summary>
public Guid RelatedActivityId
{
- [System.Security.SecurityCritical]
get;
internal set;
}
@@ -4848,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)
@@ -4893,7 +4853,7 @@ namespace System.Diagnostics.Tracing
{
get
{
- if (EventId < 0) // TraceLogging convention EventID == -1
+ if (EventId <= 0) // TraceLogging convention EventID == -1
return m_opcode;
return (EventOpcode)m_eventSource.m_eventData[EventId].Descriptor.Opcode;
}
@@ -4906,7 +4866,7 @@ namespace System.Diagnostics.Tracing
{
get
{
- if (EventId < 0) // TraceLogging convention EventID == -1
+ if (EventId <= 0) // TraceLogging convention EventID == -1
return EventTask.None;
return (EventTask)m_eventSource.m_eventData[EventId].Descriptor.Task;
@@ -4920,20 +4880,20 @@ namespace System.Diagnostics.Tracing
{
get
{
- if (EventId < 0) // TraceLogging convention EventID == -1
+ if (EventId <= 0) // TraceLogging convention EventID == -1
return m_tags;
return m_eventSource.m_eventData[EventId].Tags;
}
}
/// <summary>
- /// Gets the message for the event.
+ /// Gets the message for the event. If the message has {N} parameters they are NOT substituted.
/// </summary>
public string Message
{
get
{
- if (EventId < 0) // TraceLogging convention EventID == -1
+ if (EventId <= 0) // TraceLogging convention EventID == -1
return m_message;
else
return m_eventSource.m_eventData[EventId].Message;
@@ -4953,7 +4913,7 @@ namespace System.Diagnostics.Tracing
{
get
{
- if (EventId < 0) // TraceLogging convention EventID == -1
+ if (EventId <= 0) // TraceLogging convention EventID == -1
return EventChannel.None;
return (EventChannel)m_eventSource.m_eventData[EventId].Descriptor.Channel;
}
@@ -4967,7 +4927,7 @@ namespace System.Diagnostics.Tracing
{
get
{
- if (EventId < 0) // TraceLogging convention EventID == -1
+ if (EventId <= 0) // TraceLogging convention EventID == -1
return 0;
return m_eventSource.m_eventData[EventId].Descriptor.Version;
}
@@ -4980,7 +4940,7 @@ namespace System.Diagnostics.Tracing
{
get
{
- if (EventId < 0) // TraceLogging convention EventID == -1
+ if (EventId <= 0) // TraceLogging convention EventID == -1
return m_level;
return (EventLevel)m_eventSource.m_eventData[EventId].Descriptor.Level;
}
@@ -5277,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)
@@ -5345,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'
@@ -5432,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,
@@ -5440,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)
{
@@ -5513,7 +5472,6 @@ namespace System.Diagnostics.Tracing
return shouldBeLogged;
}
- [System.Security.SecuritySafeCritical]
public static bool IsCurrentActivityActive(ActivityFilter filterList)
{
var activeActivities = GetActiveActivities(filterList);
@@ -5530,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))
@@ -5593,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
@@ -5620,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
@@ -5694,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);
@@ -5828,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;
@@ -5909,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);
}
@@ -5927,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);
}
@@ -6163,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);
}
@@ -6206,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;
@@ -6311,7 +6268,7 @@ namespace System.Diagnostics.Tracing
// otherwise we allocate a channel bit for the channel.
// explicit channel bits are only used by WCF to mimic an existing manifest,
// so we don't dont do error checking.
- public ulong GetChannelKeyword(EventChannel channel, ulong channelKeyword=0)
+ public ulong GetChannelKeyword(EventChannel channel, ulong channelKeyword = 0)
{
// strip off any non-channel keywords, since we are only interested in channels here.
channelKeyword &= ValidPredefinedChannelKeywords;
@@ -6560,7 +6517,7 @@ namespace System.Diagnostics.Tracing
// very early in the app domain creation, when _FusionStore is not set up yet, resulting in a failure to run the static constructory
// for BinaryCompatibility. This failure is then cached and a TypeInitializationException is thrown every time some code attampts to
// access BinaryCompatibility.
- ArraySortHelper<string>.IntrospectiveSort(sortedStrings, 0, sortedStrings.Length, Comparer<string>.Default);
+ ArraySortHelper<string>.IntrospectiveSort(sortedStrings, 0, sortedStrings.Length, string.Compare);
#endif
foreach (var ci in cultures)
{
@@ -6642,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;
@@ -6701,7 +6652,7 @@ namespace System.Diagnostics.Tracing
ret = taskTab[(int)task] = eventName;
return ret;
}
-
+
private string GetOpcodeName(EventOpcode opcode, string eventName)
{
switch (opcode)
@@ -6738,12 +6689,12 @@ namespace System.Diagnostics.Tracing
}
return ret;
}
-
+
private string GetKeywords(ulong keywords, string eventName)
{
// ignore keywords associate with channels
// See ValidPredefinedChannelKeywords def for more.
- keywords &= ~ValidPredefinedChannelKeywords;
+ keywords &= ~ValidPredefinedChannelKeywords;
string ret = "";
for (ulong bit = 1; bit != 0; bit <<= 1)
@@ -6770,7 +6721,7 @@ namespace System.Diagnostics.Tracing
}
return ret;
}
-
+
private string GetTypeName(Type type)
{
if (type.IsEnum())
@@ -6779,7 +6730,7 @@ namespace System.Diagnostics.Tracing
var typeName = GetTypeName(fields[0].FieldType);
return typeName.Replace("win:Int", "win:UInt"); // ETW requires enums to be unsigned.
}
-
+
return GetTypeNameHelper(type);
}
@@ -6797,7 +6748,7 @@ namespace System.Diagnostics.Tracing
StringBuilder stringBuilder = null; // We lazily create this
int writtenSoFar = 0;
int chIdx = -1;
- for (int i = 0; ; )
+ for (int i = 0; ;)
{
if (i >= eventMessage.Length)
{
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
index 00bd0b7caa..0a689efe92 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
@@ -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,
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs
index d0d687e8d8..079d7f480b 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs
@@ -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]
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs
index be97447301..5967ad6ab5 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs
@@ -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;
@@ -40,7 +41,7 @@ namespace System.Diagnostics.Tracing
get
{
if (key == null)
- throw new System.ArgumentNullException("key");
+ throw new System.ArgumentNullException(nameof(key));
int position = 0;
foreach(var name in m_names)
@@ -83,7 +84,7 @@ namespace System.Diagnostics.Tracing
public bool ContainsKey(string key)
{
if (key == null)
- throw new System.ArgumentNullException("key");
+ throw new System.ArgumentNullException(nameof(key));
foreach (var item in m_names)
{
@@ -129,7 +130,7 @@ namespace System.Diagnostics.Tracing
public bool TryGetValue(string key, out object value)
{
if (key == null)
- throw new System.ArgumentNullException("key");
+ throw new System.ArgumentNullException(nameof(key));
int position = 0;
foreach (var name in m_names)
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs
index fccfd48721..38c1767462 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs
@@ -35,7 +35,7 @@ namespace System.Diagnostics.Tracing
public EventSourceActivity(EventSource eventSource)
{
if (eventSource == null)
- throw new ArgumentNullException("eventSource");
+ throw new ArgumentNullException(nameof(eventSource));
Contract.EndContractBlock();
this.eventSource = eventSource;
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs
index 45673f7ab5..309226b84d 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs
@@ -108,7 +108,7 @@ namespace System.Diagnostics.Tracing
if (name == null)
{
throw new ArgumentNullException(
- "name",
+ nameof(name),
"This usually means that the object passed to Write is of a type that"
+ " does not support being used as the top-level object in an event,"
+ " e.g. a primitive or built-in type.");
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs
index 0f34d95648..3ea781252f 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs
@@ -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;
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs
index e51aff0380..901a0ed1a2 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs
@@ -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"));
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs
index fa0f79f58f..516c8ba19a 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs
@@ -175,7 +175,7 @@ namespace System.Diagnostics.Tracing
{
if (name != null && 0 <= name.IndexOf('\0'))
{
- throw new ArgumentOutOfRangeException("name");
+ throw new ArgumentOutOfRangeException(nameof(name));
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs
index 4b6e633487..04a047fb35 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs
@@ -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();
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs
index 963c492419..07a56751ea 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs
@@ -100,7 +100,7 @@ namespace System.Diagnostics.Tracing
{
if (eventSourceName == null)
{
- throw new ArgumentNullException("eventSourceName");
+ throw new ArgumentNullException(nameof(eventSourceName));
}
Contract.EndContractBlock();
}
@@ -110,12 +110,11 @@ 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)
{
- throw new ArgumentNullException("eventName");
+ throw new ArgumentNullException(nameof(eventName));
}
Contract.EndContractBlock();
@@ -138,12 +137,11 @@ 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)
{
- throw new ArgumentNullException("eventName");
+ throw new ArgumentNullException(nameof(eventName));
}
Contract.EndContractBlock();
@@ -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)
{
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs
index 4e33e58a82..c2239671bb 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs
@@ -94,7 +94,7 @@ namespace System.Diagnostics.Tracing
{
if (name == null)
{
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
@@ -132,7 +132,7 @@ namespace System.Diagnostics.Tracing
{
if (defaultName == null)
{
- throw new ArgumentNullException("defaultName");
+ throw new ArgumentNullException(nameof(defaultName));
}
Contract.EndContractBlock();
@@ -212,7 +212,7 @@ namespace System.Diagnostics.Tracing
{
if (paramInfos == null)
{
- throw new ArgumentNullException("paramInfos");
+ throw new ArgumentNullException(nameof(paramInfos));
}
Contract.EndContractBlock();
@@ -231,7 +231,7 @@ namespace System.Diagnostics.Tracing
{
if (types == null)
{
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
}
Contract.EndContractBlock();
@@ -251,7 +251,7 @@ namespace System.Diagnostics.Tracing
{
if (typeInfos == null)
{
- throw new ArgumentNullException("typeInfos");
+ throw new ArgumentNullException(nameof(typeInfos));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs
index 0467ec43e5..41225c8626 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs
@@ -156,7 +156,7 @@ namespace System.Diagnostics.Tracing
size = 16;
break;
default:
- throw new ArgumentOutOfRangeException("type");
+ throw new ArgumentOutOfRangeException(nameof(type));
}
this.impl.AddScalar(size);
@@ -183,7 +183,7 @@ namespace System.Diagnostics.Tracing
case TraceLoggingDataType.CountedUtf16String:
break;
default:
- throw new ArgumentOutOfRangeException("type");
+ throw new ArgumentOutOfRangeException(nameof(type));
}
this.impl.AddScalar(2);
@@ -227,7 +227,7 @@ namespace System.Diagnostics.Tracing
case TraceLoggingDataType.Char8:
break;
default:
- throw new ArgumentOutOfRangeException("type");
+ throw new ArgumentOutOfRangeException(nameof(type));
}
if (this.BeginningBufferedArray)
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
index 5815d12fb0..0cc17e02f3 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
@@ -36,7 +36,7 @@ namespace System.Diagnostics.Tracing
{
if (dataType == null)
{
- throw new ArgumentNullException("dataType");
+ throw new ArgumentNullException(nameof(dataType));
}
Contract.EndContractBlock();
@@ -56,7 +56,7 @@ namespace System.Diagnostics.Tracing
{
if (dataType == null)
{
- throw new ArgumentNullException("dataType");
+ throw new ArgumentNullException(nameof(dataType));
}
if (name == null)
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs b/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs
index d7112fc81b..c96d2129f0 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs
@@ -73,9 +73,8 @@ namespace System.Diagnostics.Tracing
}
}
- private static string Serialize(ReadOnlyCollection<string> payloadName, ReadOnlyCollection<object> payload, string sep = ", ")
+ private static string Serialize(ReadOnlyCollection<string> payloadName, ReadOnlyCollection<object> payload, string eventMessage)
{
-
if (payloadName == null || payload == null )
return String.Empty;
@@ -92,8 +91,22 @@ namespace System.Diagnostics.Tracing
var sb = StringBuilderCache.Acquire();
sb.Append('{');
+
+ // If the event has a message, send that as well as a pseudo-field
+ if (!string.IsNullOrEmpty(eventMessage))
+ {
+ sb.Append("\\\"EventSource_Message\\\":\\\"");
+ minimalJsonserializer(eventMessage,sb);
+ sb.Append("\\\"");
+ if (eventDataCount != 0)
+ sb.Append(", ");
+ }
+
for (int i = 0; i < eventDataCount; i++)
{
+ if (i != 0)
+ sb.Append(", ");
+
var fieldstr = payloadName[i].ToString();
sb.Append("\\\"");
@@ -114,14 +127,9 @@ namespace System.Diagnostics.Tracing
sb.Append(payload[i].ToString());
}
- sb.Append(sep);
-
}
-
- sb.Length -= sep.Length;
- sb.Append('}');
-
- return StringBuilderCache.GetStringAndRelease(sb);
+ sb.Append('}');
+ return StringBuilderCache.GetStringAndRelease(sb);
}
internal protected override void OnEventSourceCreated(EventSource eventSource)
@@ -149,7 +157,7 @@ namespace System.Diagnostics.Tracing
if (eventData.Payload != null)
{
try{
- payload = Serialize(eventData.PayloadNames, eventData.Payload);
+ payload = Serialize(eventData.PayloadNames, eventData.Payload, eventData.Message);
}
catch (Exception ex)
{
diff --git a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
index e3e2b867c4..84f6b91f65 100644
--- a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
+++ b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
@@ -33,11 +33,10 @@ 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)
- throw new ArgumentOutOfRangeException("Name", Environment.GetResourceString("Argument_StringZeroLength"));
+ throw new ArgumentOutOfRangeException(nameof(Name), Environment.GetResourceString("Argument_StringZeroLength"));
Contract.EndContractBlock();
if ((name != null) && (parent != null))
@@ -55,10 +54,9 @@ namespace System.Diagnostics {
Log.AddLogSwitch (this);
}
else
- throw new ArgumentNullException ((name==null ? "name" : "parent"));
+ 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;
diff --git a/src/mscorlib/src/System/Diagnostics/Stackframe.cs b/src/mscorlib/src/System/Diagnostics/Stackframe.cs
index 397c3e12e6..06d675ea08 100644
--- a/src/mscorlib/src/System/Diagnostics/Stackframe.cs
+++ b/src/mscorlib/src/System/Diagnostics/Stackframe.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
index 047a60f328..7dc5d9df09 100644
--- a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
+++ b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
@@ -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,14 +287,11 @@ 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)
{
if (skipFrames < 0)
- throw new ArgumentOutOfRangeException("skipFrames",
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -325,14 +304,11 @@ 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)
{
if (skipFrames < 0)
- throw new ArgumentOutOfRangeException("skipFrames",
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -347,7 +323,7 @@ namespace System.Diagnostics {
public StackTrace(Exception e)
{
if (e == null)
- throw new ArgumentNullException("e");
+ throw new ArgumentNullException(nameof(e));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
@@ -357,13 +333,10 @@ 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)
- throw new ArgumentNullException("e");
+ throw new ArgumentNullException(nameof(e));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
@@ -374,16 +347,13 @@ 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)
- throw new ArgumentNullException("e");
+ throw new ArgumentNullException(nameof(e));
if (skipFrames < 0)
- throw new ArgumentOutOfRangeException("skipFrames",
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -396,16 +366,13 @@ 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)
- throw new ArgumentNullException("e");
+ throw new ArgumentNullException(nameof(e));
if (skipFrames < 0)
- throw new ArgumentOutOfRangeException("skipFrames",
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -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
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
index b6177be2aa..a0d3640c2c 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
@@ -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
diff --git a/src/mscorlib/src/System/Diagnostics/log.cs b/src/mscorlib/src/System/Diagnostics/log.cs
index 1c68aad161..6916ce3a0a 100644
--- a/src/mscorlib/src/System/Diagnostics/log.cs
+++ b/src/mscorlib/src/System/Diagnostics/log.cs
@@ -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);
@@ -140,7 +139,7 @@ namespace System.Diagnostics {
throw new ArgumentNullException ("LogSwitch");
if (level < 0)
- throw new ArgumentOutOfRangeException("level", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(level), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Is logging for this level for this switch enabled?
@@ -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);
}
diff --git a/src/mscorlib/src/System/Double.cs b/src/mscorlib/src/System/Double.cs
index b2d509af8d..ce146a1227 100644
--- a/src/mscorlib/src/System/Double.cs
+++ b/src/mscorlib/src/System/Double.cs
@@ -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));
diff --git a/src/mscorlib/src/System/Empty.cs b/src/mscorlib/src/System/Empty.cs
index f7e7486014..4790d9a383 100644
--- a/src/mscorlib/src/System/Empty.cs
+++ b/src/mscorlib/src/System/Empty.cs
@@ -25,10 +25,9 @@ namespace System {
return String.Empty;
}
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.EmptyUnity, null, null);
diff --git a/src/mscorlib/src/System/Enum.cs b/src/mscorlib/src/System/Enum.cs
index a8104556e4..d39e005d48 100644
--- a/src/mscorlib/src/System/Enum.cs
+++ b/src/mscorlib/src/System/Enum.cs
@@ -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,12 +323,28 @@ 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"));
}
}
}
+ public static bool TryParse(Type enumType, String value, out Object result)
+ {
+ return TryParse(enumType, value, false, out result);
+ }
+
+ public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result)
+ {
+ result = null;
+ EnumResult parseResult = new EnumResult();
+ bool retValue;
+
+ if (retValue = TryParseEnum(enumType, value, ignoreCase, ref parseResult))
+ result = parseResult.parsedEnum;
+ return retValue;
+ }
+
public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct
{
return TryParse(value, false, out result);
@@ -366,21 +377,35 @@ namespace System
throw parseResult.GetEnumParseException();
}
+ public static TEnum Parse<TEnum>(String value) where TEnum : struct
+ {
+ return Parse<TEnum>(value, false);
+ }
+
+ public static TEnum Parse<TEnum>(String value, bool ignoreCase) where TEnum : struct
+ {
+ EnumResult parseResult = new EnumResult() { canThrow = true };
+ if (TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult))
+ return (TEnum)parseResult.parsedEnum;
+ else
+ throw parseResult.GetEnumParseException();
+ }
+
private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, ref EnumResult parseResult)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
if (value == null) {
- parseResult.SetFailure(ParseFailureKind.ArgumentNull, "value");
+ parseResult.SetFailure(ParseFailureKind.ArgumentNull, nameof(value));
return false;
}
@@ -504,7 +529,7 @@ namespace System
public static Type GetUnderlyingType(Type enumType)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
Contract.Ensures(Contract.Result<Type>() != null);
Contract.EndContractBlock();
@@ -515,7 +540,7 @@ namespace System
public static Array GetValues(Type enumType)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
Contract.Ensures(Contract.Result<Array>() != null);
Contract.EndContractBlock();
@@ -532,7 +557,7 @@ namespace System
public static String GetName(Type enumType, Object value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
Contract.EndContractBlock();
return enumType.GetEnumName(value);
@@ -542,7 +567,7 @@ namespace System
public static String[] GetNames(Type enumType)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -559,7 +584,7 @@ namespace System
public static Object ToObject(Type enumType, Object value)
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Delegate rest of error checking to the other functions
@@ -599,7 +624,7 @@ namespace System
default:
// All unsigned types will be directly cast
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), nameof(value));
}
}
@@ -608,7 +633,7 @@ namespace System
public static bool IsDefined(Type enumType, Object value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
Contract.EndContractBlock();
return enumType.IsEnumDefined(value);
@@ -618,21 +643,21 @@ namespace System
public static String Format(Type enumType, Object value, String format)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
if (format == null)
- throw new ArgumentNullException("format");
+ throw new ArgumentNullException(nameof(format));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
// Check if both of them are of the same type
Type valueType = value.GetType();
@@ -698,7 +723,6 @@ namespace System
#endregion
#region Private Methods
- [System.Security.SecuritySafeCritical]
internal unsafe Object GetValue()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
@@ -734,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)
@@ -787,32 +810,29 @@ 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()
{
- // Avoid boxing by inlining GetValue()
- // return GetValue().GetHashCode();
+ // CONTRACT with the runtime: GetHashCode of enum types is implemented as GetHashCode of the underlying type.
+ // The runtime can bypass calls to Enum::GetHashCode and call the underlying type's GetHashCode directly
+ // to avoid boxing the enum.
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
{
@@ -847,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;
}
}
@@ -876,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
@@ -904,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"));
}
@@ -942,10 +961,9 @@ namespace System
return ToString();
}
- [System.Security.SecuritySafeCritical]
public Boolean HasFlag(Enum flag) {
if (flag == null)
- throw new ArgumentNullException("flag");
+ throw new ArgumentNullException(nameof(flag));
Contract.EndContractBlock();
if (!this.GetType().IsEquivalentTo(flag.GetType())) {
@@ -1013,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"));
}
@@ -1109,155 +1127,145 @@ 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)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, short value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, int value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, byte value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, ushort value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, uint value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, long value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, ulong value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, unchecked((long)value));
}
- [System.Security.SecuritySafeCritical] // auto-generated
private static Object ToObject(Type enumType, char value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
private static Object ToObject(Type enumType, bool value)
{
if (enumType == null)
- throw new ArgumentNullException("enumType");
+ throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
return InternalBoxEnum(rtType, value ? 1 : 0);
}
#endregion
diff --git a/src/mscorlib/src/System/Environment.cs b/src/mscorlib/src/System/Environment.cs
index 5ee30bb9ba..835219a01c 100644
--- a/src/mscorlib/src/System/Environment.cs
+++ b/src/mscorlib/src/System/Environment.cs
@@ -32,17 +32,16 @@ namespace System {
using System.Diagnostics.Contracts;
[ComVisible(true)]
- public enum EnvironmentVariableTarget {
+ public enum EnvironmentVariableTarget
+ {
Process = 0,
-#if FEATURE_WIN32_REGISTRY
User = 1,
Machine = 2,
-#endif
}
[ComVisible(true)]
- public static class Environment {
-
+ public static partial class Environment
+ {
// Assume the following constants include the terminating '\0' - use <, not <=
const int MaxEnvVariableValueLength = 32767; // maximum length for environment variable name and value
// System environment variables are stored in the registry, and have
@@ -89,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]";
}
@@ -125,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;
@@ -189,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)
{
@@ -248,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;
}
@@ -281,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);
@@ -302,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.
@@ -353,9 +298,6 @@ namespace System {
return Directory.GetCurrentDirectory();
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
set {
Directory.SetCurrentDirectory(value);
}
@@ -363,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;
}
@@ -387,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();
@@ -399,11 +330,10 @@ namespace System {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ExpandEnvironmentVariables(String name)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
if (name.Length == 0) {
@@ -442,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)
@@ -519,7 +392,6 @@ namespace System {
}
public static String MachineName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
// UWP Debug scenarios
@@ -531,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)
@@ -542,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();
@@ -571,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
@@ -591,145 +455,37 @@ 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
-
- /*============================GetEnvironmentVariable============================
- **Action:
- **Returns:
- **Arguments:
- **Exceptions:
- ==============================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
- public static String GetEnvironmentVariable(String variable)
- {
- if (variable == null)
- throw new ArgumentNullException("variable");
- Contract.EndContractBlock();
-
- 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;
- }
-
-#if !FEATURE_CORECLR
- (new EnvironmentPermission(EnvironmentPermissionAccess.Read, variable)).Demand();
-#endif //!FEATURE_CORECLR
-
- StringBuilder blob = StringBuilderCache.Acquire(128); // A somewhat reasonable default size
- int requiredSize = Win32Native.GetEnvironmentVariable(variable, blob, blob.Capacity);
-
- if (requiredSize == 0) { // GetEnvironmentVariable failed
- if (Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND) {
- StringBuilderCache.Release(blob);
- return null;
- }
- }
-
- while (requiredSize > blob.Capacity) { // need to retry since the environment variable might be changed
- blob.Capacity = requiredSize;
- blob.Length = 0;
- requiredSize = Win32Native.GetEnvironmentVariable(variable, blob, blob.Capacity);
- }
- return StringBuilderCache.GetStringAndRelease(blob);
- }
- [System.Security.SecuritySafeCritical] // auto-generated
- public static string GetEnvironmentVariable( string variable, EnvironmentVariableTarget target)
- {
- if (variable == null)
- {
- throw new ArgumentNullException("variable");
- }
- Contract.EndContractBlock();
-
- if (target == EnvironmentVariableTarget.Process)
- {
- return GetEnvironmentVariable(variable);
- }
-
-#if FEATURE_WIN32_REGISTRY
- (new EnvironmentPermission(PermissionState.Unrestricted)).Demand();
-
- if( target == EnvironmentVariableTarget.Machine) {
- using (RegistryKey environmentKey =
- Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Session Manager\Environment", false)) {
-
- Contract.Assert(environmentKey != null, @"HKLM\System\CurrentControlSet\Control\Session Manager\Environment is missing!");
- if (environmentKey == null) {
- return null;
- }
-
- string value = environmentKey.GetValue(variable) as string;
- return value;
- }
- }
- else if( target == EnvironmentVariableTarget.User) {
- using (RegistryKey environmentKey =
- Registry.CurrentUser.OpenSubKey("Environment", false)) {
-
- Contract.Assert(environmentKey != null, @"HKCU\Environment is missing!");
- if (environmentKey == null) {
- return null;
- }
-
- string value = environmentKey.GetValue(variable) as string;
- return value;
- }
- }
- else
-#endif // FEATURE_WIN32_REGISTRY
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)target));
- }
- }
-
- /*===========================GetEnvironmentVariables============================
- **Action: Returns an IDictionary containing all enviroment variables and their values.
- **Returns: An IDictionary containing all environment variables and their values.
- **Arguments: None.
- **Exceptions: None.
- ==============================================================================*/
- [System.Security.SecurityCritical] // auto-generated
private unsafe static char[] GetEnvironmentCharArray()
{
char[] block = null;
// Make sure pStrings is not leaked with async exceptions
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
}
- finally {
- char * pStrings = null;
+ finally
+ {
+ char* pStrings = null;
try
{
pStrings = Win32Native.GetEnvironmentStrings();
- if (pStrings == null) {
+ if (pStrings == null)
+ {
throw new OutOfMemoryException();
}
@@ -739,7 +495,7 @@ namespace System {
// CreateProcess page (null-terminated array of null-terminated strings).
// Search for terminating \0\0 (two unicode \0's).
- char * p = pStrings;
+ char* p = pStrings;
while (!(*p == '\0' && *(p + 1) == '\0'))
p++;
@@ -747,7 +503,7 @@ namespace System {
block = new char[len];
fixed (char* pBlock = block)
- String.wstrcpy(pBlock, pStrings, len);
+ string.wstrcpy(pBlock, pStrings, len);
}
finally
{
@@ -759,275 +515,12 @@ namespace System {
return block;
}
- [System.Security.SecuritySafeCritical] // auto-generated
- public static IDictionary GetEnvironmentVariables()
- {
- 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);
- }
-
-#if !FEATURE_CORECLR
- bool isFullTrust = CodeAccessSecurityEngine.QuickCheckForAllDemands();
- StringBuilder vars = isFullTrust ? null : new StringBuilder();
- bool first = true;
-#endif
-
- char[] block = GetEnvironmentCharArray();
-
- Hashtable table = new Hashtable(20);
-
- // Copy strings out, parsing into pairs and inserting into the table.
- // The first few environment variable entries start with an '='!
- // The current working directory of every drive (except for those drives
- // you haven't cd'ed into in your DOS window) are stored in the
- // environment block (as =C:=pwd) and the program's exit code is
- // as well (=ExitCode=00000000) Skip all that start with =.
- // Read docs about Environment Blocks on MSDN's CreateProcess page.
-
- // Format for GetEnvironmentStrings is:
- // (=HiddenVar=value\0 | Variable=value\0)* \0
- // See the description of Environment Blocks in MSDN's
- // CreateProcess page (null-terminated array of null-terminated strings).
- // Note the =HiddenVar's aren't always at the beginning.
-
- for(int i=0; i<block.Length; i++) {
- int startKey = i;
- // Skip to key
- // On some old OS, the environment block can be corrupted.
- // Someline will not have '=', so we need to check for '\0'.
- while(block[i]!='=' && block[i] != '\0') {
- i++;
- }
-
- if(block[i] == '\0') {
- continue;
- }
-
- // Skip over environment variables starting with '='
- if (i-startKey==0) {
- while(block[i]!=0) {
- i++;
- }
- continue;
- }
- String key = new String(block, startKey, i-startKey);
- i++; // skip over '='
- int startValue = i;
- while(block[i]!=0) {
- // Read to end of this entry
- i++;
- }
-
- String value = new String(block, startValue, i-startValue);
- // skip over 0 handled by for loop's i++
- table[key]=value;
-
-#if !FEATURE_CORECLR
- if (!isFullTrust) {
- if( first) {
- first = false;
- }
- else {
- vars.Append(';');
- }
- vars.Append(key);
- }
-#endif
- }
-
-#if !FEATURE_CORECLR
- if (!isFullTrust)
- new EnvironmentPermission(EnvironmentPermissionAccess.Read, vars.ToString()).Demand();
-#endif
- return table;
- }
-
-#if FEATURE_WIN32_REGISTRY
- internal static IDictionary GetRegistryKeyNameValuePairs(RegistryKey registryKey) {
- Hashtable table = new Hashtable(20);
-
- if (registryKey != null) {
- string[] names = registryKey.GetValueNames();
- foreach( string name in names) {
- string value = registryKey.GetValue(name, "").ToString();
- table.Add(name, value);
- }
- }
- return table;
- }
-#endif
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public static IDictionary GetEnvironmentVariables( EnvironmentVariableTarget target) {
- if( target == EnvironmentVariableTarget.Process) {
- return GetEnvironmentVariables();
- }
-
-#if FEATURE_WIN32_REGISTRY
- (new EnvironmentPermission(PermissionState.Unrestricted)).Demand();
-
- if( target == EnvironmentVariableTarget.Machine) {
- using (RegistryKey environmentKey =
- Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Session Manager\Environment", false)) {
-
- return GetRegistryKeyNameValuePairs(environmentKey);
- }
- }
- else if( target == EnvironmentVariableTarget.User) {
- using (RegistryKey environmentKey =
- Registry.CurrentUser.OpenSubKey("Environment", false)) {
- return GetRegistryKeyNameValuePairs(environmentKey);
- }
- }
- else
-#endif // FEATURE_WIN32_REGISTRY
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)target));
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public static void SetEnvironmentVariable(string variable, string value) {
- CheckEnvironmentVariableName(variable);
-
-#if !FEATURE_CORECLR
- new EnvironmentPermission(PermissionState.Unrestricted).Demand();
-#endif
- // explicitly null out value if is the empty string.
- if (String.IsNullOrEmpty(value) || value[0] == '\0') {
- value = null;
- }
- else {
- if( value.Length >= MaxEnvVariableValueLength) {
- throw new ArgumentException(Environment.GetResourceString("Argument_LongEnvVarValue"));
- }
- }
-
- 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();
-
- // Allow user to try to clear a environment variable
- if( errorCode == Win32Native.ERROR_ENVVAR_NOT_FOUND) {
- return;
- }
-
- // The error message from Win32 is "The filename or extension is too long",
- // which is not accurate.
- if( errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE) {
- throw new ArgumentException(Environment.GetResourceString("Argument_LongEnvVarValue"));
- }
-
- throw new ArgumentException(Win32Native.GetMessage(errorCode));
- }
- }
-
- private static void CheckEnvironmentVariableName(string variable) {
- if (variable == null) {
- throw new ArgumentNullException("variable");
- }
-
- if( variable.Length == 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_StringZeroLength"), "variable");
- }
-
- if( variable[0] == '\0') {
- throw new ArgumentException(Environment.GetResourceString("Argument_StringFirstCharIsZero"), "variable");
- }
-
- // Make sure the environment variable name isn't longer than the
- // max limit on environment variable values. (MSDN is ambiguous
- // on whether this check is necessary.)
- if( variable.Length >= MaxEnvVariableValueLength ) {
- throw new ArgumentException(Environment.GetResourceString("Argument_LongEnvVarValue"));
- }
-
- if( variable.IndexOf('=') != -1) {
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalEnvVarName"));
- }
- Contract.EndContractBlock();
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) {
- if( target == EnvironmentVariableTarget.Process) {
- SetEnvironmentVariable(variable, value);
- return;
- }
-
- CheckEnvironmentVariableName(variable);
-
- // System-wide environment variables stored in the registry are
- // limited to 1024 chars for the environment variable name.
- if (variable.Length >= MaxSystemEnvVariableLength) {
- throw new ArgumentException(Environment.GetResourceString("Argument_LongEnvVarName"));
- }
-
- new EnvironmentPermission(PermissionState.Unrestricted).Demand();
- // explicitly null out value if is the empty string.
- if (String.IsNullOrEmpty(value) || value[0] == '\0') {
- value = null;
- }
-#if FEATURE_WIN32_REGISTRY
- if( target == EnvironmentVariableTarget.Machine) {
- using (RegistryKey environmentKey =
- Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Session Manager\Environment", true)) {
-
- Contract.Assert(environmentKey != null, @"HKLM\System\CurrentControlSet\Control\Session Manager\Environment is missing!");
- if (environmentKey != null) {
- if (value == null)
- environmentKey.DeleteValue(variable, false);
- else
- environmentKey.SetValue(variable, value);
- }
- }
- }
- else if( target == EnvironmentVariableTarget.User) {
- // User-wide environment variables stored in the registry are
- // limited to 255 chars for the environment variable name.
- if (variable.Length >= MaxUserEnvVariableLength) {
- throw new ArgumentException(Environment.GetResourceString("Argument_LongEnvVarValue"));
- }
- using (RegistryKey environmentKey =
- Registry.CurrentUser.OpenSubKey("Environment", true)) {
- Contract.Assert(environmentKey != null, @"HKCU\Environment is missing!");
- if (environmentKey != null) {
- if (value == null)
- environmentKey.DeleteValue(variable, false);
- else
- environmentKey.SetValue(variable, value);
- }
- }
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)target));
- }
- // 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) BCLDebug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
-
-#else // FEATURE_WIN32_REGISTRY
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)target));
-#endif
- }
-
-
/*===============================GetLogicalDrives===============================
**Action: Retrieves the names of the logical drives on this machine in the form "C:\".
**Arguments: None.
**Exceptions: IOException.
**Permissions: SystemInfo Permission.
==============================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public static String[] GetLogicalDrives() {
new EnvironmentPermission(PermissionState.Unrestricted).Demand();
@@ -1097,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();
@@ -1117,7 +608,6 @@ namespace System {
**Exceptions:
==============================================================================*/
public static OperatingSystem OSVersion {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<OperatingSystem>() != null);
@@ -1141,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;
}
}
@@ -1186,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();
@@ -1197,7 +686,6 @@ namespace System {
}
}
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
@@ -1206,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);
@@ -1222,7 +708,6 @@ namespace System {
**Exceptions:
==============================================================================*/
public static String StackTrace {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<String>() != null);
@@ -1231,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
@@ -1250,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
@@ -1275,20 +756,13 @@ 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) {
if (m_resHelper == null)
InitResourceHelper();
@@ -1296,30 +770,74 @@ 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
}
- [System.Security.SecuritySafeCritical] // auto-generated
- internal static String GetResourceString(String key, params Object[] values) {
- String s = GetResourceString(key);
- return String.Format(CultureInfo.CurrentCulture, s, values);
+ // The reason the following overloads exist are to reduce code bloat.
+ // Since GetResourceString is basically only called when exceptions are
+ // thrown, we want the code size to be as small as possible.
+ // Using the params object[] overload works against this since the
+ // initialization of the array is done inline in the caller at the IL
+ // level. So we have overloads that simply wrap the params one, and
+ // the methods they call through to are tagged as NoInlining.
+ // In mscorlib NoInlining causes the caller and callee to not be inlined
+ // as it is an assumption of StackCrawlMark use so it is not added
+ // directly to these methods, but to the ones they call.
+ // That way they do not bloat either the IL or the generated asm.
+
+ internal static string GetResourceString(string key, object val0)
+ {
+ return GetResourceStringFormatted(key, new object[] { val0 });
}
- //The following two internal methods are not used anywhere within the framework,
+ internal static string GetResourceString(string key, object val0, object val1)
+ {
+ return GetResourceStringFormatted(key, new object[] { val0, val1 });
+ }
+
+ internal static string GetResourceString(string key, object val0, object val1, object val2)
+ {
+ return GetResourceStringFormatted(key, new object[] { val0, val1, val2 });
+ }
+
+ internal static string GetResourceString(string key, object val0, object val1, object val2, object val3)
+ {
+ return GetResourceStringFormatted(key, new object[] { val0, val1, val2, val3 });
+ }
+
+ internal static string GetResourceString(string key, object val0, object val1, object val2, object val3, object val4)
+ {
+ return GetResourceStringFormatted(key, new object[] { val0, val1, val2, val3, val4 });
+ }
+
+ internal static string GetResourceString(string key, object val0, object val1, object val2, object val3, object val4, object val5)
+ {
+ return GetResourceStringFormatted(key, new object[] { val0, val1, val2, val3, val4, val5 });
+ }
+
+ internal static String GetResourceString(string key, params object[] values)
+ {
+ return GetResourceStringFormatted(key, values);
+ }
+
+ // NoInlining causes the caller and callee to not be inlined in mscorlib as it is an assumption of StackCrawlMark use
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static String GetResourceStringFormatted(string key, params object[] values)
+ {
+ string rs = GetResourceString(key);
+ return String.Format(CultureInfo.CurrentCulture, rs, values);
+ }
+
+ // The following two internal methods are not used anywhere within the framework,
// but are being kept around as external platforms built on top of us have taken
// dependency by using private reflection on them for getting system resource strings
- internal static String GetRuntimeResourceString(String key) {
+ private static String GetRuntimeResourceString(String key) {
return GetResourceString(key);
}
- internal static String GetRuntimeResourceString(String key, params Object[] values) {
- return GetResourceString(key,values);
+ private static String GetRuntimeResourceString(String key, params Object[] values) {
+ return GetResourceStringFormatted(key,values);
}
public static bool Is64BitProcess {
@@ -1333,7 +851,6 @@ namespace System {
}
public static bool Is64BitOperatingSystem {
- [System.Security.SecuritySafeCritical]
get {
#if BIT64
// 64-bit programs run only on 64-bit
@@ -1348,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();
@@ -1375,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));
@@ -1417,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));
@@ -1428,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
@@ -1455,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 */
@@ -1499,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();
}
@@ -1517,7 +986,6 @@ namespace System {
public static string UserDomainName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
new EnvironmentPermission(EnvironmentPermissionAccess.Read,"UserDomain").Demand();
@@ -1650,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.
//
@@ -1658,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
@@ -1764,5 +1138,367 @@ namespace System {
}
}
+ internal static extern int CurrentProcessorNumber
+ {
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ get;
+ }
+
+ public static string GetEnvironmentVariable(string variable)
+ {
+ if (variable == null)
+ {
+ throw new ArgumentNullException(nameof(variable));
+ }
+
+ // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case
+ return GetEnvironmentVariableCore(variable);
+ }
+
+ public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
+ {
+ if (variable == null)
+ {
+ throw new ArgumentNullException(nameof(variable));
+ }
+
+ ValidateTarget(target);
+
+ return GetEnvironmentVariableCore(variable, target);
+ }
+
+ public static IDictionary GetEnvironmentVariables()
+ {
+ // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case
+ return GetEnvironmentVariablesCore();
+ }
+
+ public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
+ {
+ ValidateTarget(target);
+
+ return GetEnvironmentVariablesCore(target);
+ }
+
+ public static void SetEnvironmentVariable(string variable, string value)
+ {
+ ValidateVariableAndValue(variable, ref value);
+
+ // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case
+ SetEnvironmentVariableCore(variable, value);
+ }
+
+ public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
+ {
+ ValidateVariableAndValue(variable, ref value);
+ ValidateTarget(target);
+
+ SetEnvironmentVariableCore(variable, value, target);
+ }
+
+ private static void ValidateVariableAndValue(string variable, ref string value)
+ {
+ const int MaxEnvVariableValueLength = 32767;
+
+ if (variable == null)
+ {
+ throw new ArgumentNullException(nameof(variable));
+ }
+ if (variable.Length == 0)
+ {
+ throw new ArgumentException(GetResourceString("Argument_StringZeroLength"), nameof(variable));
+ }
+ if (variable[0] == '\0')
+ {
+ throw new ArgumentException(GetResourceString("Argument_StringFirstCharIsZero"), nameof(variable));
+ }
+ if (variable.Length >= MaxEnvVariableValueLength)
+ {
+ throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable));
+ }
+ if (variable.IndexOf('=') != -1)
+ {
+ throw new ArgumentException(GetResourceString("Argument_IllegalEnvVarName"), nameof(variable));
+ }
+
+ if (string.IsNullOrEmpty(value) || value[0] == '\0')
+ {
+ // Explicitly null out value if it's empty
+ value = null;
+ }
+ else if (value.Length >= MaxEnvVariableValueLength)
+ {
+ throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(value));
+ }
+ }
+
+ private static void ValidateTarget(EnvironmentVariableTarget target)
+ {
+ if (target != EnvironmentVariableTarget.Process &&
+ target != EnvironmentVariableTarget.Machine &&
+ target != EnvironmentVariableTarget.User)
+ {
+ throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(GetResourceString("Arg_EnumIllegalVal"), target));
+ }
+ }
+
+ private static Dictionary<string, string> GetRawEnvironmentVariables()
+ {
+ // Format for GetEnvironmentStrings is:
+ // (=HiddenVar=value\0 | Variable=value\0)* \0
+ // See the description of Environment Blocks in MSDN's
+ // CreateProcess page (null-terminated array of null-terminated strings).
+ // Note the =HiddenVar's aren't always at the beginning.
+
+ // Copy strings out, parsing into pairs and inserting into the table.
+ // The first few environment variable entries start with an '='.
+ // The current working directory of every drive (except for those drives
+ // you haven't cd'ed into in your DOS window) are stored in the
+ // environment block (as =C:=pwd) and the program's exit code is
+ // as well (=ExitCode=00000000).
+
+ var results = new Dictionary<string, string>();
+ char[] block = GetEnvironmentCharArray();
+ for (int i = 0; i < block.Length; i++)
+ {
+ int startKey = i;
+
+ // Skip to key. On some old OS, the environment block can be corrupted.
+ // Some will not have '=', so we need to check for '\0'.
+ while (block[i] != '=' && block[i] != '\0') i++;
+ if (block[i] == '\0') continue;
+
+ // Skip over environment variables starting with '='
+ if (i - startKey == 0)
+ {
+ while (block[i] != 0) i++;
+ continue;
+ }
+
+ string key = new string(block, startKey, i - startKey);
+ i++; // skip over '='
+
+ int startValue = i;
+ while (block[i] != 0) i++; // Read to end of this entry
+ string value = new string(block, startValue, i - startValue); // skip over 0 handled by for loop's i++
+
+ results[key] = value;
+ }
+ 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
+ }
}
}
diff --git a/src/mscorlib/src/System/Exception.cs b/src/mscorlib/src/System/Exception.cs
index 12799e7875..a8ee328f1c 100644
--- a/src/mscorlib/src/System/Exception.cs
+++ b/src/mscorlib/src/System/Exception.cs
@@ -73,11 +73,10 @@ namespace System {
_innerException = innerException;
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected Exception(SerializationInfo info, StreamingContext context)
{
if (info==null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
_className = info.GetString("ClassName");
@@ -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();
@@ -536,14 +499,19 @@ namespace System {
add { _safeSerializationManager.SerializeObjectState += value; }
remove { _safeSerializationManager.SerializeObjectState -= value; }
}
+#else
+ protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
+ {
+ add { throw new PlatformNotSupportedException();}
+ remove { throw new PlatformNotSupportedException();}
+ }
#endif // FEATURE_SERIALIZATION
- [System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -591,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
@@ -656,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;
@@ -731,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)
@@ -770,7 +723,6 @@ namespace System {
}
}
- [SecuritySafeCritical]
internal object DeepCopyDynamicMethods(object currentDynamicMethods)
{
if (currentDynamicMethods != null)
@@ -783,7 +735,6 @@ namespace System {
}
}
- [SecuritySafeCritical]
internal void GetStackTracesDeepCopy(out object currentStackTrace, out object dynamicMethodArray)
{
GetStackTracesDeepCopy(this, out currentStackTrace, out dynamicMethodArray);
@@ -791,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));
@@ -894,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
@@ -923,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);
@@ -951,7 +898,6 @@ namespace System {
}
// See comment on ExceptionMessageKind
- [System.Security.SecuritySafeCritical] // auto-generated
internal static String GetMessageFromNativeResources(ExceptionMessageKind kind)
{
string retMesg = null;
@@ -959,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
@@ -990,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
-
-
}
diff --git a/src/mscorlib/src/System/FormattableString.cs b/src/mscorlib/src/System/FormattableString.cs
index ef56bcf3e0..294b2c1846 100644
--- a/src/mscorlib/src/System/FormattableString.cs
+++ b/src/mscorlib/src/System/FormattableString.cs
@@ -67,7 +67,7 @@ namespace System
{
if (formattable == null)
{
- throw new ArgumentNullException("formattable");
+ throw new ArgumentNullException(nameof(formattable));
}
return formattable.ToString(Globalization.CultureInfo.InvariantCulture);
diff --git a/src/mscorlib/src/System/GC.cs b/src/mscorlib/src/System/GC.cs
index 73c676df7d..e338e44526 100644
--- a/src/mscorlib/src/System/GC.cs
+++ b/src/mscorlib/src/System/GC.cs
@@ -63,71 +63,56 @@ 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("bytesAllocated",
+ throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
@@ -140,15 +125,14 @@ namespace System {
_AddMemoryPressure((ulong)bytesAllocated);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void RemoveMemoryPressure (long bytesAllocated) {
if( bytesAllocated <= 0) {
- throw new ArgumentOutOfRangeException("bytesAllocated",
+ throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if( (4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue) ) {
- throw new ArgumentOutOfRangeException("bytesAllocated",
+ throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32"));
}
Contract.EndContractBlock();
@@ -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,35 +155,31 @@ 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)
{
- throw new ArgumentOutOfRangeException("generation", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(generation), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized))
{
- throw new ArgumentOutOfRangeException("mode", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(mode), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
}
Contract.EndContractBlock();
@@ -227,26 +206,24 @@ namespace System {
_Collect(generation, iInternalModes);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int CollectionCount (int generation)
{
if (generation<0)
{
- throw new ArgumentOutOfRangeException("generation", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(generation), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
Contract.EndContractBlock();
return _CollectionCount(generation, 0);
}
// 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)
{
if (generation<0)
{
- throw new ArgumentOutOfRangeException("generation", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(generation), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
Contract.EndContractBlock();
return _CollectionCount(generation, (getSpecialGCCount ? 1 : 0));
@@ -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,16 +295,14 @@ 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)
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
Contract.EndContractBlock();
_SuppressFinalize(obj);
}
@@ -340,14 +311,12 @@ 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("obj");
+ throw new ArgumentNullException(nameof(obj));
Contract.EndContractBlock();
_ReRegisterForFinalize(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,12 +366,11 @@ 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))
{
- throw new ArgumentOutOfRangeException("maxGenerationThreshold",
+ throw new ArgumentOutOfRangeException(nameof(maxGenerationThreshold),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
@@ -416,7 +380,7 @@ namespace System {
if ((largeObjectHeapThreshold <= 0) || (largeObjectHeapThreshold >= 100))
{
- throw new ArgumentOutOfRangeException("largeObjectHeapThreshold",
+ throw new ArgumentOutOfRangeException(nameof(largeObjectHeapThreshold),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
@@ -430,7 +394,6 @@ namespace System {
}
}
- [SecurityCritical]
public static void CancelFullGCNotification()
{
if (!_CancelFullGCNotification())
@@ -439,32 +402,28 @@ namespace System {
}
}
- [SecurityCritical]
public static GCNotificationStatus WaitForFullGCApproach()
{
return (GCNotificationStatus)_WaitForFullGCApproach(-1);
}
- [SecurityCritical]
public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
- throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout);
}
- [SecurityCritical]
public static GCNotificationStatus WaitForFullGCComplete()
{
return (GCNotificationStatus)_WaitForFullGCComplete(-1);
}
- [SecurityCritical]
public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
- throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
return (GCNotificationStatus)_WaitForFullGCComplete(millisecondsTimeout);
}
@@ -484,12 +443,11 @@ namespace System {
AllocationExceeded = 3
}
- [SecurityCritical]
static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
{
StartNoGCRegionStatus status = (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
if (status == StartNoGCRegionStatus.AmountTooLarge)
- throw new ArgumentOutOfRangeException("totalSize",
+ throw new ArgumentOutOfRangeException(nameof(totalSize),
"totalSize is too large. For more information about setting the maximum size, see \"Latency Modes\" in http://go.microsoft.com/fwlink/?LinkId=522706");
else if (status == StartNoGCRegionStatus.AlreadyInProgress)
throw new InvalidOperationException("The NoGCRegion mode was already in progress");
@@ -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
}
diff --git a/src/mscorlib/src/System/Globalization/Calendar.cs b/src/mscorlib/src/System/Globalization/Calendar.cs
index d6dfdc9f4b..d0460386b6 100644
--- a/src/mscorlib/src/System/Globalization/Calendar.cs
+++ b/src/mscorlib/src/System/Globalization/Calendar.cs
@@ -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
@@ -192,7 +193,7 @@ namespace System.Globalization {
[System.Runtime.InteropServices.ComVisible(false)]
public static Calendar ReadOnly(Calendar calendar)
{
- if (calendar == null) { throw new ArgumentNullException("calendar"); }
+ if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
Contract.EndContractBlock();
if (calendar.IsReadOnly) { return (calendar); }
@@ -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);
@@ -262,7 +263,7 @@ namespace System.Globalization {
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
}
long millis = (long)tempMillis;
@@ -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);
}
@@ -651,7 +652,7 @@ namespace System.Globalization {
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) {
throw new ArgumentOutOfRangeException(
- "firstDayOfWeek", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(firstDayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
@@ -664,7 +665,7 @@ namespace System.Globalization {
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
- "rule", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(rule), Environment.GetResourceString("ArgumentOutOfRange_Range",
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
@@ -815,7 +816,7 @@ namespace System.Globalization {
public virtual int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -835,7 +836,7 @@ namespace System.Globalization {
{
if (millisecond < 0 || millisecond >= MillisPerSecond) {
throw new ArgumentOutOfRangeException(
- "millisecond",
+ nameof(millisecond),
String.Format(
CultureInfo.InvariantCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 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
diff --git a/src/mscorlib/src/System/Globalization/CalendarData.cs b/src/mscorlib/src/System/Globalization/CalendarData.cs
index 8c187f0033..6f583fbcbc 100644
--- a/src/mscorlib/src/System/Globalization/CalendarData.cs
+++ b/src/mscorlib/src/System/Globalization/CalendarData.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs b/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs
index 7084511ce9..1113cd58ba 100644
--- a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs
+++ b/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs
@@ -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;
}
diff --git a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
index 63151951f9..2822b418ef 100644
--- a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
@@ -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);
}
@@ -326,10 +317,10 @@ namespace System.Globalization {
public static double GetNumericValue(String s, int index) {
if (s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
return (InternalGetNumericValue(InternalConvertToUtf32(s, index)));
@@ -361,10 +352,10 @@ namespace System.Globalization {
public static int GetDecimalDigitValue(String s, int index) {
if (s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
@@ -398,10 +389,10 @@ namespace System.Globalization {
public static int GetDigitValue(String s, int index) {
if (s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
return (InternalGetDigitValue(InternalConvertToUtf32(s, index)));
@@ -415,9 +406,9 @@ namespace System.Globalization {
public static UnicodeCategory GetUnicodeCategory(String s, int index)
{
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return InternalGetUnicodeCategory(s, index);
@@ -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);
}
@@ -467,9 +457,9 @@ namespace System.Globalization {
internal static BidiCategory GetBidiCategory(String s, int index) {
if (s==null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return ((BidiCategory)InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET));
@@ -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 ||
diff --git a/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
index a5cf37f712..6479152e09 100644
--- a/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
@@ -331,12 +331,12 @@ namespace System.Globalization {
internal override int GetGregorianYear(int year, int era) {
if (era != CurrentEra && era != ChineseEra) {
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
if (year < MIN_LUNISOLAR_YEAR || year > MAX_LUNISOLAR_YEAR) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR));
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/mscorlib/src/System/Globalization/CompareInfo.cs
index 0b14f05264..dcf1f32e4a 100644
--- a/src/mscorlib/src/System/Globalization/CompareInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.cs
@@ -32,6 +32,7 @@ namespace System.Globalization {
using System.Security.Permissions;
using Microsoft.Win32;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
@@ -135,7 +136,7 @@ namespace System.Globalization {
public static CompareInfo GetCompareInfo(int culture, Assembly assembly){
// Parameter checking.
if (assembly == null) {
- throw new ArgumentNullException("assembly");
+ throw new ArgumentNullException(nameof(assembly));
}
if (assembly!=typeof(Object).Module.Assembly) {
throw new ArgumentException(Environment.GetResourceString("Argument_OnlyMscorlib"));
@@ -161,7 +162,7 @@ namespace System.Globalization {
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(String name, Assembly assembly){
if (name == null || assembly == null) {
- throw new ArgumentNullException(name == null ? "name" : "assembly");
+ throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly));
}
Contract.EndContractBlock();
@@ -189,7 +190,7 @@ namespace System.Globalization {
if (CultureData.IsCustomCultureId(culture))
{
// Customized culture cannot be created by the LCID.
- throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", "culture"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", nameof(culture)));
}
return CultureInfo.GetCultureInfo(culture).CompareInfo;
@@ -209,7 +210,7 @@ namespace System.Globalization {
{
if (name == null)
{
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
@@ -221,12 +222,11 @@ namespace System.Globalization {
return(IsSortable(ch.ToString()));
}
- [System.Security.SecuritySafeCritical]
[System.Runtime.InteropServices.ComVisible(false)]
public static bool IsSortable(String text) {
if (text == null) {
// A null param is invalid here.
- throw new ArgumentNullException("text");
+ throw new ArgumentNullException(nameof(text));
}
if (0 == text.Length) {
@@ -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,12 +321,7 @@ namespace System.Globalization {
{
get
{
- Contract.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set");
- if (m_name == "zh-CHT" || m_name == "zh-CHS")
- {
- return m_name;
- }
-
+ Debug.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set");
return (m_sortName);
}
}
@@ -352,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;
@@ -367,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 |
@@ -375,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;
}
@@ -398,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)
@@ -411,14 +405,14 @@ namespace System.Globalization {
{
if (options != CompareOptions.Ordinal)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_CompareOptionOrdinal"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_CompareOptionOrdinal"), nameof(options));
}
return String.CompareOrdinal(string1, string2);
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
}
//Our paradigm is that null sorts less than any other string and
@@ -469,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)
@@ -483,31 +476,31 @@ namespace System.Globalization {
// Verify inputs
if (length1 < 0 || length2 < 0)
{
- throw new ArgumentOutOfRangeException((length1 < 0) ? "length1" : "length2", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if (offset1 < 0 || offset2 < 0)
{
- throw new ArgumentOutOfRangeException((offset1 < 0) ? "offset1" : "offset2", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if (offset1 > (string1 == null ? 0 : string1.Length) - length1)
{
- throw new ArgumentOutOfRangeException("string1", Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
+ throw new ArgumentOutOfRangeException(nameof(string1), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
}
if (offset2 > (string2 == null ? 0 : string2.Length) - length2)
{
- throw new ArgumentOutOfRangeException("string2", Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
+ throw new ArgumentOutOfRangeException(nameof(string2), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
}
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(Environment.GetResourceString("Argument_CompareOptionOrdinal"),
- "options");
+ nameof(options));
}
}
else if ((options & ValidCompareMaskOffFlags) != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
}
//
@@ -546,11 +539,10 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual bool IsPrefix(String source, String prefix, CompareOptions options)
{
if (source == null || prefix == null) {
- throw new ArgumentNullException((source == null ? "source" : "prefix"),
+ throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -572,7 +564,7 @@ namespace System.Globalization {
}
if ((options & ValidIndexMaskOffFlags) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
}
@@ -601,11 +593,10 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual bool IsSuffix(String source, String suffix, CompareOptions options)
{
if (source == null || suffix == null) {
- throw new ArgumentNullException((source == null ? "source" : "suffix"),
+ throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -625,7 +616,7 @@ namespace System.Globalization {
}
if ((options & ValidIndexMaskOffFlags) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
}
// to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to
@@ -659,7 +650,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, char value)
{
if (source==null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
@@ -669,7 +660,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, String value)
{
if (source==null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
@@ -679,7 +670,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, char value, CompareOptions options)
{
if (source==null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
@@ -689,7 +680,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, String value, CompareOptions options)
{
if (source==null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
@@ -699,7 +690,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, char value, int startIndex)
{
if (source == null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
@@ -709,7 +700,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, String value, int startIndex)
{
if (source == null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
@@ -719,7 +710,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, char value, int startIndex, CompareOptions options)
{
if (source == null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
@@ -729,7 +720,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, String value, int startIndex, CompareOptions options)
{
if (source == null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
@@ -747,18 +738,17 @@ 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
if (source == null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
if (startIndex < 0 || startIndex > source.Length)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count < 0 || startIndex > source.Length - count)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
Contract.EndContractBlock();
if (options == CompareOptions.OrdinalIgnoreCase)
@@ -769,7 +759,7 @@ namespace System.Globalization {
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
// to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to
// the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString.
@@ -780,18 +770,17 @@ 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
if (source == null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
if (startIndex > source.Length)
{
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
@@ -808,11 +797,11 @@ namespace System.Globalization {
if (startIndex < 0)
{
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (count < 0 || startIndex > source.Length - count)
- throw new ArgumentOutOfRangeException("count",Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count),Environment.GetResourceString("ArgumentOutOfRange_Count"));
if (options == CompareOptions.OrdinalIgnoreCase)
{
@@ -822,7 +811,7 @@ namespace System.Globalization {
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
// to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to
// the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString.
@@ -849,7 +838,7 @@ namespace System.Globalization {
public unsafe virtual int LastIndexOf(String source, char value)
{
if (source==null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
@@ -861,7 +850,7 @@ namespace System.Globalization {
public virtual int LastIndexOf(String source, String value)
{
if (source==null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
@@ -873,7 +862,7 @@ namespace System.Globalization {
public virtual int LastIndexOf(String source, char value, CompareOptions options)
{
if (source==null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
@@ -884,7 +873,7 @@ namespace System.Globalization {
public unsafe virtual int LastIndexOf(String source, String value, CompareOptions options)
{
if (source==null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
@@ -929,12 +918,11 @@ 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
if (source==null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Validate CompareOptions
@@ -942,7 +930,7 @@ namespace System.Globalization {
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
@@ -950,7 +938,7 @@ namespace System.Globalization {
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
@@ -962,7 +950,7 @@ namespace System.Globalization {
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
if (options == CompareOptions.OrdinalIgnoreCase)
{
@@ -978,14 +966,13 @@ 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
if (source == null)
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Validate CompareOptions
@@ -993,7 +980,7 @@ namespace System.Globalization {
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
@@ -1001,7 +988,7 @@ namespace System.Globalization {
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
@@ -1017,7 +1004,7 @@ namespace System.Globalization {
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
if (options == CompareOptions.OrdinalIgnoreCase)
{
@@ -1051,10 +1038,9 @@ namespace System.Globalization {
return CreateSortKey(source, CompareOptions.None);
}
- [System.Security.SecuritySafeCritical]
private SortKey CreateSortKey(String source, CompareOptions options)
{
- if (source==null) { throw new ArgumentNullException("source"); }
+ if (source==null) { throw new ArgumentNullException(nameof(source)); }
Contract.EndContractBlock();
// Mask used to check if we have the right flags.
@@ -1067,7 +1053,7 @@ namespace System.Globalization {
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
}
byte[] keyData = null;
// The OS doesn't have quite the same behavior so we have to test for empty inputs
@@ -1088,7 +1074,7 @@ namespace System.Globalization {
// If there was an error, return an error
if (length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "source");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(source));
}
// If input was empty, return the empty byte[] we made earlier and skip this
@@ -1157,7 +1143,7 @@ namespace System.Globalization {
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (options == CompareOptions.Ordinal)
@@ -1207,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)
{
//
@@ -1215,12 +1200,12 @@ namespace System.Globalization {
//
if(null == source)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if ((options & ValidHashCodeOfStringMaskOffFlags) != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
}
Contract.EndContractBlock();
@@ -1259,39 +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();
- }
- }
-
[OptionalField(VersionAdded = 3)]
private SortVersion m_SortVersion;
public SortVersion Version
{
- [SecuritySafeCritical]
get
{
if(m_SortVersion == null)
@@ -1306,38 +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);
- [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,
@@ -1345,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);
diff --git a/src/mscorlib/src/System/Globalization/CultureData.cs b/src/mscorlib/src/System/Globalization/CultureData.cs
index ae1eeea298..0bcb796152 100644
--- a/src/mscorlib/src/System/Globalization/CultureData.cs
+++ b/src/mscorlib/src/System/Globalization/CultureData.cs
@@ -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;
@@ -451,8 +448,8 @@ namespace System.Globalization
invariant.iDefaultOemCodePage = 437; // default oem code page ID (OCP or OEM)
invariant.iDefaultMacCodePage = 10000; // default macintosh code page
invariant.iDefaultEbcdicCodePage = 037; // default EBCDIC code page
- invariant.sAbbrevLang = "IVL"; // abbreviated language name (Windows Language Name)
- invariant.sAbbrevCountry = "IVC"; // abbreviated country name (RegionInfo) (Windows Region Name)
+ invariant.sAbbrevLang = "IVL"; // abbreviated language name (Windows Language Name)
+ invariant.sAbbrevCountry = "IVC"; // abbreviated country name (RegionInfo) (Windows Region Name)
invariant.sISO639Language2 = "ivl"; // 3 char ISO 639 lang name 2
invariant.sISO3166CountryName2 = "ivc"; // 3 char ISO 3166 country name 2 2(RegionInfo)
invariant.iInputLanguageHandle = 0x007f; // input language handle
@@ -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);
}
@@ -906,7 +682,7 @@ namespace System.Globalization
// If not successful, throw
if (retVal == null)
throw new CultureNotFoundException(
- "culture", culture, Environment.GetResourceString("Argument_CultureNotSupported"));
+ nameof(culture), culture, Environment.GetResourceString("Argument_CultureNotSupported"));
// Return the one we found
return retVal;
@@ -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
@@ -933,7 +708,7 @@ namespace System.Globalization
CultureTypes.FrameworkCultures)) != 0)
{
throw new ArgumentOutOfRangeException(
- "types",
+ nameof(types),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), CultureTypes.NeutralCultures, CultureTypes.FrameworkCultures));
@@ -972,25 +747,12 @@ namespace System.Globalization
int arrayLength = cultureNames.Length;
- if ((types & (CultureTypes.NeutralCultures | CultureTypes.FrameworkCultures)) != 0) // add zh-CHT and zh-CHS
- {
- arrayLength += 2;
- }
-
CultureInfo[] cultures = new CultureInfo[arrayLength];
for (int i = 0; i < cultureNames.Length; i++)
{
cultures[i] = new CultureInfo(cultureNames[i]);
}
-
- 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");
- }
-
#pragma warning restore 618
return cultures;
@@ -1028,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)
{
@@ -1041,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;
}
@@ -1065,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.
@@ -1093,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)
{
@@ -1106,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;
}
@@ -1139,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))
{
@@ -1180,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)
@@ -1189,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
{
@@ -1233,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)
@@ -1242,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))
@@ -1287,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;
}
}
@@ -1299,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)
@@ -1313,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)
@@ -1327,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)
@@ -1342,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)
@@ -1365,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)
@@ -1379,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);
}
@@ -1399,15 +1085,6 @@ namespace System.Globalization
}
}
-#if !FEATURE_CORECLR
- private bool IsIncorrectNativeLanguageForSinhala()
- {
- return IsOsWin7OrPrior()
- && (sName == "si-LK" || sName == "si")
- && !IsReplacementCulture;
- }
-#endif
-
///////////
// Region //
///////////
@@ -1415,7 +1092,6 @@ namespace System.Globalization
// region name (eg US)
internal String SREGIONNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sRegionName == null)
@@ -1451,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))
{
@@ -1484,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)
@@ -1498,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)
@@ -1512,7 +1178,6 @@ namespace System.Globalization
// ISO 3166 Country Name
internal String SISO3166CTRYNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sISO3166CountryName == null)
@@ -1526,7 +1191,6 @@ namespace System.Globalization
// ISO 3166 Country Name
internal String SISO3166CTRYNAME2
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sISO3166CountryName2 == null)
@@ -1540,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)
@@ -1584,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)
@@ -1624,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)
@@ -1642,7 +1303,6 @@ namespace System.Globalization
// Not a Number
internal String SNAN
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sNaN == null)
@@ -1656,7 +1316,6 @@ namespace System.Globalization
// + Infinity
internal String SPOSINFINITY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sPositiveInfinity == null)
@@ -1670,7 +1329,6 @@ namespace System.Globalization
// - Infinity
internal String SNEGINFINITY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sNegativeInfinity == null)
@@ -1717,7 +1375,6 @@ namespace System.Globalization
// Percent (%) symbol
internal String SPERCENT
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sPercent == null)
@@ -1732,7 +1389,6 @@ namespace System.Globalization
// PerMille (‰) symbol
internal String SPERMILLE
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sPerMille == null)
@@ -1751,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)
@@ -1765,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)
@@ -1779,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)
@@ -1793,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)
@@ -1811,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)
@@ -1845,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)
@@ -1872,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)
@@ -1886,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)
@@ -2067,7 +1715,6 @@ namespace System.Globalization
// time duration format
internal String[] SADURATION
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.saDurationFormats == null)
@@ -2198,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.
@@ -2243,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);
@@ -2253,7 +1899,6 @@ namespace System.Globalization
temp[0] = i;
}
}
-#endif
this.waCalendars = temp;
}
@@ -2272,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
@@ -2291,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;
}
@@ -2344,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);
}
@@ -2361,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)
@@ -2387,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)
@@ -2423,7 +2058,6 @@ namespace System.Globalization
private String SSCRIPTS
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (this.sScripts == null)
@@ -2436,7 +2070,6 @@ namespace System.Globalization
private String SOPENTYPELANGUAGETAG
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return DoGetLocaleInfo(LOCALE_SOPENTYPELANGUAGETAG);
@@ -2445,7 +2078,6 @@ namespace System.Globalization
private String FONTSIGNATURE
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (this.fontSignature == null)
@@ -2458,7 +2090,6 @@ namespace System.Globalization
private String SKEYBOARDSTOINSTALL
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return DoGetLocaleInfo(LOCALE_SKEYBOARDSTOINSTALL);
@@ -2516,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);
@@ -2528,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;
@@ -2584,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;
}
@@ -2610,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)
@@ -2856,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)
{
@@ -2892,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
@@ -2911,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)
{
@@ -2932,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;
@@ -2941,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;
@@ -2950,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;
@@ -2975,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)
@@ -3013,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);
}
@@ -3056,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)
@@ -3333,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);
diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs
index d620d2dc24..9f306c3c99 100644
--- a/src/mscorlib/src/System/Globalization/CultureInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs
@@ -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,10 +85,8 @@ namespace System.Globalization {
#if FEATURE_LEAK_CULTURE_INFO
[NonSerialized]private bool m_isSafeCrossDomain;
[NonSerialized]private int m_createdDomainID;
-#endif // !FEATURE_CORECLR
-#if !FEATURE_CORECLR
+#endif // !FEATURE_LEAK_CULTURE_INFO
[NonSerialized]private CultureInfo m_consoleFallbackCulture;
-#endif // !FEATURE_CORECLR
// Names are confusing. Here are 3 names we have:
//
@@ -152,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]
@@ -197,7 +191,6 @@ namespace System.Globalization {
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
static CultureInfo InitUserDefaultCulture()
{
String strDefault = GetDefaultLocaleName(LOCALE_USER_DEFAULT);
@@ -241,7 +234,6 @@ namespace System.Globalization {
}
#if FEATURE_APPX
- [SecuritySafeCritical]
internal static CultureInfo GetCultureInfoForUserPreferredLanguageInAppX()
{
// If a call to GetCultureInfoForUserPreferredLanguageInAppX() generated a recursive
@@ -287,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
@@ -323,7 +314,7 @@ namespace System.Globalization {
public CultureInfo(String name, bool useUserOverride) {
if (name==null) {
- throw new ArgumentNullException("name",
+ throw new ArgumentNullException(nameof(name),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -332,7 +323,7 @@ namespace System.Globalization {
this.m_cultureData = CultureData.GetCultureData(name, useUserOverride);
if (this.m_cultureData == null) {
- throw new CultureNotFoundException("name", name, Environment.GetResourceString("Argument_CultureNotSupported"));
+ throw new CultureNotFoundException(nameof(name), name, Environment.GetResourceString("Argument_CultureNotSupported"));
}
this.m_name = this.m_cultureData.CultureName;
@@ -347,7 +338,7 @@ namespace System.Globalization {
public CultureInfo(int culture, bool useUserOverride) {
// We don't check for other invalid LCIDS here...
if (culture < 0) {
- throw new ArgumentOutOfRangeException("culture",
+ throw new ArgumentOutOfRangeException(nameof(culture),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
Contract.EndContractBlock();
@@ -367,7 +358,7 @@ namespace System.Globalization {
// Can't support unknown custom cultures and we do not support neutral or
// non-custom user locales.
throw new CultureNotFoundException(
- "culture", culture, Environment.GetResourceString("Argument_CultureNotSupported"));
+ nameof(culture), culture, Environment.GetResourceString("Argument_CultureNotSupported"));
default:
// Now see if this LCID is supported in the system default CultureData table.
@@ -413,18 +404,18 @@ 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)
throw new CultureNotFoundException(
- "m_name", m_name, Environment.GetResourceString("Argument_CultureNotSupported"));
+ nameof(m_name), m_name, Environment.GetResourceString("Argument_CultureNotSupported"));
#if FEATURE_USE_LCID
}
@@ -486,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;
}
}
@@ -540,7 +531,7 @@ namespace System.Globalization {
internal CultureInfo(String cultureName, String textAndCompareCultureName)
{
if (cultureName==null) {
- throw new ArgumentNullException("cultureName",
+ throw new ArgumentNullException(nameof(cultureName),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -548,7 +539,7 @@ namespace System.Globalization {
this.m_cultureData = CultureData.GetCultureData(cultureName, false);
if (this.m_cultureData == null)
throw new CultureNotFoundException(
- "cultureName", cultureName, Environment.GetResourceString("Argument_CultureNotSupported"));
+ nameof(cultureName), cultureName, Environment.GetResourceString("Argument_CultureNotSupported"));
this.m_name = this.m_cultureData.CultureName;
@@ -644,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.
@@ -672,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
@@ -695,13 +683,12 @@ namespace System.Globalization {
s_DefaultThreadCurrentCulture ??
s_userDefaultCulture ??
UserDefaultCulture;
-#endif
}
set {
#if FEATURE_APPX
if (value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
if (AppDomain.IsAppXModel()) {
@@ -770,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
@@ -793,13 +777,12 @@ namespace System.Globalization {
s_DefaultThreadCurrentUICulture ??
s_userDefaultUICulture ??
UserDefaultUICulture;
-#endif
}
set {
#if FEATURE_APPX
if (value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
if (AppDomain.IsAppXModel()) {
@@ -843,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
@@ -861,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,
@@ -915,24 +890,23 @@ namespace System.Globalization {
public virtual CultureInfo Parent
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
+ CultureInfo culture = null;
if (null == m_parent)
{
try
{
string parentName = this.m_cultureData.SPARENT;
-
if (String.IsNullOrEmpty(parentName))
{
- m_parent = InvariantCulture;
+ culture = InvariantCulture;
}
else
{
- m_parent = new CultureInfo(parentName, this.m_cultureData.UseUserOverride);
+ culture = new CultureInfo(parentName, this.m_cultureData.UseUserOverride);
}
}
catch (ArgumentException)
@@ -940,8 +914,10 @@ namespace System.Globalization {
// For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant
// We can't allow ourselves to fail. In case of custom cultures the parent of the
// current custom culture isn't installed.
- m_parent = InvariantCulture;
+ culture = InvariantCulture;
}
+
+ Interlocked.CompareExchange<CultureInfo>(ref m_parent, culture, null);
}
return m_parent;
}
@@ -1034,7 +1010,6 @@ namespace System.Globalization {
}
}
-#if !FEATURE_CORECLR
[System.Runtime.InteropServices.ComVisible(false)]
public String IetfLanguageTag
{
@@ -1054,7 +1029,6 @@ namespace System.Globalization {
}
}
}
-#endif
////////////////////////////////////////////////////////////////////////
//
@@ -1067,11 +1041,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;
}
@@ -1087,7 +1060,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);
@@ -1104,7 +1076,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);
@@ -1113,7 +1084,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);
@@ -1122,7 +1092,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);
@@ -1138,7 +1107,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);
@@ -1178,31 +1146,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
@@ -1294,7 +1237,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;
}
@@ -1315,7 +1258,6 @@ namespace System.Globalization {
}
}
-#if !FEATURE_CORECLR
[System.Runtime.InteropServices.ComVisible(false)]
public CultureTypes CultureTypes
{
@@ -1333,15 +1275,14 @@ namespace System.Globalization {
// Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete
#pragma warning disable 618
types |= m_cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0;
-
#pragma warning restore 618
+
types |= m_cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0;
types |= m_cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0;
return types;
}
}
-#endif
public virtual NumberFormatInfo NumberFormat {
get
@@ -1351,13 +1292,13 @@ namespace System.Globalization {
if (numInfo == null) {
NumberFormatInfo temp = new NumberFormatInfo(this.m_cultureData);
temp.isReadOnly = m_isReadOnly;
- numInfo = temp;
+ Interlocked.CompareExchange(ref numInfo, temp, null);
}
return (numInfo);
}
set {
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
@@ -1385,15 +1326,14 @@ namespace System.Globalization {
DateTimeFormatInfo temp = new DateTimeFormatInfo(
this.m_cultureData, this.Calendar);
temp.m_isReadOnly = m_isReadOnly;
- System.Threading.Thread.MemoryBarrier();
- dateTimeInfo = temp;
+ Interlocked.CompareExchange(ref dateTimeInfo, temp, null);
}
return (dateTimeInfo);
}
set {
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
@@ -1402,17 +1342,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;
@@ -1438,7 +1377,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
@@ -1490,7 +1429,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;
@@ -1534,8 +1473,6 @@ namespace System.Globalization {
}
}
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public CultureInfo GetConsoleFallbackUICulture()
{
@@ -1550,7 +1487,6 @@ namespace System.Globalization {
}
return (temp);
}
-#endif
public virtual Object Clone()
{
@@ -1595,7 +1531,7 @@ namespace System.Globalization {
public static CultureInfo ReadOnly(CultureInfo ci) {
if (ci == null) {
- throw new ArgumentNullException("ci");
+ throw new ArgumentNullException(nameof(ci));
}
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.EndContractBlock();
@@ -1827,7 +1763,7 @@ namespace System.Globalization {
// the altCulture code path for SQL Server.
// Also check for zero as this would fail trying to add as a key to the hash.
if (culture <= 0) {
- throw new ArgumentOutOfRangeException("culture",
+ throw new ArgumentOutOfRangeException(nameof(culture),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
Contract.Ensures(Contract.Result<CultureInfo>() != null);
@@ -1836,7 +1772,7 @@ namespace System.Globalization {
if (null == retval)
{
throw new CultureNotFoundException(
- "culture", culture, Environment.GetResourceString("Argument_CultureNotSupported"));
+ nameof(culture), culture, Environment.GetResourceString("Argument_CultureNotSupported"));
}
return retval;
}
@@ -1849,7 +1785,7 @@ namespace System.Globalization {
// Make sure we have a valid, non-zero length string as name
if (name == null)
{
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
}
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.EndContractBlock();
@@ -1858,7 +1794,7 @@ namespace System.Globalization {
if (retval == null)
{
throw new CultureNotFoundException(
- "name", name, Environment.GetResourceString("Argument_CultureNotSupported"));
+ nameof(name), name, Environment.GetResourceString("Argument_CultureNotSupported"));
}
return retval;
@@ -1871,12 +1807,12 @@ namespace System.Globalization {
// Make sure we have a valid, non-zero length string as name
if (null == name)
{
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
}
if (null == altName)
{
- throw new ArgumentNullException("altName");
+ throw new ArgumentNullException(nameof(altName));
}
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.EndContractBlock();
@@ -1884,7 +1820,7 @@ namespace System.Globalization {
CultureInfo retval = GetCultureInfoHelper(-1, name, altName);
if (retval == null)
{
- throw new CultureNotFoundException("name or altName",
+ throw new CultureNotFoundException(nameof(name) + " or " + nameof(altName),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Argument_OneOfCulturesNotSupported"),
@@ -1904,7 +1840,7 @@ namespace System.Globalization {
if (name == "zh-CHT" || name == "zh-CHS")
{
throw new CultureNotFoundException(
- "name",
+ nameof(name),
String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
);
}
@@ -1915,7 +1851,7 @@ namespace System.Globalization {
if (ci.LCID > 0xffff || ci.LCID == 0x040a)
{
throw new CultureNotFoundException(
- "name",
+ nameof(name),
String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
);
}
@@ -1943,22 +1879,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)))
@@ -1969,13 +1901,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;
@@ -1987,13 +1917,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;
@@ -2005,19 +1933,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
}
}
diff --git a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs b/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
index 0486cc9d17..17c0b43f9c 100644
--- a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
+++ b/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
@@ -66,10 +66,9 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
base.GetObjectData(info, context);
diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs b/src/mscorlib/src/System/Globalization/DateTimeFormat.cs
index 228e5f56a2..c6e0591a74 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeFormat.cs
@@ -11,6 +11,7 @@ namespace System {
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
/*
@@ -139,8 +140,13 @@ namespace System {
internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK";
internal const String RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz";
- private const int DEFAULT_ALL_DATETIMES_SIZE = 132;
-
+ private const int DEFAULT_ALL_DATETIMES_SIZE = 132;
+
+ internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat;
+ internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames;
+ internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames;
+ internal const string Gmt = "GMT";
+
internal static String[] fixedNumberFormats = new String[] {
"0",
"00",
@@ -166,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.
@@ -218,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));
@@ -230,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));
@@ -271,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)));
@@ -703,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('-');
@@ -739,7 +733,7 @@ namespace System {
// 'zzz*' or longer format e.g "-07:30"
result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes);
}
- }
+ }
}
// output the 'K' format, which is for round-tripping the data
@@ -775,7 +769,9 @@ namespace System {
offset = offset.Negate();
}
- result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}:{1:00}", offset.Hours, offset.Minutes);
+ AppendNumber(result, offset.Hours, 2);
+ result.Append(':');
+ AppendNumber(result, offset.Minutes, 2);
}
@@ -957,12 +953,101 @@ namespace System {
}
if (format.Length == 1) {
+ switch (format[0])
+ {
+ case 'O':
+ case 'o':
+ return FastFormatRoundtrip(dateTime, offset);
+ case 'R':
+ case 'r':
+ return FastFormatRfc1123(dateTime, offset, dtfi);
+ }
+
format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset);
- }
+ }
return (FormatCustomized(dateTime, format, dtfi, offset));
}
-
+
+ internal static string FastFormatRfc1123(DateTime dateTime, TimeSpan offset, DateTimeFormatInfo dtfi)
+ {
+ // ddd, dd MMM yyyy HH:mm:ss GMT
+ const int Rfc1123FormatLength = 29;
+ StringBuilder result = StringBuilderCache.Acquire(Rfc1123FormatLength);
+
+ if (offset != NullOffset)
+ {
+ // Convert to UTC invariants
+ dateTime = dateTime - offset;
+ }
+
+ result.Append(InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]);
+ result.Append(',');
+ result.Append(' ');
+ AppendNumber(result, dateTime.Day, 2);
+ result.Append(' ');
+ result.Append(InvariantAbbreviatedMonthNames[dateTime.Month - 1]);
+ result.Append(' ');
+ AppendNumber(result, dateTime.Year, 4);
+ result.Append(' ');
+ AppendHHmmssTimeOfDay(result, dateTime);
+ result.Append(' ');
+ result.Append(Gmt);
+
+ return StringBuilderCache.GetStringAndRelease(result);
+ }
+
+ internal static string FastFormatRoundtrip(DateTime dateTime, TimeSpan offset)
+ {
+ // yyyy-MM-ddTHH:mm:ss.fffffffK
+ const int roundTripFormatLength = 28;
+ StringBuilder result = StringBuilderCache.Acquire(roundTripFormatLength);
+
+ AppendNumber(result, dateTime.Year, 4);
+ result.Append('-');
+ AppendNumber(result, dateTime.Month, 2);
+ result.Append('-');
+ AppendNumber(result, dateTime.Day, 2);
+ result.Append('T');
+ AppendHHmmssTimeOfDay(result, dateTime);
+ result.Append('.');
+
+ long fraction = dateTime.Ticks % TimeSpan.TicksPerSecond;
+ AppendNumber(result, fraction, 7);
+
+ FormatCustomizedRoundripTimeZone(dateTime, offset, result);
+
+ return StringBuilderCache.GetStringAndRelease(result);
+ }
+
+ private static void AppendHHmmssTimeOfDay(StringBuilder result, DateTime dateTime)
+ {
+ // HH:mm:ss
+ AppendNumber(result, dateTime.Hour, 2);
+ result.Append(':');
+ AppendNumber(result, dateTime.Minute, 2);
+ result.Append(':');
+ AppendNumber(result, dateTime.Second, 2);
+ }
+
+ internal static void AppendNumber(StringBuilder builder, long val, int digits)
+ {
+ for (int i = 0; i < digits; i++)
+ {
+ builder.Append('0');
+ }
+
+ int index = 1;
+ while (val > 0 && index <= digits)
+ {
+ builder[builder.Length - index] = (char)('0' + (val % 10));
+ val = val / 10;
+ index++;
+ }
+
+ Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
+ }
+
internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
{
Contract.Requires(dtfi != null);
@@ -1042,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();
diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
index 00c2d1f439..14cdeb60e9 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
@@ -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;
//
@@ -181,18 +182,6 @@ namespace System.Globalization {
// genitive form or leap year month names.
[OptionalField(VersionAdded = 2)]
internal DateTimeFormatFlags formatFlags = DateTimeFormatFlags.NotInitialized;
- internal static bool preferExistingTokens = InitPreferExistingTokens();
-
-
- [System.Security.SecuritySafeCritical]
- static bool InitPreferExistingTokens()
- {
- bool ret = false;
-#if !FEATURE_CORECLR
- ret = DateTime.LegacyParseMode();
-#endif
- return ret;
- }
private String CultureName
{
@@ -220,7 +209,6 @@ namespace System.Globalization {
private String LanguageName
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (m_langName == null)
@@ -243,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);
}
@@ -266,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);
}
@@ -283,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);
}
@@ -300,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);
@@ -319,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");
}
@@ -347,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; }
@@ -367,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
@@ -411,7 +395,7 @@ namespace System.Globalization {
if (this.m_cultureData == null)
throw new CultureNotFoundException(
- "m_name", m_name, Environment.GetResourceString("Argument_CultureNotSupported"));
+ nameof(m_name), m_name, Environment.GetResourceString("Argument_CultureNotSupported"));
}
// Note: This is for Everett compatibility
@@ -458,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.
@@ -561,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);
}
@@ -582,7 +557,7 @@ namespace System.Globalization {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null)
{
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -596,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);
}
@@ -604,7 +579,7 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
@@ -694,7 +669,7 @@ namespace System.Globalization {
}
// The assigned calendar is not a valid calendar for this culture, throw
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("Argument_InvalidCalendar"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("Argument_InvalidCalendar"));
}
}
@@ -718,7 +693,7 @@ namespace System.Globalization {
public int GetEra(String eraName) {
if (eraName == null) {
- throw new ArgumentNullException("eraName",
+ throw new ArgumentNullException(nameof(eraName),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -795,7 +770,7 @@ namespace System.Globalization {
if ((--era) < EraNames.Length && (era >= 0)) {
return (m_eraNames[era]);
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
internal String[] AbbreviatedEraNames
@@ -823,7 +798,7 @@ namespace System.Globalization {
if ((--era) < m_abbrevEraNames.Length && (era >= 0)) {
return (m_abbrevEraNames[era]);
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
internal String[] AbbreviatedEnglishEraNames
@@ -832,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);
@@ -846,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);
}
@@ -862,7 +836,7 @@ namespace System.Globalization {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null)
{
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -876,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);
}
@@ -894,7 +866,7 @@ namespace System.Globalization {
firstDayOfWeek = (int)value;
} else {
throw new ArgumentOutOfRangeException(
- "value", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
}
@@ -905,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);
}
@@ -922,7 +893,7 @@ namespace System.Globalization {
calendarWeekRule = (int)value;
} else {
throw new ArgumentOutOfRangeException(
- "value", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Range",
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
}
@@ -945,7 +916,7 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -977,7 +948,7 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -1016,7 +987,7 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -1042,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,7 +1024,7 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -1065,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);
}
@@ -1084,7 +1051,7 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -1128,7 +1095,7 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null)
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
Contract.EndContractBlock();
@@ -1168,7 +1135,7 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -1292,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);
}
@@ -1308,7 +1274,7 @@ namespace System.Globalization {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null)
{
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -1349,7 +1315,7 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -1388,11 +1354,11 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
if (value.Length != 7) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value));
}
Contract.EndContractBlock();
CheckNullValue(value, value.Length);
@@ -1416,12 +1382,12 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
if (value.Length != 7)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value));
}
Contract.EndContractBlock();
CheckNullValue(value, value.Length);
@@ -1441,12 +1407,12 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
if (value.Length != 7)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value));
}
Contract.EndContractBlock();
CheckNullValue(value, value.Length);
@@ -1466,12 +1432,12 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
if (value.Length != 13)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value));
}
Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
@@ -1492,12 +1458,12 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null) {
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
if (value.Length != 13)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value));
}
Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
@@ -1556,7 +1522,7 @@ namespace System.Globalization {
// (actually is 13 right now for all cases)
if ((month < 1) || (month > monthNamesArray.Length)) {
throw new ArgumentOutOfRangeException(
- "month", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
1, monthNamesArray.Length));
}
return (monthNamesArray[month-1]);
@@ -1575,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);
@@ -1584,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);
@@ -1600,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);
@@ -1614,7 +1580,7 @@ namespace System.Globalization {
if ((int)dayofweek < 0 || (int)dayofweek > 6) {
throw new ArgumentOutOfRangeException(
- "dayofweek", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(dayofweek), Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
@@ -1633,7 +1599,7 @@ namespace System.Globalization {
if ((int)dayOfWeek < 0 || (int)dayOfWeek > 6) {
throw new ArgumentOutOfRangeException(
- "dayOfWeek", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(dayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
@@ -1740,7 +1706,7 @@ namespace System.Globalization {
result = this.AllYearMonthPatterns;
break;
default:
- throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), "format");
+ throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), nameof(format));
}
return (result);
}
@@ -1750,7 +1716,7 @@ namespace System.Globalization {
{
if ((int)dayofweek < 0 || (int)dayofweek > 6) {
throw new ArgumentOutOfRangeException(
- "dayofweek", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(dayofweek), Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
@@ -1765,7 +1731,7 @@ namespace System.Globalization {
{
if (month < 1 || month > 13) {
throw new ArgumentOutOfRangeException(
- "month", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
1, 13));
}
Contract.EndContractBlock();
@@ -1778,7 +1744,7 @@ namespace System.Globalization {
{
if (month < 1 || month > 13) {
throw new ArgumentOutOfRangeException(
- "month", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
1, 13));
}
Contract.EndContractBlock();
@@ -1795,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
@@ -1894,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");
}
@@ -1913,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");
}
@@ -1931,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");
}
@@ -1950,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");
}
@@ -1967,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");
}
@@ -1977,7 +1943,7 @@ namespace System.Globalization {
public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi) {
if (dtfi == null) {
- throw new ArgumentNullException("dtfi",
+ throw new ArgumentNullException(nameof(dtfi),
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
@@ -2038,13 +2004,13 @@ namespace System.Globalization {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (patterns == null) {
- throw new ArgumentNullException("patterns",
+ throw new ArgumentNullException(nameof(patterns),
Environment.GetResourceString("ArgumentNull_Array"));
}
if (patterns.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayZeroError"), "patterns");
+ throw new ArgumentException(Environment.GetResourceString("Arg_ArrayZeroError"), nameof(patterns));
}
Contract.EndContractBlock();
@@ -2086,7 +2052,7 @@ namespace System.Globalization {
break;
default:
- throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), "format");
+ throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), nameof(format));
}
// Clear the token hash table, note that even short dates could require this
@@ -2109,12 +2075,12 @@ namespace System.Globalization {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null)
{
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
if (value.Length != 13)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value));
}
Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
@@ -2137,12 +2103,12 @@ namespace System.Globalization {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null)
{
- throw new ArgumentNullException("value",
+ throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
if (value.Length != 13)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value));
}
Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
@@ -2396,7 +2362,6 @@ namespace System.Globalization {
formatFlags = DateTimeFormatFlags.NotInitialized;
}
- [System.Security.SecurityCritical] // auto-generated
internal TokenHashValue[] CreateTokenHashTable() {
TokenHashValue[] temp = m_dtfiTokenHash;
if (temp == null) {
@@ -2689,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) {
@@ -2710,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);
@@ -2825,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) {
@@ -2877,35 +2841,13 @@ namespace System.Globalization {
int nTokenType = (int)tokenType;
int nCurrentTokenTypeInHash = (int)value.tokenType;
- // The idea behind this check is:
- // - if the app is targetting 4.5.1 or above OR the compat flag is set, use the correct behavior by default.
- // - if the app is targetting 4.5 or below AND the compat switch is set, use the correct behavior
- // - if the app is targetting 4.5 or below AND the compat switch is NOT set, use the incorrect behavior
- if (preferExistingTokens || BinaryCompatibility.TargetsAtLeast_Desktop_V4_5_1)
+ if (((nCurrentTokenTypeInHash & (int)TokenType.RegularTokenMask) == 0) && ((nTokenType & (int)TokenType.RegularTokenMask) != 0) ||
+ ((nCurrentTokenTypeInHash & (int)TokenType.SeparatorTokenMask) == 0) && ((nTokenType & (int)TokenType.SeparatorTokenMask) != 0))
{
- if (((nCurrentTokenTypeInHash & (int)TokenType.RegularTokenMask) == 0) && ((nTokenType & (int)TokenType.RegularTokenMask) != 0) ||
- ((nCurrentTokenTypeInHash & (int)TokenType.SeparatorTokenMask) == 0) && ((nTokenType & (int)TokenType.SeparatorTokenMask) != 0))
- {
- value.tokenType |= tokenType;
- if (tokenValue != 0)
- {
- value.tokenValue = tokenValue;
- }
- }
- }
- else
- {
- // The following logic is incorrect and causes updates to happen depending on the bitwise relationship between the existing token type and the
- // the stored token type. It was this way in .NET 4 RTM. The behavior above is correct and will be adopted going forward.
-
- if ((((nTokenType | nCurrentTokenTypeInHash) & (int)TokenType.RegularTokenMask) == nTokenType) ||
- (((nTokenType | nCurrentTokenTypeInHash) & (int)TokenType.SeparatorTokenMask) == nTokenType))
+ value.tokenType |= tokenType;
+ if (tokenValue != 0)
{
- value.tokenType |= tokenType;
- if (tokenValue != 0)
- {
- value.tokenValue = tokenValue;
- }
+ value.tokenValue = tokenValue;
}
}
// The token to be inserted is already in the table. Skip it.
@@ -2918,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
diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs b/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs
index 40cbabc096..4555bb2463 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs
@@ -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');
diff --git a/src/mscorlib/src/System/Globalization/DateTimeParse.cs b/src/mscorlib/src/System/Globalization/DateTimeParse.cs
index 8de3242f30..363747cfc3 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeParse.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeParse.cs
@@ -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();
@@ -97,11 +87,11 @@ namespace System {
internal static bool TryParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) {
if (s == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
return false;
}
if (format == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "format");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(format));
return false;
}
if (s.Length == 0) {
@@ -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);
}
@@ -178,11 +168,11 @@ namespace System {
internal static bool TryParseExactMultiple(String s, String[] formats,
DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) {
if (s == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
return false;
}
if (formats == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "formats");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(formats));
return false;
}
@@ -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,10 +2291,9 @@ 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, "s");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
return false;
}
if (s.Length == 0) {
@@ -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];
}
diff --git a/src/mscorlib/src/System/Globalization/DaylightTime.cs b/src/mscorlib/src/System/Globalization/DaylightTime.cs
index 037d9ffdf3..a164867576 100644
--- a/src/mscorlib/src/System/Globalization/DaylightTime.cs
+++ b/src/mscorlib/src/System/Globalization/DaylightTime.cs
@@ -2,12 +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.
-namespace System.Globalization {
-
- using System;
+using System.Runtime.InteropServices;
+
+namespace System.Globalization
+{
// This class represents a starting/ending time for a period of daylight saving time.
[Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
+ [ComVisible(true)]
public class DaylightTime
{
internal DateTime m_start;
@@ -46,4 +47,18 @@ namespace System.Globalization {
}
+ // Value type version of DaylightTime
+ internal struct DaylightTimeStruct
+ {
+ public DaylightTimeStruct(DateTime start, DateTime end, TimeSpan delta)
+ {
+ Start = start;
+ End = end;
+ Delta = delta;
+ }
+
+ public DateTime Start { get; }
+ public DateTime End { get; }
+ public TimeSpan Delta { get; }
+ }
}
diff --git a/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs
index 2460eee3af..3c9391fa63 100644
--- a/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs
@@ -65,7 +65,7 @@ namespace System.Globalization {
public int GetCelestialStem(int sexagenaryYear) {
if ((sexagenaryYear < 1) || (sexagenaryYear > 60)) {
throw new ArgumentOutOfRangeException(
- "sexagenaryYear",
+ nameof(sexagenaryYear),
Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 60));
}
Contract.EndContractBlock();
@@ -80,7 +80,7 @@ namespace System.Globalization {
public int GetTerrestrialBranch(int sexagenaryYear) {
if ((sexagenaryYear < 1) || (sexagenaryYear > 60)) {
throw new ArgumentOutOfRangeException(
- "sexagenaryYear",
+ nameof(sexagenaryYear),
Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 60));
}
Contract.EndContractBlock();
@@ -121,7 +121,7 @@ namespace System.Globalization {
return (mEraInfo[i].minEraYear);
}
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
internal int MaxEraCalendarYear (int era) {
@@ -144,7 +144,7 @@ namespace System.Globalization {
return (mEraInfo[i].maxEraYear);
}
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
// Construct an instance of EastAsianLunisolar calendar.
@@ -168,7 +168,7 @@ namespace System.Globalization {
}
if ((era <GetEra(MinDate)) || (era > GetEra(MaxDate))) {
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
}
@@ -178,7 +178,7 @@ namespace System.Globalization {
if ((year < MinCalendarYear) || (year > MaxCalendarYear)) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_Range", MinEraCalendarYear(era), MaxEraCalendarYear(era)));
}
return year;
@@ -191,11 +191,11 @@ namespace System.Globalization {
{
//Reject if there is no leap month this year
if (GetYearInfo(year , LeapMonth) == 0)
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
if (month < 1 || month > 13) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
return year;
}
@@ -236,7 +236,7 @@ namespace System.Globalization {
if (day < 1 || day > daysInMonth) {
BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
Environment.GetResourceString("ArgumentOutOfRange_Day", daysInMonth, month));
}
@@ -399,7 +399,7 @@ namespace System.Globalization {
public override DateTime AddMonths(DateTime time, int months) {
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
- "months",
+ nameof(months),
Environment.GetResourceString("ArgumentOutOfRange_Range", -120000, 120000));
}
Contract.EndContractBlock();
@@ -561,7 +561,7 @@ namespace System.Globalization {
if (day < 1 || day > daysInMonth) {
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
Environment.GetResourceString("ArgumentOutOfRange_Day", daysInMonth, month));
}
int m = GetYearInfo(year, LeapMonth);
@@ -620,7 +620,7 @@ namespace System.Globalization {
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
- "value",
+ nameof(value),
Environment.GetResourceString("ArgumentOutOfRange_Range", 99, MaxCalendarYear));
}
twoDigitYearMax = value;
@@ -630,7 +630,7 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs
index 1dc1bd2eaf..89ac780587 100644
--- a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs
@@ -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
@@ -62,7 +60,7 @@ namespace System.Globalization {
}
}
- throw new ArgumentException("pStrings");
+ throw new ArgumentException(null, nameof(pStrings));
}
else
{
@@ -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);
diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs
index 5628a2def9..0fce2e58fc 100644
--- a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs
@@ -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;
@@ -30,7 +31,7 @@ namespace System.Globalization
{
if (name == null)
{
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
@@ -44,7 +45,7 @@ namespace System.Globalization
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_EncodingNotSupported"), name), "name");
+ Environment.GetResourceString("Argument_EncodingNotSupported"), name), nameof(name));
}
internal static CodePageDataItem GetCodePageDataItem(int codepage)
@@ -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}",
diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.cs b/src/mscorlib/src/System/Globalization/EncodingTable.cs
index cdda9eaf6d..d908a2ac2b 100644
--- a/src/mscorlib/src/System/Globalization/EncodingTable.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingTable.cs
@@ -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;
@@ -94,11 +90,10 @@ namespace System.Globalization
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_EncodingNotSupported"), name), "name");
+ Environment.GetResourceString("Argument_EncodingNotSupported"), name), nameof(name));
}
// 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)
@@ -136,7 +131,7 @@ namespace System.Globalization
internal static int GetCodePageFromName(String name)
{
if (name==null) {
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
@@ -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;
}
diff --git a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
index 4de3fd399b..0810d67b59 100644
--- a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
+++ b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
@@ -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,
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
index e540adda9f..6cf9b2eb85 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
@@ -132,7 +132,7 @@ namespace System.Globalization {
public GregorianCalendar(GregorianCalendarTypes type) {
if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) {
throw new ArgumentOutOfRangeException(
- "type",
+ nameof(type),
Environment.GetResourceString("ArgumentOutOfRange_Range",
GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench));
}
@@ -159,7 +159,7 @@ namespace System.Globalization {
break;
default:
- throw new ArgumentOutOfRangeException("m_type", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(m_type), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
}
}
}
@@ -217,7 +217,7 @@ namespace System.Globalization {
int[] days = leapYear? DaysToMonth366: DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
- int m = n >> 5 + 1;
+ int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
@@ -285,7 +285,7 @@ namespace System.Globalization {
{
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
- "months",
+ nameof(months),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -371,16 +371,16 @@ namespace System.Globalization {
public override int GetDaysInMonth(int year, int month, int era) {
if (era == CurrentEra || era == ADEra) {
if (year < 1 || year > MaxYear) {
- throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range",
1, MaxYear));
}
if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365);
return (days[month] - days[month - 1]);
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
// Returns the number of days in the year given by the year argument for the current era.
@@ -393,14 +393,14 @@ namespace System.Globalization {
return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365);
}
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
MaxYear));
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
// Returns the era for the specified DateTime value.
@@ -437,14 +437,14 @@ namespace System.Globalization {
return (12);
}
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
MaxYear));
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
// Returns the year part of the specified DateTime. The returned value is an
@@ -463,23 +463,23 @@ namespace System.Globalization {
public override bool IsLeapDay(int year, int month, int day, int era)
{
if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
1, 12));
}
Contract.EndContractBlock();
if (era != CurrentEra && era != ADEra)
{
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
if (year < 1 || year > MaxYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear));
}
if (day < 1 || day > GetDaysInMonth(year, month)) {
- throw new ArgumentOutOfRangeException("day", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ throw new ArgumentOutOfRangeException(nameof(day), Environment.GetResourceString("ArgumentOutOfRange_Range",
1, GetDaysInMonth(year, month)));
}
if (!IsLeapYear(year)) {
@@ -500,11 +500,11 @@ namespace System.Globalization {
{
if (era != CurrentEra && era != ADEra)
{
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
if (year < 1 || year > MaxYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
@@ -520,19 +520,19 @@ namespace System.Globalization {
public override bool IsLeapMonth(int year, int month, int era)
{
if (era != CurrentEra && era != ADEra) {
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
if (year < 1 || year > MaxYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
}
if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
1, 12));
}
Contract.EndContractBlock();
@@ -551,12 +551,12 @@ namespace System.Globalization {
}
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
@@ -567,7 +567,7 @@ namespace System.Globalization {
if (era == CurrentEra || era == ADEra) {
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) {
@@ -609,14 +609,14 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (year > MaxYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
index 75b280d457..062ae4818a 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
@@ -153,7 +153,7 @@ namespace System.Globalization {
internal int GetGregorianYear(int year, int era) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -166,7 +166,7 @@ namespace System.Globalization {
if (era == m_EraInfo[i].era) {
if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -176,7 +176,7 @@ namespace System.Globalization {
return (m_EraInfo[i].yearOffset + year);
}
}
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
internal bool IsValidYear(int year, int era) {
@@ -243,7 +243,7 @@ namespace System.Globalization {
int[] days = leapYear? DaysToMonth366: DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
- int m = n >> 5 + 1;
+ int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
@@ -299,7 +299,7 @@ namespace System.Globalization {
{
if (millisecond < 0 || millisecond >= MillisPerSecond) {
throw new ArgumentOutOfRangeException(
- "millisecond",
+ nameof(millisecond),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -346,7 +346,7 @@ namespace System.Globalization {
{
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
- "months",
+ nameof(months),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -432,7 +432,7 @@ namespace System.Globalization {
//
year = GetGregorianYear(year, era);
if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365);
return (days[month] - days[month - 1]);
@@ -460,7 +460,7 @@ namespace System.Globalization {
return (m_EraInfo[i].era);
}
}
- throw new ArgumentOutOfRangeException("time", Environment.GetResourceString("ArgumentOutOfRange_Era"));
+ throw new ArgumentOutOfRangeException(nameof(time), Environment.GetResourceString("ArgumentOutOfRange_Era"));
}
@@ -533,7 +533,7 @@ namespace System.Globalization {
// year/month/era checking is done in GetDaysInMonth()
if (day < 1 || day > GetDaysInMonth(year, month, era)) {
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -570,7 +570,7 @@ namespace System.Globalization {
year = GetGregorianYear(year, era);
if (month < 1 || month > 12) {
throw new ArgumentOutOfRangeException(
- "month",
+ nameof(month),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -607,7 +607,7 @@ namespace System.Globalization {
public int ToFourDigitYear(int year, int twoDigitYearMax) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
Contract.EndContractBlock();
@@ -619,7 +619,7 @@ namespace System.Globalization {
if (year < m_minYear || year > m_maxYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), m_minYear, m_maxYear));
diff --git a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
index 3a17494001..44cbdb8bde 100644
--- a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
@@ -5,6 +5,7 @@
namespace System.Globalization {
using System;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
@@ -397,7 +398,7 @@ namespace System.Globalization {
int monthsInYear = GetMonthsInYear(year, era);
if (month < 1 || month > monthsInYear) {
throw new ArgumentOutOfRangeException(
- "month",
+ nameof(month),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -421,7 +422,7 @@ namespace System.Globalization {
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth) {
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -432,7 +433,7 @@ namespace System.Globalization {
static internal void CheckEraRange(int era) {
if (era != CurrentEra && era != HebrewEra) {
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
}
@@ -486,7 +487,7 @@ namespace System.Globalization {
//
int index = gregorianYear - FirstGregorianTableYear;
if (index < 0 || index > TABLESIZE) {
- throw new ArgumentOutOfRangeException("gregorianYear");
+ throw new ArgumentOutOfRangeException(nameof(gregorianYear));
}
index *= 2;
@@ -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.
@@ -705,7 +706,7 @@ namespace System.Globalization {
catch (ArgumentException)
{
throw new ArgumentOutOfRangeException(
- "months",
+ nameof(months),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_AddValue")));
@@ -727,7 +728,7 @@ namespace System.Globalization {
int d = GetDatePart(time.Ticks, DatePartDay);
y += years;
- CheckHebrewYearValue(y, Calendar.CurrentEra, "years");
+ CheckHebrewYearValue(y, Calendar.CurrentEra, nameof(years));
int months = GetMonthsInYear(y, CurrentEra);
if (m > months) {
@@ -765,7 +766,7 @@ namespace System.Globalization {
}
static internal int GetHebrewYearType(int year, int era) {
- CheckHebrewYearValue(year, era, "year");
+ CheckHebrewYearValue(year, era, nameof(year));
// The HebrewTable is indexed by Gregorian year and starts from FirstGregorianYear.
// So we need to convert year (Hebrew year value) to Gregorian Year below.
return (HebrewTable[(year - HebrewYearOf1AD - FirstGregorianTableYear) * 2 + 1]);
@@ -811,11 +812,11 @@ 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) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
return (monthDays);
}
@@ -931,7 +932,7 @@ namespace System.Globalization {
//
public override bool IsLeapYear(int year, int era) {
- CheckHebrewYearValue(year, era, "year");
+ CheckHebrewYearValue(year, era, nameof(year));
return (((7 * (long)year + 1) % 19) < 7);
}
@@ -1015,7 +1016,7 @@ namespace System.Globalization {
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- CheckHebrewYearValue(year, era, "year");
+ CheckHebrewYearValue(year, era, nameof(year));
CheckHebrewMonthValue(year, month, era);
CheckHebrewDayValue(year, month, day, era);
DateTime dt = HebrewToGregorian(year, month, day, hour, minute, second, millisecond);
@@ -1042,7 +1043,7 @@ namespace System.Globalization {
}
else
{
- CheckHebrewYearValue(value, HebrewEra, "value");
+ CheckHebrewYearValue(value, HebrewEra, nameof(value));
}
twoDigitYearMax = value;
}
@@ -1051,7 +1052,7 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -1062,7 +1063,7 @@ namespace System.Globalization {
if (year > MaxHebrewYear || year < MinHebrewYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
diff --git a/src/mscorlib/src/System/Globalization/HebrewNumber.cs b/src/mscorlib/src/System/Globalization/HebrewNumber.cs
index cf0595585a..5517cb14ea 100644
--- a/src/mscorlib/src/System/Globalization/HebrewNumber.cs
+++ b/src/mscorlib/src/System/Globalization/HebrewNumber.cs
@@ -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.
diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.cs
index 194d329d25..39a01e5774 100644
--- a/src/mscorlib/src/System/Globalization/HijriCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/HijriCalendar.cs
@@ -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.
@@ -222,7 +221,7 @@ namespace System.Globalization {
// NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good.
if (value < MinAdvancedHijri || value > MaxAdvancedHijri) {
throw new ArgumentOutOfRangeException(
- "HijriAdjustment",
+ nameof(HijriAdjustment),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
@@ -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
@@ -320,7 +318,7 @@ namespace System.Globalization {
static internal void CheckEraRange(int era) {
if (era != CurrentEra && era != HijriEra) {
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
}
@@ -328,7 +326,7 @@ namespace System.Globalization {
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -342,7 +340,7 @@ namespace System.Globalization {
if (year == MaxCalendarYear) {
if (month > MaxCalendarMonth) {
throw new ArgumentOutOfRangeException(
- "month",
+ nameof(month),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -352,7 +350,7 @@ namespace System.Globalization {
}
if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
@@ -465,7 +463,7 @@ namespace System.Globalization {
public override DateTime AddMonths(DateTime time, int months) {
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
- "months",
+ nameof(months),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -602,7 +600,7 @@ namespace System.Globalization {
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth) {
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Day"),
@@ -650,7 +648,7 @@ namespace System.Globalization {
if (day < 1 || day > daysInMonth) {
BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Day"),
@@ -683,7 +681,7 @@ namespace System.Globalization {
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
- "value",
+ nameof(value),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -698,7 +696,7 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -709,7 +707,7 @@ namespace System.Globalization {
if (year > MaxCalendarYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
diff --git a/src/mscorlib/src/System/Globalization/IdnMapping.cs b/src/mscorlib/src/System/Globalization/IdnMapping.cs
index 599a32ad87..bf75f5be3c 100644
--- a/src/mscorlib/src/System/Globalization/IdnMapping.cs
+++ b/src/mscorlib/src/System/Globalization/IdnMapping.cs
@@ -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
@@ -125,23 +126,22 @@ namespace System.Globalization
public String GetAscii(String unicode, int index)
{
- if (unicode==null) throw new ArgumentNullException("unicode");
+ if (unicode==null) throw new ArgumentNullException(nameof(unicode));
Contract.EndContractBlock();
return GetAscii(unicode, index, unicode.Length - index);
}
- public String GetAscii(String unicode, int index, int count)
+ public string GetAscii(String unicode, int index, int count)
{
- throw null;
- /*if (unicode==null) throw new ArgumentNullException("unicode");
+ if (unicode == null) throw new ArgumentNullException(nameof(unicode));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count",
+ throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (index > unicode.Length)
- throw new ArgumentOutOfRangeException("byteIndex",
+ throw new ArgumentOutOfRangeException(nameof(index),
Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (index > unicode.Length - count)
- throw new ArgumentOutOfRangeException("unicode",
+ throw new ArgumentOutOfRangeException(nameof(unicode),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
@@ -161,12 +161,12 @@ 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(
Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length-1 ),
- "unicode");
+ nameof(unicode));
}
// Have to correctly IDNA normalize the string and Unassigned flags
@@ -178,7 +178,7 @@ namespace System.Globalization
if ((!bHasLastDot) && unicode.Length > 0 && IsDot(unicode[unicode.Length - 1]))
{
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "unicode");
+ "Argument_IdnBadLabelSize"), nameof(unicode));
}
// May need to check Std3 rules again for non-ascii
@@ -188,24 +188,23 @@ namespace System.Globalization
}
// Go ahead and encode it
- return punycode_encode(unicode);*/
+ return punycode_encode(unicode);
}
- [System.Security.SecuritySafeCritical]
private String GetAsciiUsingOS(String unicode)
{
if (unicode.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "unicode");
+ "Argument_IdnBadLabelSize"), nameof(unicode));
}
if (unicode[unicode.Length - 1] == 0)
{
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length - 1),
- "unicode");
+ nameof(unicode));
}
uint flags = (uint) ((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
@@ -218,10 +217,10 @@ namespace System.Globalization
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "unicode");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode));
}
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), "unicode");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode));
}
char [] output = new char[length];
@@ -232,10 +231,10 @@ namespace System.Globalization
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "unicode");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode));
}
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), "unicode");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode));
}
return new String(output, 0, length);
@@ -249,30 +248,30 @@ namespace System.Globalization
public String GetUnicode(String ascii, int index)
{
- if (ascii==null) throw new ArgumentNullException("ascii");
+ if (ascii==null) throw new ArgumentNullException(nameof(ascii));
Contract.EndContractBlock();
return GetUnicode(ascii, index, ascii.Length - index);
}
public String GetUnicode(String ascii, int index, int count)
{
- if (ascii==null) throw new ArgumentNullException("ascii");
+ if (ascii==null) throw new ArgumentNullException(nameof(ascii));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count",
+ throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (index > ascii.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (index > ascii.Length - count)
- throw new ArgumentOutOfRangeException("ascii",
+ throw new ArgumentOutOfRangeException(nameof(ascii),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
// This is a case (i.e. explicitly null-terminated input) where behavior in .NET and Win32 intentionally differ.
// The .NET APIs should (and did in v4.0 and earlier) throw an ArgumentException on input that includes a terminating null.
// The Win32 APIs fail on an embedded null, but not on a terminating null.
if (count > 0 && ascii[index + count - 1] == (char)0)
- throw new ArgumentException("ascii",
- Environment.GetResourceString("Argument_IdnBadPunycode"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"),
+ nameof(ascii));
Contract.EndContractBlock();
// We're only using part of the string
@@ -289,13 +288,12 @@ namespace System.Globalization
// Output name MUST obey IDNA rules & round trip (casing differences are allowed)
if (!ascii.Equals(GetAscii(strUnicode), StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnIllegalName"), "ascii");
+ "Argument_IdnIllegalName"), nameof(ascii));
return strUnicode;
}
- [System.Security.SecuritySafeCritical]
private string GetUnicodeUsingOS(string ascii)
{
uint flags = (uint)((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
@@ -307,10 +305,10 @@ namespace System.Globalization
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "ascii");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
}
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii));
}
char [] output = new char[length];
@@ -321,10 +319,10 @@ namespace System.Globalization
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "ascii");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
}
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii));
}
return new String(output, 0, length);
@@ -370,7 +368,7 @@ namespace System.Globalization
// If its empty, then its too small
if (unicode.Length == 0)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "unicode");
+ "Argument_IdnBadLabelSize"), nameof(unicode));
Contract.EndContractBlock();
int iLastDot = -1;
@@ -383,7 +381,7 @@ namespace System.Globalization
{
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequence", i ),
- "unicode");
+ nameof(unicode));
}
// If its Unicode or a control character, return false (non-ascii)
@@ -396,12 +394,12 @@ namespace System.Globalization
// Can't have 2 dots in a row
if (i == iLastDot + 1)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "unicode");
+ "Argument_IdnBadLabelSize"), nameof(unicode));
// If its too far between dots then fail
if (i - iLastDot > M_labelLimit + 1)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "Unicode");
+ "Argument_IdnBadLabelSize"), nameof(unicode));
// If validating Std3, then char before dot can't be - char
if (bUseStd3 && i > 0)
@@ -422,14 +420,14 @@ namespace System.Globalization
// If we never had a dot, then we need to be shorter than the label limit
if (iLastDot == -1 && unicode.Length > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "unicode");
+ "Argument_IdnBadLabelSize"), nameof(unicode));
// Need to validate entire string length, 1 shorter if last char wasn't a dot
if (unicode.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1])? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)),
- "unicode");
+ nameof(unicode));
// If last char wasn't a dot we need to check for trailing -
if (bUseStd3 && !IsDot(unicode[unicode.Length-1]))
@@ -510,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');
@@ -547,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)
@@ -555,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));
}
@@ -592,7 +590,7 @@ namespace System.Globalization
// 0 length strings aren't allowed
if (unicode.Length == 0)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "unicode");
+ "Argument_IdnBadLabelSize"), nameof(unicode));
Contract.EndContractBlock();
StringBuilder output = new StringBuilder(unicode.Length);
@@ -605,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;
@@ -615,7 +613,7 @@ namespace System.Globalization
// Only allowed to have empty sections as trailing .
if (iNextDot != unicode.Length)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "unicode");
+ "Argument_IdnBadLabelSize"), nameof(unicode));
// Last dot, stop
break;
}
@@ -645,7 +643,7 @@ namespace System.Globalization
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), "unicode");
+ "Argument_IdnBadBidi"), nameof(unicode));
}
}
@@ -655,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
@@ -666,7 +664,7 @@ namespace System.Globalization
{
// Oops, throw error
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), "unicode");
+ "Argument_IdnBadBidi"), nameof(unicode));
}
// If we're not RTL we can't have RTL chars
@@ -675,7 +673,7 @@ namespace System.Globalization
{
// Oops, throw error
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), "unicode");
+ "Argument_IdnBadBidi"), nameof(unicode));
}
// If its basic then add it
@@ -704,7 +702,7 @@ namespace System.Globalization
unicode.Substring(iAfterLastDot, M_strAcePrefix.Length).Equals(
M_strAcePrefix, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), "unicode");
+ "Argument_IdnBadPunycode"), nameof(unicode));
// Need to do ACE encoding
int numSurrogatePairs = 0; // number of surrogate pairs so far
@@ -739,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)
@@ -753,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)
@@ -765,9 +763,11 @@ 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");
- output.Append(encode_digit(t + (q - t) % (punycodeBase - t)));
- q = (q - t) / (punycodeBase - 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);
+ output.Append(encode_digit(t + mod));
}
output.Append(encode_digit(q));
@@ -784,14 +784,14 @@ 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");
}
}
// Make sure its not too big
if (output.Length - iOutputAfterLastDot > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "unicode");
+ "Argument_IdnBadLabelSize"), nameof(unicode));
// Done with this segment, add dot if necessary
if (iNextDot != unicode.Length)
@@ -806,7 +806,7 @@ namespace System.Globalization
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)),
- "unicode");
+ nameof(unicode));
// Return our output string
return output.ToString();
@@ -840,14 +840,14 @@ namespace System.Globalization
// 0 length strings aren't allowed
if (ascii.Length == 0)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "ascii");
+ "Argument_IdnBadLabelSize"), nameof(ascii));
Contract.EndContractBlock();
// Throw if we're too long
if (ascii.Length > M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
- M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), "ascii");
+ M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), nameof(ascii));
// output stringbuilder
StringBuilder output = new StringBuilder(ascii.Length);
@@ -870,7 +870,7 @@ namespace System.Globalization
// Only allowed to have empty sections as trailing .
if (iNextDot != ascii.Length)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "ascii");
+ "Argument_IdnBadLabelSize"), nameof(ascii));
// Last dot, stop
break;
@@ -879,7 +879,7 @@ namespace System.Globalization
// In either case it can't be bigger than segment size
if (iNextDot - iAfterLastDot > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "ascii");
+ "Argument_IdnBadLabelSize"), nameof(ascii));
// See if this section's ASCII or ACE
if (ascii.Length < M_strAcePrefix.Length + iAfterLastDot ||
@@ -893,7 +893,7 @@ namespace System.Globalization
// // Only ASCII is allowed
// if (ascii[i] >= 0x80)
// throw new ArgumentException(Environment.GetResourceString(
- // "Argument_IdnBadPunycode"), "ascii");
+ // "Argument_IdnBadPunycode"), nameof(ascii));
// }
// Its ASCII, copy it
@@ -913,7 +913,7 @@ namespace System.Globalization
// Trailing - not allowed
if (iTemp == iNextDot - 1)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), "ascii");
+ "Argument_IdnBadPunycode"), nameof(ascii));
int numBasicCodePoints;
if (iTemp <= iAfterLastDot)
@@ -931,7 +931,7 @@ namespace System.Globalization
// Make sure we don't allow unicode in the ascii part
if (ascii[copyAscii] > 0x7f)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), "ascii");
+ "Argument_IdnBadPunycode"), nameof(ascii));
// When appending make sure they get lower cased
output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ?
@@ -970,24 +970,24 @@ namespace System.Globalization
// Check to make sure we aren't overrunning our ascii string
if (asciiIndex >= iNextDot)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), "ascii");
+ "Argument_IdnBadPunycode"), nameof(ascii));
// 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"), "ascii");
+ "Argument_IdnBadPunycode"), nameof(ascii));
i += (int)(digit * w);
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"), "ascii");
+ "Argument_IdnBadPunycode"), nameof(ascii));
w *= (punycodeBase - t);
}
@@ -996,11 +996,11 @@ 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(
- "Argument_IdnBadPunycode"), "ascii");
+ "Argument_IdnBadPunycode"), nameof(ascii));
n += (int)(i / (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1));
i %= (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1);
@@ -1016,7 +1016,7 @@ namespace System.Globalization
// Make sure n is legal
if ((n < 0 || n > 0x10ffff) || (n >= 0xD800 && n <= 0xDFFF))
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), "ascii");
+ "Argument_IdnBadPunycode"), nameof(ascii));
// insert n at position i of the output: Really tricky if we have surrogates
int iUseInsertLocation;
@@ -1034,7 +1034,7 @@ namespace System.Globalization
// If its a surrogate, we have to go one more
if (iUseInsertLocation >= output.Length)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), "ascii");
+ "Argument_IdnBadPunycode"), nameof(ascii));
if (Char.IsSurrogate(output[iUseInsertLocation]))
iUseInsertLocation++;
}
@@ -1079,7 +1079,7 @@ namespace System.Globalization
(!bRightToLeft && (eBidi == BidiCategory.RightToLeft ||
eBidi == BidiCategory.RightToLeftArabic)))
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), "ascii");
+ "Argument_IdnBadBidi"), nameof(ascii));
// Make it lower case if we must (so we can test IsNormalized later)
// if (output[iTest] >= 'A' && output[iTest] <= 'Z')
@@ -1091,14 +1091,14 @@ namespace System.Globalization
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), "ascii");
+ "Argument_IdnBadBidi"), nameof(ascii));
}
}
// See if this label was too long
if (iNextDot - iAfterLastDot > M_labelLimit)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), "ascii");
+ "Argument_IdnBadLabelSize"), nameof(ascii));
// Done with this segment, add dot if necessary
if (iNextDot != ascii.Length)
@@ -1112,7 +1112,7 @@ namespace System.Globalization
if (output.Length > M_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadNameSize",
- M_defaultNameLimit -(IsDot(output[output.Length-1]) ? 0 : 1)), "ascii");
+ M_defaultNameLimit -(IsDot(output[output.Length-1]) ? 0 : 1)), nameof(ascii));
// Return our output string
return output.ToString();
@@ -1157,9 +1157,8 @@ namespace System.Globalization
private const int ERROR_INVALID_NAME = 123;
- [System.Security.SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
- [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
+ [DllImport("normaliz.dll", CharSet=CharSet.Unicode, SetLastError=true)]
private static extern int IdnToAscii(
uint dwFlags,
[InAttribute()]
@@ -1171,9 +1170,8 @@ namespace System.Globalization
char [] lpASCIICharStr,
int cchASCIIChar);
- [System.Security.SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
- [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
+ [DllImport("normaliz.dll", CharSet=CharSet.Unicode, SetLastError=true)]
private static extern int IdnToUnicode(
uint dwFlags,
[InAttribute()]
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
index 2984d08ab3..6b168ce916 100644
--- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
@@ -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
@@ -491,14 +490,14 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year <= 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
Contract.EndContractBlock();
if (year > helper.MaxYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
diff --git a/src/mscorlib/src/System/Globalization/JulianCalendar.cs b/src/mscorlib/src/System/Globalization/JulianCalendar.cs
index 9c8db3415c..db286e0363 100644
--- a/src/mscorlib/src/System/Globalization/JulianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/JulianCalendar.cs
@@ -112,7 +112,7 @@ namespace System.Globalization {
static internal void CheckEraRange(int era) {
if (era != CurrentEra && era != JulianEra) {
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
}
@@ -120,7 +120,7 @@ namespace System.Globalization {
CheckEraRange(era);
if (year <= 0 || year > MaxYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -131,7 +131,7 @@ namespace System.Globalization {
static internal void CheckMonthRange(int month) {
if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
@@ -159,7 +159,7 @@ namespace System.Globalization {
int monthDays = days[month] - days[month - 1];
if (day < 1 || day > monthDays) {
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -204,7 +204,7 @@ namespace System.Globalization {
int[] days = leapYear? DaysToMonth366: DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
- int m = n >> 5 + 1;
+ int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
@@ -230,7 +230,7 @@ namespace System.Globalization {
{
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
- "months",
+ nameof(months),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -377,7 +377,7 @@ namespace System.Globalization {
CheckDayRange(year, month, day);
if (millisecond < 0 || millisecond >= MillisPerSecond) {
throw new ArgumentOutOfRangeException(
- "millisecond",
+ nameof(millisecond),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -420,14 +420,14 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (year > MaxYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
diff --git a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs b/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
index 9343884445..dde82b6e6b 100644
--- a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
@@ -254,7 +254,7 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs
index eb0a810864..9e36b435e7 100644
--- a/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs
@@ -1267,12 +1267,12 @@ namespace System.Globalization {
internal override int GetGregorianYear(int year, int era)
{
if (era != CurrentEra && era != GregorianEra)
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
if (year < MIN_LUNISOLAR_YEAR || year > MAX_LUNISOLAR_YEAR)
{
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR));
diff --git a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs b/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
index fae91c2a1d..a5dce46aa4 100644
--- a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
+++ b/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
@@ -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)
@@ -316,7 +294,7 @@ namespace System.Globalization {
set {
if (value < 0 || value > 99) {
throw new ArgumentOutOfRangeException(
- "CurrencyDecimalDigits",
+ nameof(CurrencyDecimalDigits),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -376,7 +354,7 @@ namespace System.Globalization {
}
set {
if (value == null) {
- throw new ArgumentNullException("CurrencyGroupSizes",
+ throw new ArgumentNullException(nameof(CurrencyGroupSizes),
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
@@ -397,7 +375,7 @@ namespace System.Globalization {
}
set {
if (value == null) {
- throw new ArgumentNullException("NumberGroupSizes",
+ throw new ArgumentNullException(nameof(NumberGroupSizes),
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
@@ -416,7 +394,7 @@ namespace System.Globalization {
}
set {
if (value == null) {
- throw new ArgumentNullException("PercentGroupSizes",
+ throw new ArgumentNullException(nameof(PercentGroupSizes),
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
@@ -443,7 +421,7 @@ namespace System.Globalization {
get { return currencySymbol; }
set {
if (value == null) {
- throw new ArgumentNullException("CurrencySymbol",
+ throw new ArgumentNullException(nameof(CurrencySymbol),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -475,7 +453,7 @@ namespace System.Globalization {
}
set {
if (value == null) {
- throw new ArgumentNullException("NaNSymbol",
+ throw new ArgumentNullException(nameof(NaNSymbol),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -491,7 +469,7 @@ namespace System.Globalization {
set {
if (value < 0 || value > 15) {
throw new ArgumentOutOfRangeException(
- "CurrencyNegativePattern",
+ nameof(CurrencyNegativePattern),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -513,7 +491,7 @@ namespace System.Globalization {
//
if (value < 0 || value > 4) {
throw new ArgumentOutOfRangeException(
- "NumberNegativePattern",
+ nameof(NumberNegativePattern),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -535,7 +513,7 @@ namespace System.Globalization {
//
if (value < 0 || value > 3) {
throw new ArgumentOutOfRangeException(
- "PercentPositivePattern",
+ nameof(PercentPositivePattern),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -557,7 +535,7 @@ namespace System.Globalization {
//
if (value < 0 || value > 11) {
throw new ArgumentOutOfRangeException(
- "PercentNegativePattern",
+ nameof(PercentNegativePattern),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -577,7 +555,7 @@ namespace System.Globalization {
}
set {
if (value == null) {
- throw new ArgumentNullException("NegativeInfinitySymbol",
+ throw new ArgumentNullException(nameof(NegativeInfinitySymbol),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -591,7 +569,7 @@ namespace System.Globalization {
get { return negativeSign; }
set {
if (value == null) {
- throw new ArgumentNullException("NegativeSign",
+ throw new ArgumentNullException(nameof(NegativeSign),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -606,7 +584,7 @@ namespace System.Globalization {
set {
if (value < 0 || value > 99) {
throw new ArgumentOutOfRangeException(
- "NumberDecimalDigits",
+ nameof(NumberDecimalDigits),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -645,7 +623,7 @@ namespace System.Globalization {
set {
if (value < 0 || value > 3) {
throw new ArgumentOutOfRangeException(
- "CurrencyPositivePattern",
+ nameof(CurrencyPositivePattern),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -665,7 +643,7 @@ namespace System.Globalization {
}
set {
if (value == null) {
- throw new ArgumentNullException("PositiveInfinitySymbol",
+ throw new ArgumentNullException(nameof(PositiveInfinitySymbol),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -679,7 +657,7 @@ namespace System.Globalization {
get { return positiveSign; }
set {
if (value == null) {
- throw new ArgumentNullException("PositiveSign",
+ throw new ArgumentNullException(nameof(PositiveSign),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -694,7 +672,7 @@ namespace System.Globalization {
set {
if (value < 0 || value > 99) {
throw new ArgumentOutOfRangeException(
- "PercentDecimalDigits",
+ nameof(PercentDecimalDigits),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -734,7 +712,7 @@ namespace System.Globalization {
}
set {
if (value == null) {
- throw new ArgumentNullException("PercentSymbol",
+ throw new ArgumentNullException(nameof(PercentSymbol),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -748,7 +726,7 @@ namespace System.Globalization {
get { return perMilleSymbol; }
set {
if (value == null) {
- throw new ArgumentNullException("PerMilleSymbol",
+ throw new ArgumentNullException(nameof(PerMilleSymbol),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -788,7 +766,7 @@ namespace System.Globalization {
public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) {
if (nfi == null) {
- throw new ArgumentNullException("nfi");
+ throw new ArgumentNullException(nameof(nfi));
}
Contract.EndContractBlock();
if (nfi.IsReadOnly) {
@@ -809,7 +787,7 @@ namespace System.Globalization {
internal static void ValidateParseStyleInteger(NumberStyles style) {
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style));
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
@@ -822,7 +800,7 @@ namespace System.Globalization {
internal static void ValidateParseStyleFloatingPoint(NumberStyles style) {
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style));
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
diff --git a/src/mscorlib/src/System/Globalization/PersianCalendar.cs b/src/mscorlib/src/System/Globalization/PersianCalendar.cs
index 2f1ffacee7..e61a007a02 100644
--- a/src/mscorlib/src/System/Globalization/PersianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/PersianCalendar.cs
@@ -4,6 +4,7 @@
namespace System.Globalization {
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
@@ -147,7 +148,7 @@ namespace System.Globalization {
static internal void CheckEraRange(int era) {
if (era != CurrentEra && era != PersianEra) {
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
}
@@ -155,7 +156,7 @@ namespace System.Globalization {
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -169,7 +170,7 @@ namespace System.Globalization {
if (year == MaxCalendarYear) {
if (month > MaxCalendarMonth) {
throw new ArgumentOutOfRangeException(
- "month",
+ nameof(month),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -179,13 +180,13 @@ namespace System.Globalization {
}
if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
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.
@@ -290,7 +291,7 @@ namespace System.Globalization {
public override DateTime AddMonths(DateTime time, int months) {
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
- "months",
+ nameof(months),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -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;
@@ -450,7 +451,7 @@ namespace System.Globalization {
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth) {
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Day"),
@@ -506,7 +507,7 @@ namespace System.Globalization {
if (day < 1 || day > daysInMonth) {
BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Day"),
@@ -538,7 +539,7 @@ namespace System.Globalization {
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
- "value",
+ nameof(value),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -553,7 +554,7 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -564,7 +565,7 @@ namespace System.Globalization {
if (year > MaxCalendarYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
diff --git a/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/mscorlib/src/System/Globalization/RegionInfo.cs
index f06d63f1d2..4bed87570f 100644
--- a/src/mscorlib/src/System/Globalization/RegionInfo.cs
+++ b/src/mscorlib/src/System/Globalization/RegionInfo.cs
@@ -19,6 +19,7 @@ namespace System.Globalization {
using System;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
@@ -59,14 +60,13 @@ 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("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0) //The InvariantCulture has no matching region
{
- throw new ArgumentException(Environment.GetResourceString("Argument_NoRegionInvariantCulture"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NoRegionInvariantCulture"), nameof(name));
}
Contract.EndContractBlock();
@@ -83,19 +83,18 @@ namespace System.Globalization {
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_InvalidCultureName"), name), "name");
+ Environment.GetResourceString("Argument_InvalidCultureName"), name), nameof(name));
// Not supposed to be neutral
if (this.m_cultureData.IsNeutralCulture)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNeutralRegionName", name), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNeutralRegionName", name), nameof(name));
SetName(name);
}
#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
@@ -106,13 +105,13 @@ namespace System.Globalization {
if (culture == CultureInfo.LOCALE_NEUTRAL)
{
// Not supposed to be neutral
- throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), "culture");
+ throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), nameof(culture));
}
if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT)
{
// Not supposed to be neutral
- throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", culture), "culture");
+ throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", culture), nameof(culture));
}
this.m_cultureData = CultureData.GetCultureData(culture,true);
@@ -121,34 +120,23 @@ namespace System.Globalization {
if (this.m_cultureData.IsNeutralCulture)
{
// Not supposed to be neutral
- throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), "culture");
+ throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), nameof(culture));
}
m_cultureId = culture;
}
#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,174 +151,17 @@ 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(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_InvalidCultureName"), m_name), "m_name");
+ Environment.GetResourceString("Argument_InvalidCultureName"), m_name), nameof(m_name));
if (m_cultureId == 0)
{
@@ -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);
}
diff --git a/src/mscorlib/src/System/Globalization/SortKey.cs b/src/mscorlib/src/System/Globalization/SortKey.cs
index e3308dc4f8..9c35f485e5 100644
--- a/src/mscorlib/src/System/Globalization/SortKey.cs
+++ b/src/mscorlib/src/System/Globalization/SortKey.cs
@@ -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)]
@@ -119,15 +120,15 @@ namespace System.Globalization {
public static int Compare(SortKey sortkey1, SortKey sortkey2) {
if (sortkey1==null || sortkey2==null) {
- throw new ArgumentNullException((sortkey1==null ? "sortkey1": "sortkey2"));
+ throw new ArgumentNullException((sortkey1==null ? nameof(sortkey1): nameof(sortkey2)));
}
Contract.EndContractBlock();
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) {
diff --git a/src/mscorlib/src/System/Globalization/StringInfo.cs b/src/mscorlib/src/System/Globalization/StringInfo.cs
index b1151bde4f..d86e11592e 100644
--- a/src/mscorlib/src/System/Globalization/StringInfo.cs
+++ b/src/mscorlib/src/System/Globalization/StringInfo.cs
@@ -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]
@@ -92,7 +93,7 @@ namespace System.Globalization {
}
set {
if (null == value) {
- throw new ArgumentNullException("String",
+ throw new ArgumentNullException(nameof(String),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
@@ -118,11 +119,11 @@ namespace System.Globalization {
if(null == this.Indexes) {
// Just decide which error to give depending on the param they gave us....
if(startingTextElement < 0) {
- throw new ArgumentOutOfRangeException("startingTextElement",
+ throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
else {
- throw new ArgumentOutOfRangeException("startingTextElement",
+ throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
}
@@ -135,22 +136,22 @@ namespace System.Globalization {
// Parameter checking
//
if(startingTextElement < 0) {
- throw new ArgumentOutOfRangeException("startingTextElement",
+ throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) {
- throw new ArgumentOutOfRangeException("startingTextElement",
+ throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
if(lengthInTextElements < 0) {
- throw new ArgumentOutOfRangeException("lengthInTextElements",
+ throw new ArgumentOutOfRangeException(nameof(lengthInTextElements),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if(startingTextElement > this.Indexes.Length - lengthInTextElements) {
- throw new ArgumentOutOfRangeException("lengthInTextElements",
+ throw new ArgumentOutOfRangeException(nameof(lengthInTextElements),
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
@@ -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.
@@ -268,7 +269,7 @@ namespace System.Globalization {
// Validate parameters.
//
if (str==null) {
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
@@ -277,7 +278,7 @@ namespace System.Globalization {
if (index == len) {
return (String.Empty);
}
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
int charLen;
@@ -297,14 +298,14 @@ namespace System.Globalization {
//
if (str==null)
{
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || (index > len))
{
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
return (new TextElementEnumerator(str, index, len));
@@ -326,7 +327,7 @@ namespace System.Globalization {
{
if (str == null)
{
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs b/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
index 013e2cd50e..476ddeef7c 100644
--- a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
@@ -241,14 +241,14 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year <= 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
Contract.EndContractBlock();
if (year > helper.MaxYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
diff --git a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
index 5f47f5fbd4..049ccf6f81 100644
--- a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
+++ b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs
index 9b84486f4e..c8108e4922 100644
--- a/src/mscorlib/src/System/Globalization/TextInfo.cs
+++ b/src/mscorlib/src/System/Globalization/TextInfo.cs
@@ -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)
@@ -462,7 +443,7 @@ namespace System.Globalization {
[System.Runtime.InteropServices.ComVisible(false)]
public static TextInfo ReadOnly(TextInfo textInfo)
{
- if (textInfo == null) { throw new ArgumentNullException("textInfo"); }
+ if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); }
Contract.EndContractBlock();
if (textInfo.IsReadOnly) { return (textInfo); }
@@ -498,7 +479,6 @@ namespace System.Globalization {
public virtual String ListSeparator
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_listSeparator == null) {
@@ -512,7 +492,7 @@ namespace System.Globalization {
{
if (value == null)
{
- throw new ArgumentNullException("value", Environment.GetResourceString("ArgumentNull_String"));
+ throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
@@ -529,7 +509,6 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual char ToLower(char c)
{
if(IsAscii(c) && IsAsciiCasingSameAsInvariant)
@@ -539,10 +518,9 @@ 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("str"); }
+ if (str == null) { throw new ArgumentNullException(nameof(str)); }
Contract.EndContractBlock();
return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, false);
@@ -567,7 +545,6 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual char ToUpper(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
@@ -578,10 +555,9 @@ namespace System.Globalization {
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual String ToUpper(String str)
{
- if (str == null) { throw new ArgumentNullException("str"); }
+ if (str == null) { throw new ArgumentNullException(nameof(str)); }
Contract.EndContractBlock();
return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, true);
}
@@ -698,7 +674,7 @@ namespace System.Globalization {
{
if (str == null)
{
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
if (str.Length == 0)
@@ -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,19 +923,17 @@ 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
if (str==null)
{
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
@@ -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)]
diff --git a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs b/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
index f26c68adce..e294b51325 100644
--- a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
@@ -213,7 +213,7 @@ namespace System.Globalization {
public override int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs b/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs
index 8f58623868..e5e615f1b3 100644
--- a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs
+++ b/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
index e72e582a97..d83c5fa151 100644
--- a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
+++ b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
@@ -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"));
}
}
@@ -627,7 +628,7 @@ namespace System.Globalization {
//
private static Boolean TryParseTimeSpan(String input, TimeSpanStandardStyles style, IFormatProvider formatProvider, ref TimeSpanResult result) {
if (input == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "input");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input));
return false;
}
@@ -1117,11 +1118,11 @@ namespace System.Globalization {
//
private static Boolean TryParseExactTimeSpan(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result) {
if (input == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "input");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input));
return false;
}
if (format == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "format");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(format));
return false;
}
if (format.Length == 0) {
@@ -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?
@@ -1376,7 +1377,7 @@ namespace System.Globalization {
result.parsedTimeSpan._ticks = 0;
if (input == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "input");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input));
return false;
}
str = input;
@@ -1511,11 +1512,11 @@ namespace System.Globalization {
//
private static Boolean TryParseExactMultipleTimeSpan(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result) {
if (input == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "input");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input));
return false;
}
if (formats == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "formats");
+ result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(formats));
return false;
}
diff --git a/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs b/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs
index 94b235085e..06e7c7d75a 100644
--- a/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs
@@ -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;
@@ -392,7 +393,7 @@ namespace System.Globalization {
static internal void CheckEraRange(int era) {
if (era != CurrentEra && era != UmAlQuraEra) {
- throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
}
@@ -400,7 +401,7 @@ namespace System.Globalization {
CheckEraRange(era);
if (year < MinCalendarYear || year > MaxCalendarYear) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -412,7 +413,7 @@ namespace System.Globalization {
static internal void CheckYearMonthRange(int year, int month, int era) {
CheckYearRange(year, era);
if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
@@ -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.
@@ -528,7 +529,7 @@ namespace System.Globalization {
public override DateTime AddMonths(DateTime time, int months) {
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
- "months",
+ nameof(months),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -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;
}
@@ -712,7 +713,7 @@ namespace System.Globalization {
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth) {
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Day"),
@@ -774,7 +775,7 @@ namespace System.Globalization {
if (day < 1 || day > daysInMonth) {
BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
throw new ArgumentOutOfRangeException(
- "day",
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Day"),
@@ -806,7 +807,7 @@ DayInRang:
set {
if (value != 99 && (value < MinCalendarYear || value > MaxCalendarYear)) {
throw new ArgumentOutOfRangeException(
- "value",
+ nameof(value),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
@@ -824,7 +825,7 @@ DayInRang:
public override int ToFourDigitYear(int year) {
if (year < 0) {
- throw new ArgumentOutOfRangeException("year",
+ throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -835,7 +836,7 @@ DayInRang:
if ((year < MinCalendarYear) || (year > MaxCalendarYear)) {
throw new ArgumentOutOfRangeException(
- "year",
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
diff --git a/src/mscorlib/src/System/Guid.cs b/src/mscorlib/src/System/Guid.cs
index 1ccabeb8db..e2e36ba1b2 100644
--- a/src/mscorlib/src/System/Guid.cs
+++ b/src/mscorlib/src/System/Guid.cs
@@ -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.
@@ -47,9 +48,9 @@ namespace System {
public Guid(byte[] b)
{
if (b==null)
- throw new ArgumentNullException("b");
+ throw new ArgumentNullException(nameof(b));
if (b.Length != 16)
- throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16"), "b");
+ throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16"), nameof(b));
Contract.EndContractBlock();
_a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0];
@@ -87,10 +88,10 @@ namespace System {
public Guid(int a, short b, short c, byte[] d)
{
if (d==null)
- throw new ArgumentNullException("d");
+ throw new ArgumentNullException(nameof(d));
// Check that array is not too big
if(d.Length != 8)
- throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "8"), "d");
+ throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "8"), nameof(d));
Contract.EndContractBlock();
_a = a;
@@ -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"));
}
}
@@ -231,7 +232,7 @@ namespace System {
public Guid(String g)
{
if (g==null) {
- throw new ArgumentNullException("g");
+ throw new ArgumentNullException(nameof(g));
}
Contract.EndContractBlock();
this = Guid.Empty;
@@ -250,7 +251,7 @@ namespace System {
public static Guid Parse(String input)
{
if (input == null) {
- throw new ArgumentNullException("input");
+ throw new ArgumentNullException(nameof(input));
}
Contract.EndContractBlock();
@@ -281,10 +282,10 @@ namespace System {
public static Guid ParseExact(String input, String format)
{
if (input == null)
- throw new ArgumentNullException("input");
+ throw new ArgumentNullException(nameof(input));
if (format == null)
- throw new ArgumentNullException("format");
+ throw new ArgumentNullException(nameof(format));
if( format.Length != 1) {
// all acceptable format strings are of length 1
@@ -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.
@@ -1007,7 +998,7 @@ namespace System {
return 1;
}
if (!(value is Guid)) {
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeGuid"), "value");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeGuid"), nameof(value));
}
Guid g = (Guid)value;
@@ -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)
diff --git a/src/mscorlib/src/System/IAppDomain.cs b/src/mscorlib/src/System/IAppDomain.cs
index bd8b876577..cdb83166c8 100644
--- a/src/mscorlib/src/System/IAppDomain.cs
+++ b/src/mscorlib/src/System/IAppDomain.cs
@@ -13,256 +13,16 @@
**
**
===========================================================*/
-namespace System {
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using SecurityManager = System.Security.SecurityManager;
- using System.Security.Permissions;
- using IEvidenceFactory = System.Security.IEvidenceFactory;
-#if FEATURE_IMPERSONATION
- using System.Security.Principal;
-#endif
- using System.Security.Policy;
- using System.Security;
- using System.Security.Util;
- using System.Collections;
- using System.Text;
- using System.Configuration.Assemblies;
- using System.Threading;
+namespace System
+{
using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
- using System.Reflection.Emit;
- using CultureInfo = System.Globalization.CultureInfo;
- using System.IO;
- using System.Runtime.Versioning;
[GuidAttribute("05F696DC-2B29-3663-AD8B-C4389CF2A713")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _AppDomain
{
-#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);
-
- String ToString();
-
- bool Equals (Object other);
-
- int GetHashCode ();
-
- Type GetType ();
-
-#if FEATURE_REMOTING
- [System.Security.SecurityCritical] // auto-generated_required
- Object InitializeLifetimeService ();
-
- [System.Security.SecurityCritical] // auto-generated_required
- Object GetLifetimeService ();
-#endif // FEATURE_REMOTING
-
-#if FEATURE_CAS_POLICY
- Evidence Evidence { get; }
-#endif // FEATURE_CAS_POLICY
- event EventHandler DomainUnload;
-
- [method:System.Security.SecurityCritical]
- event AssemblyLoadEventHandler AssemblyLoad;
-
- event EventHandler ProcessExit;
-
- [method:System.Security.SecurityCritical]
- event ResolveEventHandler TypeResolve;
-
- [method:System.Security.SecurityCritical]
- event ResolveEventHandler ResourceResolve;
-
- [method:System.Security.SecurityCritical]
- event ResolveEventHandler AssemblyResolve;
-
- [method:System.Security.SecurityCritical]
- event UnhandledExceptionEventHandler UnhandledException;
-
- AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access);
-
- AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access,
- String dir);
-
- AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access,
- Evidence evidence);
-
- AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions);
-
- AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- Evidence evidence);
-
- AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions);
-
- AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access,
- Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions);
-
- AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions);
-
- AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
- AssemblyBuilderAccess access,
- String dir,
- Evidence evidence,
- PermissionSet requiredPermissions,
- PermissionSet optionalPermissions,
- PermissionSet refusedPermissions,
- bool isSynchronized);
-
- ObjectHandle CreateInstance(String assemblyName,
- String typeName);
-
-
- ObjectHandle CreateInstanceFrom(String assemblyFile,
- String typeName);
-
-
- ObjectHandle CreateInstance(String assemblyName,
- String typeName,
- Object[] activationAttributes);
-
- ObjectHandle CreateInstanceFrom(String assemblyFile,
- String typeName,
- Object[] activationAttributes);
-
- ObjectHandle CreateInstance(String assemblyName,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes);
-
- ObjectHandle CreateInstanceFrom(String assemblyFile,
- String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes,
- Evidence securityAttributes);
-
- Assembly Load(AssemblyName assemblyRef);
-
- Assembly Load(String assemblyString);
-
- Assembly Load(byte[] rawAssembly);
-
- Assembly Load(byte[] rawAssembly,
- byte[] rawSymbolStore);
-
- Assembly Load(byte[] rawAssembly,
- byte[] rawSymbolStore,
- Evidence securityEvidence);
-
- Assembly Load(AssemblyName assemblyRef,
- Evidence assemblySecurity);
-
- Assembly Load(String assemblyString,
- Evidence assemblySecurity);
-
- int ExecuteAssembly(String assemblyFile,
- Evidence assemblySecurity);
-
- int ExecuteAssembly(String assemblyFile);
-
- int ExecuteAssembly(String assemblyFile,
- Evidence assemblySecurity,
- String[] args);
-
- String FriendlyName
- { get; }
-#if FEATURE_FUSION
- String BaseDirectory
- {
- get;
- }
-
- String RelativeSearchPath
- { get; }
-
- bool ShadowCopyFiles
- { get; }
-#endif
- Assembly[] GetAssemblies();
-#if FEATURE_FUSION
- [System.Security.SecurityCritical] // auto-generated_required
- void AppendPrivatePath(String path);
-
- [System.Security.SecurityCritical] // auto-generated_required
- void ClearPrivatePath();
-
- [System.Security.SecurityCritical] // auto-generated_required
- void SetShadowCopyPath (String s);
-
- [System.Security.SecurityCritical] // auto-generated_required
- void ClearShadowCopyPath ( );
-
- [System.Security.SecurityCritical] // auto-generated_required
- void SetCachePath (String s);
-#endif //FEATURE_FUSION
- [System.Security.SecurityCritical] // auto-generated_required
- void SetData(String name, Object data);
-
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- Object GetData(string name);
-
-#if FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated_required
- void SetAppDomainPolicy(PolicyLevel domainPolicy);
-
-#if FEATURE_IMPERSONATION
- void SetThreadPrincipal(IPrincipal principal);
-#endif // FEATURE_IMPERSONATION
-
- void SetPrincipalPolicy(PrincipalPolicy policy);
-#endif
-
-#if FEATURE_REMOTING
- void DoCallBack(CrossAppDomainDelegate theDelegate);
-#endif
-
- String DynamicDirectory
- { get; }
-#endif
}
}
diff --git a/src/mscorlib/src/System/IAppDomainPauseManager.cs b/src/mscorlib/src/System/IAppDomainPauseManager.cs
index 7e031454a4..902a79bd2a 100644
--- a/src/mscorlib/src/System/IAppDomainPauseManager.cs
+++ b/src/mscorlib/src/System/IAppDomainPauseManager.cs
@@ -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;
}
}
diff --git a/src/mscorlib/src/System/IO/BinaryReader.cs b/src/mscorlib/src/System/IO/BinaryReader.cs
index 8accf0bd77..4145a7f4f6 100644
--- a/src/mscorlib/src/System/IO/BinaryReader.cs
+++ b/src/mscorlib/src/System/IO/BinaryReader.cs
@@ -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;
@@ -40,7 +41,7 @@ namespace System.IO {
private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf
private bool m_leaveOpen;
- public BinaryReader(Stream input) : this(input, new UTF8Encoding(), false) {
+ public BinaryReader(Stream input) : this(input, Encoding.UTF8, false) {
}
public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false) {
@@ -48,10 +49,10 @@ namespace System.IO {
public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) {
if (input==null) {
- throw new ArgumentNullException("input");
+ throw new ArgumentNullException(nameof(input));
}
if (encoding==null) {
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
}
if (!input.CanRead)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
@@ -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,16 +293,15 @@ namespace System.IO {
return StringBuilderCache.GetStringAndRelease(sb);
}
- [SecuritySafeCritical]
public virtual int Read(char[] buffer, int index, int count) {
if (buffer==null) {
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
}
if (index < 0) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (count < 0) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (buffer.Length - index < count) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
@@ -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,10 +469,9 @@ namespace System.IO {
return m_singleChar[0];
}
- [SecuritySafeCritical]
public virtual char[] ReadChars(int count) {
if (count<0) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.Ensures(Contract.Result<char[]>() != null);
Contract.Ensures(Contract.Result<char[]>().Length <= count);
@@ -502,11 +498,11 @@ namespace System.IO {
public virtual int Read(byte[] buffer, int index, int count) {
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<int>() >= 0);
@@ -518,7 +514,7 @@ namespace System.IO {
}
public virtual byte[] ReadBytes(int count) {
- if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count));
Contract.EndContractBlock();
@@ -551,7 +547,7 @@ namespace System.IO {
protected virtual void FillBuffer(int numBytes) {
if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length)) {
- throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_BinaryReaderFillBuffer"));
+ throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_BinaryReaderFillBuffer"));
}
int bytesRead=0;
int n = 0;
diff --git a/src/mscorlib/src/System/IO/BinaryWriter.cs b/src/mscorlib/src/System/IO/BinaryWriter.cs
index c775cbc9ff..f99b4d3d42 100644
--- a/src/mscorlib/src/System/IO/BinaryWriter.cs
+++ b/src/mscorlib/src/System/IO/BinaryWriter.cs
@@ -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,14 +39,6 @@ namespace System.IO {
[OptionalField] // New in .NET FX 4.5. False is the right default value.
private bool _leaveOpen;
- // 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
-
// Perf optimization stuff
private byte[] _largeByteBuffer; // temp space for writing chars.
private int _maxChars; // max # of chars we can put in _largeByteBuffer
@@ -58,11 +51,11 @@ namespace System.IO {
{
OutStream = Stream.Null;
_buffer = new byte[16];
- _encoding = new UTF8Encoding(false, true);
+ _encoding = EncodingCache.UTF8NoBOM;
_encoder = _encoding.GetEncoder();
}
- public BinaryWriter(Stream output) : this(output, new UTF8Encoding(false, true), false)
+ public BinaryWriter(Stream output) : this(output, EncodingCache.UTF8NoBOM, false)
{
}
@@ -73,9 +66,9 @@ namespace System.IO {
public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)
{
if (output==null)
- throw new ArgumentNullException("output");
+ throw new ArgumentNullException(nameof(output));
if (encoding==null)
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
if (!output.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
Contract.EndContractBlock();
@@ -166,7 +159,7 @@ namespace System.IO {
//
public virtual void Write(byte[] buffer) {
if (buffer == null)
- throw new ArgumentNullException("buffer");
+ throw new ArgumentNullException(nameof(buffer));
Contract.EndContractBlock();
OutStream.Write(buffer, 0, buffer.Length);
}
@@ -185,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);
@@ -207,7 +199,7 @@ namespace System.IO {
public virtual void Write(char[] chars)
{
if (chars == null)
- throw new ArgumentNullException("chars");
+ throw new ArgumentNullException(nameof(chars));
Contract.EndContractBlock();
byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length);
@@ -229,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;
@@ -332,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;
@@ -349,11 +339,10 @@ 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)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
int len = _encoding.GetByteCount(value);
@@ -366,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);
}
@@ -401,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
}
}
diff --git a/src/mscorlib/src/System/IO/BufferedStream.cs b/src/mscorlib/src/System/IO/BufferedStream.cs
deleted file mode 100644
index 0c73b5c0f5..0000000000
--- a/src/mscorlib/src/System/IO/BufferedStream.cs
+++ /dev/null
@@ -1,1320 +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: A composable Stream that buffers reads & writes to the underlying stream.
-**
-**
-===========================================================*/
-using System;
-using System.Runtime.InteropServices;
-using System.Globalization;
-using System.Diagnostics.Contracts;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using System.Collections.ObjectModel;
-using System.Security;
-using System.Threading.Tasks;
-
-namespace System.IO {
-
-/// <summary>
-/// One of the design goals here is to prevent the buffer from getting in the way and slowing
-/// down underlying stream accesses when it is not needed. If you always read & write for sizes
-/// greater than the internal buffer size, then this class may not even allocate the internal buffer.
-/// See a large comment in Write for the details of the write buffer heuristic.
-///
-/// This class buffers reads & writes in a shared buffer.
-/// (If you maintained two buffers separately, one operation would always trash the other buffer
-/// anyways, so we might as well use one buffer.)
-/// The assumption here is you will almost always be doing a series of reads or writes, but rarely
-/// alternate between the two of them on the same stream.
-///
-/// Class Invariants:
-/// The class has one buffer, shared for reading & writing.
-/// It can only be used for one or the other at any point in time - not both.
-/// The following should be true:
-/// <![CDATA[
-/// * 0 <= _readPos <= _readLen < _bufferSize
-/// * 0 <= _writePos < _bufferSize
-/// * _readPos == _readLen && _readPos > 0 implies the read buffer is valid, but we're at the end of the buffer.
-/// * _readPos == _readLen == 0 means the read buffer contains garbage.
-/// * Either _writePos can be greater than 0, or _readLen & _readPos can be greater than zero,
-/// but neither can be greater than zero at the same time.
-/// ]]>
-/// This class will never cache more bytes than the max specified buffer size.
-/// However, it may use a temporary buffer of up to twice the size in order to combine several IO operations on
-/// the underlying stream into a single operation. This is because we assume that memory copies are significantly
-/// faster than IO operations on the underlying stream (if this was not true, using buffering is never appropriate).
-/// The max size of this "shadow" buffer is limited as to not allocate it on the LOH.
-/// Shadowing is always transient. Even when using this technique, this class still guarantees that the number of
-/// bytes cached (not yet written to the target stream or not yet consumed by the user) is never larger than the
-/// actual specified buffer size.
-/// </summary>
-[ComVisible(true)]
-public sealed class BufferedStream : Stream {
-
-
- private const Int32 _DefaultBufferSize = 4096;
-
-
- private Stream _stream; // Underlying stream. Close sets _stream to null.
-
- private Byte[] _buffer; // Shared read/write buffer. Alloc on first use.
-
- private readonly Int32 _bufferSize; // Length of internal buffer (not counting the shadow buffer).
-
- private Int32 _readPos; // Read pointer within shared buffer.
- private Int32 _readLen; // Number of bytes read in buffer from _stream.
- private Int32 _writePos; // Write pointer within shared buffer.
-
- private BeginEndAwaitableAdapter _beginEndAwaitable; // Used to be able to await a BeginXxx call and thus to share code
- // between the APM and Async pattern implementations
-
- private Task<Int32> _lastSyncCompletedReadTask; // The last successful Task returned from ReadAsync
- // (perf optimization for successive reads of the same size)
-
-
- // Removing a private default constructor is a breaking change for the DataContractSerializer.
- // Because this ctor was here previously we need to keep it around.
- private BufferedStream() { }
-
-
- public BufferedStream(Stream stream)
-
- : this(stream, _DefaultBufferSize) {
- }
-
-
- public BufferedStream(Stream stream, Int32 bufferSize) {
-
- if (stream == null)
- throw new ArgumentNullException("stream");
-
- if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "bufferSize"));
-
- Contract.EndContractBlock();
-
- BCLDebug.Perf(!(stream is FileStream), "FileStream is buffered - don't wrap it in a BufferedStream");
- BCLDebug.Perf(!(stream is MemoryStream), "MemoryStream shouldn't be wrapped in a BufferedStream!");
- BCLDebug.Perf(!(stream is BufferedStream), "BufferedStream shouldn't be wrapped in another BufferedStream!");
-
- _stream = stream;
- _bufferSize = bufferSize;
-
- // Allocate _buffer on its first use - it will not be used if all reads
- // & writes are greater than or equal to buffer size.
-
- if (!_stream.CanRead && !_stream.CanWrite)
- __Error.StreamIsClosed();
- }
-
-
- private void EnsureNotClosed() {
-
- if (_stream == null)
- __Error.StreamIsClosed();
- }
-
-
- private void EnsureCanSeek() {
-
- Contract.Requires(_stream != null);
-
- if (!_stream.CanSeek)
- __Error.SeekNotSupported();
- }
-
-
- private void EnsureCanRead() {
-
- Contract.Requires(_stream != null);
-
- if (!_stream.CanRead)
- __Error.ReadNotSupported();
- }
-
-
- private void EnsureCanWrite() {
-
- Contract.Requires(_stream != null);
-
- if (!_stream.CanWrite)
- __Error.WriteNotSupported();
- }
-
-
- private void EnsureBeginEndAwaitableAllocated() {
- // We support only a single ongoing async operation and enforce this with a semaphore,
- // so singleton is fine and no need to worry about a race condition here.
- if (_beginEndAwaitable == null)
- _beginEndAwaitable = new BeginEndAwaitableAdapter();
- }
-
-
- /// <summary><code>MaxShadowBufferSize</code> is chosed such that shadow buffers are not allocated on the Large Object Heap.
- /// Currently, an object is allocated on the LOH if it is larger than 85000 bytes. See LARGE_OBJECT_SIZE in ndp\clr\src\vm\gc.h
- /// We will go with exactly 80 KBytes, although this is somewhat arbitrary.</summary>
- private const Int32 MaxShadowBufferSize = 81920; // Make sure not to get to the Large Object Heap.
- private void EnsureShadowBufferAllocated() {
-
- Contract.Assert(_buffer != null);
- Contract.Assert(_bufferSize > 0);
-
- // Already have shadow buffer?
- if (_buffer.Length != _bufferSize || _bufferSize >= MaxShadowBufferSize)
- return;
-
- Byte[] shadowBuffer = new Byte[Math.Min(_bufferSize + _bufferSize, MaxShadowBufferSize)];
- Buffer.InternalBlockCopy(_buffer, 0, shadowBuffer, 0, _writePos);
- _buffer = shadowBuffer;
- }
-
-
- private void EnsureBufferAllocated() {
-
- Contract.Assert(_bufferSize > 0);
-
- // BufferedStream is not intended for multi-threaded use, so no worries about the get/set race conditions on _buffer.
- if (_buffer == null)
- _buffer = new Byte[_bufferSize];
- }
-
-
- internal Stream UnderlyingStream {
- [FriendAccessAllowed]
- [Pure]
- get { return _stream; }
- }
-
-
- internal Int32 BufferSize {
- [FriendAccessAllowed]
- [Pure]
- get { return _bufferSize; }
- }
-
-
- public override bool CanRead {
- [Pure]
- get { return _stream != null && _stream.CanRead; }
- }
-
-
- public override bool CanWrite {
- [Pure]
- get { return _stream != null && _stream.CanWrite; }
- }
-
-
- public override bool CanSeek {
- [Pure]
- get { return _stream != null && _stream.CanSeek; }
- }
-
-
- public override Int64 Length {
- get {
- EnsureNotClosed();
-
- if (_writePos > 0)
- FlushWrite();
-
- return _stream.Length;
- }
- }
-
-
- public override Int64 Position {
- get {
- EnsureNotClosed();
- EnsureCanSeek();
-
- Contract.Assert(! (_writePos > 0 && _readPos != _readLen), "Read and Write buffers cannot both have data in them at the same time.");
- return _stream.Position + (_readPos - _readLen + _writePos);
- }
- set {
- if (value < 0)
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- EnsureNotClosed();
- EnsureCanSeek();
-
- if (_writePos > 0)
- FlushWrite();
-
- _readPos = 0;
- _readLen = 0;
- _stream.Seek(value, SeekOrigin.Begin);
- }
- }
-
-
- protected override void Dispose(bool disposing) {
-
- try {
- if (disposing && _stream != null) {
- try {
- Flush();
- } finally {
- _stream.Close();
- }
- }
- } finally {
- _stream = null;
- _buffer = null;
- _lastSyncCompletedReadTask = null;
-
- // Call base.Dispose(bool) to cleanup async IO resources
- base.Dispose(disposing);
- }
- }
-
-
- public override void Flush() {
-
- EnsureNotClosed();
-
- // Has WRITE data in the buffer:
- if (_writePos > 0) {
-
- FlushWrite();
- Contract.Assert(_writePos == 0 && _readPos == 0 && _readLen == 0);
- return;
- }
-
- // Has READ data in the buffer:
- if (_readPos < _readLen) {
-
- // If the underlying stream is not seekable AND we have something in the read buffer, then FlushRead would throw.
- // We can either throw away the buffer resulting in data loss (!) or ignore the Flush.
- // (We cannot throw becasue it would be a breaking change.) We opt into ignoring the Flush in that situation.
- if (!_stream.CanSeek)
- return;
-
- FlushRead();
-
- // User streams may have opted to throw from Flush if CanWrite is false (although the abstract Stream does not do so).
- // However, if we do not forward the Flush to the underlying stream, we may have problems when chaining several streams.
- // Let us make a best effort attempt:
- if (_stream.CanWrite || _stream is BufferedStream)
- _stream.Flush();
-
- Contract.Assert(_writePos == 0 && _readPos == 0 && _readLen == 0);
- return;
- }
-
- // We had no data in the buffer, but we still need to tell the underlying stream to flush.
- if (_stream.CanWrite || _stream is BufferedStream)
- _stream.Flush();
-
- _writePos = _readPos = _readLen = 0;
- }
-
- public override Task FlushAsync(CancellationToken cancellationToken) {
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled<Int32>(cancellationToken);
-
- EnsureNotClosed();
-
- return FlushAsyncInternal(cancellationToken, this, _stream, _writePos, _readPos, _readLen);
- }
-
-
- private static async Task FlushAsyncInternal(CancellationToken cancellationToken,
- BufferedStream _this, Stream stream, Int32 writePos, Int32 readPos, Int32 readLen) {
-
- // We bring instance fields down as local parameters to this async method becasue BufferedStream is derived from MarshalByRefObject.
- // Field access would be from the async state machine i.e., not via the this pointer and would require runtime checking to see
- // if we are talking to a remote object, which is currently very slow
-
- Contract.Assert(stream != null);
-
- SemaphoreSlim sem = _this.EnsureAsyncActiveSemaphoreInitialized();
- await sem.WaitAsync().ConfigureAwait(false);
- try {
-
- if (writePos > 0) {
-
- await _this.FlushWriteAsync(cancellationToken).ConfigureAwait(false);
- Contract.Assert(_this._writePos == 0 && _this._readPos == 0 && _this._readLen == 0);
- return;
- }
-
- if (readPos < readLen) {
-
- // If the underlying stream is not seekable AND we have something in the read buffer, then FlushRead would throw.
- // We can either throw away the buffer resulting in date loss (!) or ignore the Flush. (We cannot throw becasue it
- // would be a breaking change.) We opt into ignoring the Flush in that situation.
- if (!stream.CanSeek)
- return;
-
- _this.FlushRead(); // not async; it uses Seek, but there's no SeekAsync
-
- // User streams may have opted to throw from Flush if CanWrite is false (although the abstract Stream does not do so).
- // However, if we do not forward the Flush to the underlying stream, we may have problems when chaining several streams.
- // Let us make a best effort attempt:
- if (stream.CanRead || stream is BufferedStream)
- await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
-
- Contract.Assert(_this._writePos == 0 && _this._readPos == 0 && _this._readLen == 0);
- return;
- }
-
- // We had no data in the buffer, but we still need to tell the underlying stream to flush.
- if (stream.CanWrite || stream is BufferedStream)
- await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
-
- // There was nothing in the buffer:
- Contract.Assert(_this._writePos == 0 && _this._readPos == _this._readLen);
-
- } finally {
- sem.Release();
- }
- }
-
-
- // Reading is done in blocks, but someone could read 1 byte from the buffer then write.
- // At that point, the underlying stream's pointer is out of sync with this stream's position.
- // All write functions should call this function to ensure that the buffered data is not lost.
- private void FlushRead() {
-
- Contract.Assert(_writePos == 0, "BufferedStream: Write buffer must be empty in FlushRead!");
-
- if (_readPos - _readLen != 0)
- _stream.Seek(_readPos - _readLen, SeekOrigin.Current);
-
- _readPos = 0;
- _readLen = 0;
- }
-
-
- private void ClearReadBufferBeforeWrite() {
-
- // This is called by write methods to clear the read buffer.
-
- Contract.Assert(_readPos <= _readLen, "_readPos <= _readLen [" + _readPos +" <= " + _readLen + "]");
-
- // No READ data in the buffer:
- if (_readPos == _readLen) {
-
- _readPos = _readLen = 0;
- return;
- }
-
- // Must have READ data.
- Contract.Assert(_readPos < _readLen);
-
- // If the underlying stream cannot seek, FlushRead would end up throwing NotSupported.
- // However, since the user did not call a method that is intuitively expected to seek, a better message is in order.
- // Ideally, we would throw an InvalidOperation here, but for backward compat we have to stick with NotSupported.
- if (!_stream.CanSeek)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotWriteToBufferedStreamIfReadBufferCannotBeFlushed"));
-
- FlushRead();
- }
-
-
- private void FlushWrite() {
-
- Contract.Assert(_readPos == 0 && _readLen == 0,
- "BufferedStream: Read buffer must be empty in FlushWrite!");
- Contract.Assert(_buffer != null && _bufferSize >= _writePos,
- "BufferedStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!");
-
- _stream.Write(_buffer, 0, _writePos);
- _writePos = 0;
- _stream.Flush();
- }
-
-
- private async Task FlushWriteAsync(CancellationToken cancellationToken) {
-
- Contract.Assert(_readPos == 0 && _readLen == 0,
- "BufferedStream: Read buffer must be empty in FlushWrite!");
- Contract.Assert(_buffer != null && _bufferSize >= _writePos,
- "BufferedStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!");
-
- await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false);
- _writePos = 0;
- await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
- }
-
-
- private Int32 ReadFromBuffer(Byte[] array, Int32 offset, Int32 count) {
-
- Int32 readBytes = _readLen - _readPos;
- Contract.Assert(readBytes >= 0);
-
- if (readBytes == 0)
- return 0;
-
- Contract.Assert(readBytes > 0);
-
- if (readBytes > count)
- readBytes = count;
-
- Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, readBytes);
- _readPos += readBytes;
-
- return readBytes;
- }
-
-
- private Int32 ReadFromBuffer(Byte[] array, Int32 offset, Int32 count, out Exception error) {
-
- try {
-
- error = null;
- return ReadFromBuffer(array, offset, count);
-
- } catch (Exception ex) {
- error = ex;
- return 0;
- }
- }
-
-
- public override int Read([In, Out] Byte[] array, Int32 offset, Int32 count) {
-
- if (array == null)
- throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- EnsureNotClosed();
- EnsureCanRead();
-
- Int32 bytesFromBuffer = ReadFromBuffer(array, offset, count);
-
- // We may have read less than the number of bytes the user asked for, but that is part of the Stream contract.
-
- // Reading again for more data may cause us to block if we're using a device with no clear end of file,
- // such as a serial port or pipe. If we blocked here and this code was used with redirected pipes for a
- // process's standard output, this can lead to deadlocks involving two processes.
- // BUT - this is a breaking change.
- // So: If we could not read all bytes the user asked for from the buffer, we will try once from the underlying
- // stream thus ensuring the same blocking behaviour as if the underlying stream was not wrapped in this BufferedStream.
- if (bytesFromBuffer == count)
- return bytesFromBuffer;
-
- Int32 alreadySatisfied = bytesFromBuffer;
- if (bytesFromBuffer > 0) {
- count -= bytesFromBuffer;
- offset += bytesFromBuffer;
- }
-
- // So the READ buffer is empty.
- Contract.Assert(_readLen == _readPos);
- _readPos = _readLen = 0;
-
- // If there was anything in the WRITE buffer, clear it.
- if (_writePos > 0)
- FlushWrite();
-
- // If the requested read is larger than buffer size, avoid the buffer and still use a single read:
- if (count >= _bufferSize) {
-
- return _stream.Read(array, offset, count) + alreadySatisfied;
- }
-
- // Ok. We can fill the buffer:
- EnsureBufferAllocated();
- _readLen = _stream.Read(_buffer, 0, _bufferSize);
-
- bytesFromBuffer = ReadFromBuffer(array, offset, count);
-
- // We may have read less than the number of bytes the user asked for, but that is part of the Stream contract.
- // Reading again for more data may cause us to block if we're using a device with no clear end of stream,
- // such as a serial port or pipe. If we blocked here & this code was used with redirected pipes for a process's
- // standard output, this can lead to deadlocks involving two processes. Additionally, translating one read on the
- // BufferedStream to more than one read on the underlying Stream may defeat the whole purpose of buffering of the
- // underlying reads are significantly more expensive.
-
- return bytesFromBuffer + alreadySatisfied;
- }
-
-
- public override IAsyncResult BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state) {
-
- if (buffer == null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- // Previous version incorrectly threw NotSupported instead of ObjectDisposed. We keep that behaviour for back-compat.
- // EnsureNotClosed();
- if (_stream == null) __Error.ReadNotSupported();
- EnsureCanRead();
-
- Int32 bytesFromBuffer = 0;
- // Try to satisfy the request from the buffer synchronously. But still need a sem-lock in case that another
- // Async IO Task accesses the buffer concurrently. If we fail to acquire the lock without waiting, make this
- // an Async operation.
- SemaphoreSlim sem = base.EnsureAsyncActiveSemaphoreInitialized();
- Task semaphoreLockTask = sem.WaitAsync();
- if (semaphoreLockTask.Status == TaskStatus.RanToCompletion) {
-
- bool completeSynchronously = true;
- try {
-
- Exception error;
- bytesFromBuffer = ReadFromBuffer(buffer, offset, count, out error);
-
- // If we satistied enough data from the buffer, we can complete synchronously.
- // Reading again for more data may cause us to block if we're using a device with no clear end of file,
- // such as a serial port or pipe. If we blocked here and this code was used with redirected pipes for a
- // process's standard output, this can lead to deadlocks involving two processes.
- // BUT - this is a breaking change.
- // So: If we could not read all bytes the user asked for from the buffer, we will try once from the underlying
- // stream thus ensuring the same blocking behaviour as if the underlying stream was not wrapped in this BufferedStream.
- completeSynchronously = (bytesFromBuffer == count || error != null);
-
- if (completeSynchronously) {
-
- SynchronousAsyncResult asyncResult = (error == null)
- ? new SynchronousAsyncResult(bytesFromBuffer, state)
- : new SynchronousAsyncResult(error, state, isWrite: false);
- if (callback != null)
- callback(asyncResult);
-
- return asyncResult;
- }
- } finally {
- if (completeSynchronously) // if this is FALSE, we will be entering ReadFromUnderlyingStreamAsync and releasing there.
- sem.Release();
- }
- }
-
- // Delegate to the async implementation.
- return BeginReadFromUnderlyingStream(buffer, offset + bytesFromBuffer, count - bytesFromBuffer, callback, state,
- bytesFromBuffer, semaphoreLockTask);
- }
-
-
- private IAsyncResult BeginReadFromUnderlyingStream(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state,
- Int32 bytesAlreadySatisfied, Task semaphoreLockTask) {
-
- Task<Int32> readOp = ReadFromUnderlyingStreamAsync(buffer, offset, count, CancellationToken.None,
- bytesAlreadySatisfied, semaphoreLockTask, useApmPattern: true);
- return TaskToApm.Begin(readOp, callback, state);
- }
-
-
- public override Int32 EndRead(IAsyncResult asyncResult) {
-
- if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
- Contract.Ensures(Contract.Result<Int32>() >= 0);
- Contract.EndContractBlock();
-
- var sAR = asyncResult as SynchronousAsyncResult;
- if (sAR != null)
- return SynchronousAsyncResult.EndRead(asyncResult);
- return TaskToApm.End<Int32>(asyncResult);
- }
-
-
- private Task<Int32> LastSyncCompletedReadTask(Int32 val) {
-
- Task<Int32> t = _lastSyncCompletedReadTask;
- Contract.Assert(t == null || t.Status == TaskStatus.RanToCompletion);
-
- if (t != null && t.Result == val)
- return t;
-
- t = Task.FromResult<Int32>(val);
- _lastSyncCompletedReadTask = t;
- return t;
- }
-
-
- public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
-
- if (buffer == null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- // Fast path check for cancellation already requested
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled<Int32>(cancellationToken);
-
- EnsureNotClosed();
- EnsureCanRead();
-
- Int32 bytesFromBuffer = 0;
- // Try to satisfy the request from the buffer synchronously. But still need a sem-lock in case that another
- // Async IO Task accesses the buffer concurrently. If we fail to acquire the lock without waiting, make this
- // an Async operation.
- SemaphoreSlim sem = base.EnsureAsyncActiveSemaphoreInitialized();
- Task semaphoreLockTask = sem.WaitAsync();
- if (semaphoreLockTask.Status == TaskStatus.RanToCompletion) {
-
- bool completeSynchronously = true;
- try {
- Exception error;
- bytesFromBuffer = ReadFromBuffer(buffer, offset, count, out error);
-
- // If we satistied enough data from the buffer, we can complete synchronously.
- // Reading again for more data may cause us to block if we're using a device with no clear end of file,
- // such as a serial port or pipe. If we blocked here and this code was used with redirected pipes for a
- // process's standard output, this can lead to deadlocks involving two processes.
- // BUT - this is a breaking change.
- // So: If we could not read all bytes the user asked for from the buffer, we will try once from the underlying
- // stream thus ensuring the same blocking behaviour as if the underlying stream was not wrapped in this BufferedStream.
- completeSynchronously = (bytesFromBuffer == count || error != null);
-
- if (completeSynchronously) {
-
- return (error == null)
- ? LastSyncCompletedReadTask(bytesFromBuffer)
- : Task.FromException<Int32>(error);
- }
- } finally {
- if (completeSynchronously) // if this is FALSE, we will be entering ReadFromUnderlyingStreamAsync and releasing there.
- sem.Release();
- }
- }
-
- // Delegate to the async implementation.
- return ReadFromUnderlyingStreamAsync(buffer, offset + bytesFromBuffer, count - bytesFromBuffer, cancellationToken,
- bytesFromBuffer, semaphoreLockTask, useApmPattern: false);
- }
-
-
- /// <summary>BufferedStream should be as thin a wrapper as possible. We want that ReadAsync delegates to
- /// ReadAsync of the underlying _stream and that BeginRead delegates to BeginRead of the underlying stream,
- /// rather than calling the base Stream which implements the one in terms of the other. This allows BufferedStream
- /// to affect the semantics of the stream it wraps as little as possible. At the same time, we want to share as
- /// much code between the APM and the Async pattern implementations as possible. This method is called by both with
- /// a corresponding useApmPattern value. Recall that Task implements IAsyncResult.</summary>
- /// <returns>-2 if _bufferSize was set to 0 while waiting on the semaphore; otherwise num of bytes read.</returns>
- private async Task<Int32> ReadFromUnderlyingStreamAsync(Byte[] array, Int32 offset, Int32 count,
- CancellationToken cancellationToken,
- Int32 bytesAlreadySatisfied,
- Task semaphoreLockTask, bool useApmPattern) {
-
- // Same conditions validated with exceptions in ReadAsync:
- // (These should be Contract.Requires(..) but that method had some issues in async methods; using Assert(..) for now.)
- Contract.Assert(array != null);
- Contract.Assert(offset >= 0);
- Contract.Assert(count >= 0);
- Contract.Assert(array.Length - offset >= count);
- Contract.Assert(_stream != null);
- Contract.Assert(_stream.CanRead);
- Contract.Assert(_bufferSize > 0);
- Contract.Assert(semaphoreLockTask != null);
-
- // Employ async waiting based on the same synchronization used in BeginRead of the abstract Stream.
- await semaphoreLockTask.ConfigureAwait(false);
- try {
-
- // The buffer might have been changed by another async task while we were waiting on the semaphore.
- // Check it now again.
- Int32 bytesFromBuffer = ReadFromBuffer(array, offset, count);
- if (bytesFromBuffer == count)
- return bytesAlreadySatisfied + bytesFromBuffer;
-
- if (bytesFromBuffer > 0) {
- count -= bytesFromBuffer;
- offset += bytesFromBuffer;
- bytesAlreadySatisfied += bytesFromBuffer;
- }
-
- Contract.Assert(_readLen == _readPos);
- _readPos = _readLen = 0;
-
- // If there was anything in the WRITE buffer, clear it.
- if (_writePos > 0)
- await FlushWriteAsync(cancellationToken).ConfigureAwait(false); // no Begin-End read version for Flush. Use Async.
-
- // If the requested read is larger than buffer size, avoid the buffer and still use a single read:
- if (count >= _bufferSize) {
-
- if (useApmPattern) {
- EnsureBeginEndAwaitableAllocated();
- _stream.BeginRead(array, offset, count, BeginEndAwaitableAdapter.Callback, _beginEndAwaitable);
- return bytesAlreadySatisfied + _stream.EndRead(await _beginEndAwaitable);
- } else {
- return bytesAlreadySatisfied + await _stream.ReadAsync(array, offset, count, cancellationToken).ConfigureAwait(false);
- }
- }
-
- // Ok. We can fill the buffer:
- EnsureBufferAllocated();
- if (useApmPattern) {
- EnsureBeginEndAwaitableAllocated();
- _stream.BeginRead(_buffer, 0, _bufferSize, BeginEndAwaitableAdapter.Callback, _beginEndAwaitable);
- _readLen = _stream.EndRead(await _beginEndAwaitable);
- } else {
- _readLen = await _stream.ReadAsync(_buffer, 0, _bufferSize, cancellationToken).ConfigureAwait(false);
- }
-
- bytesFromBuffer = ReadFromBuffer(array, offset, count);
- return bytesAlreadySatisfied + bytesFromBuffer;
-
- } finally {
- SemaphoreSlim sem = base.EnsureAsyncActiveSemaphoreInitialized();
- sem.Release();
- }
- }
-
-
- public override Int32 ReadByte() {
-
- EnsureNotClosed();
- EnsureCanRead();
-
- if (_readPos == _readLen) {
-
- if (_writePos > 0)
- FlushWrite();
-
- EnsureBufferAllocated();
- _readLen = _stream.Read(_buffer, 0, _bufferSize);
- _readPos = 0;
- }
-
- if (_readPos == _readLen)
- return -1;
-
- Int32 b = _buffer[_readPos++];
- return b;
- }
-
-
- private void WriteToBuffer(Byte[] array, ref Int32 offset, ref Int32 count) {
-
- Int32 bytesToWrite = Math.Min(_bufferSize - _writePos, count);
-
- if (bytesToWrite <= 0)
- return;
-
- EnsureBufferAllocated();
- Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, bytesToWrite);
-
- _writePos += bytesToWrite;
- count -= bytesToWrite;
- offset += bytesToWrite;
- }
-
-
- private void WriteToBuffer(Byte[] array, ref Int32 offset, ref Int32 count, out Exception error) {
-
- try {
-
- error = null;
- WriteToBuffer(array, ref offset, ref count);
-
- } catch (Exception ex) {
- error = ex;
- }
- }
-
-
- public override void Write(Byte[] array, Int32 offset, Int32 count) {
-
- if (array == null)
- throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- EnsureNotClosed();
- EnsureCanWrite();
-
- if (_writePos == 0)
- ClearReadBufferBeforeWrite();
-
- #region Write algorithm comment
- // We need to use the buffer, while avoiding unnecessary buffer usage / memory copies.
- // We ASSUME that memory copies are much cheaper than writes to the underlying stream, so if an extra copy is
- // guaranteed to reduce the number of writes, we prefer it.
- // We pick a simple strategy that makes degenerate cases rare if our assumptions are right.
- //
- // For every write, we use a simple heuristic (below) to decide whether to use the buffer.
- // The heuristic has the desirable property (*) that if the specified user data can fit into the currently available
- // buffer space without filling it up completely, the heuristic will always tell us to use the buffer. It will also
- // tell us to use the buffer in cases where the current write would fill the buffer, but the remaining data is small
- // enough such that subsequent operations can use the buffer again.
- //
- // Algorithm:
- // Determine whether or not to buffer according to the heuristic (below).
- // If we decided to use the buffer:
- // Copy as much user data as we can into the buffer.
- // If we consumed all data: We are finished.
- // Otherwise, write the buffer out.
- // Copy the rest of user data into the now cleared buffer (no need to write out the buffer again as the heuristic
- // will prevent it from being filled twice).
- // If we decided not to use the buffer:
- // Can the data already in the buffer and current user data be combines to a single write
- // by allocating a "shadow" buffer of up to twice the size of _bufferSize (up to a limit to avoid LOH)?
- // Yes, it can:
- // Allocate a larger "shadow" buffer and ensure the buffered data is moved there.
- // Copy user data to the shadow buffer.
- // Write shadow buffer to the underlying stream in a single operation.
- // No, it cannot (amount of data is still too large):
- // Write out any data possibly in the buffer.
- // Write out user data directly.
- //
- // Heuristic:
- // If the subsequent write operation that follows the current write operation will result in a write to the
- // underlying stream in case that we use the buffer in the current write, while it would not have if we avoided
- // using the buffer in the current write (by writing current user data to the underlying stream directly), then we
- // prefer to avoid using the buffer since the corresponding memory copy is wasted (it will not reduce the number
- // of writes to the underlying stream, which is what we are optimising for).
- // ASSUME that the next write will be for the same amount of bytes as the current write (most common case) and
- // determine if it will cause a write to the underlying stream. If the next write is actually larger, our heuristic
- // still yields the right behaviour, if the next write is actually smaller, we may making an unnecessary write to
- // the underlying stream. However, this can only occur if the current write is larger than half the buffer size and
- // we will recover after one iteration.
- // We have:
- // useBuffer = (_writePos + count + count < _bufferSize + _bufferSize)
- //
- // Example with _bufferSize = 20, _writePos = 6, count = 10:
- //
- // +---------------------------------------+---------------------------------------+
- // | current buffer | next iteration's "future" buffer |
- // +---------------------------------------+---------------------------------------+
- // |0| | | | | | | | | |1| | | | | | | | | |2| | | | | | | | | |3| | | | | | | | | |
- // |0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|
- // +-----------+-------------------+-------------------+---------------------------+
- // | _writePos | current count | assumed next count|avail buff after next write|
- // +-----------+-------------------+-------------------+---------------------------+
- //
- // A nice property (*) of this heuristic is that it will always succeed if the user data completely fits into the
- // available buffer, i.e. if count < (_bufferSize - _writePos).
- #endregion Write algorithm comment
-
- Contract.Assert(_writePos < _bufferSize);
-
- Int32 totalUserBytes;
- bool useBuffer;
- checked { // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early:
- totalUserBytes = _writePos + count;
- useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize));
- }
-
- if (useBuffer) {
-
- WriteToBuffer(array, ref offset, ref count);
-
- if (_writePos < _bufferSize) {
-
- Contract.Assert(count == 0);
- return;
- }
-
- Contract.Assert(count >= 0);
- Contract.Assert(_writePos == _bufferSize);
- Contract.Assert(_buffer != null);
-
- _stream.Write(_buffer, 0, _writePos);
- _writePos = 0;
-
- WriteToBuffer(array, ref offset, ref count);
-
- Contract.Assert(count == 0);
- Contract.Assert(_writePos < _bufferSize);
-
- } else { // if (!useBuffer)
-
- // Write out the buffer if necessary.
- if (_writePos > 0) {
-
- Contract.Assert(_buffer != null);
- Contract.Assert(totalUserBytes >= _bufferSize);
-
- // Try avoiding extra write to underlying stream by combining previously buffered data with current user data:
- if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize) {
-
- EnsureShadowBufferAllocated();
- Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, count);
- _stream.Write(_buffer, 0, totalUserBytes);
- _writePos = 0;
- return;
- }
-
- _stream.Write(_buffer, 0, _writePos);
- _writePos = 0;
- }
-
- // Write out user data.
- _stream.Write(array, offset, count);
- }
- }
-
-
-
-
- public override IAsyncResult BeginWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state) {
-
- if (buffer == null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- // Previous version incorrectly threw NotSupported instead of ObjectDisposed. We keep that behaviour for back-compat.
- // EnsureNotClosed();
- if (_stream == null) __Error.ReadNotSupported();
- EnsureCanWrite();
-
- // Try to satisfy the request from the buffer synchronously. But still need a sem-lock in case that another
- // Async IO Task accesses the buffer concurrently. If we fail to acquire the lock without waiting, make this
- // an Async operation.
- SemaphoreSlim sem = base.EnsureAsyncActiveSemaphoreInitialized();
- Task semaphoreLockTask = sem.WaitAsync();
- if (semaphoreLockTask.Status == TaskStatus.RanToCompletion) {
-
- bool completeSynchronously = true;
- try {
- if (_writePos == 0)
- ClearReadBufferBeforeWrite();
-
- // If the write completely fits into the buffer, we can complete synchronously.
- Contract.Assert(_writePos < _bufferSize);
- completeSynchronously = (count < _bufferSize - _writePos);
-
- if (completeSynchronously) {
-
- Exception error;
- WriteToBuffer(buffer, ref offset, ref count, out error);
- Contract.Assert(count == 0);
-
- SynchronousAsyncResult asyncResult = (error == null)
- ? new SynchronousAsyncResult(state)
- : new SynchronousAsyncResult(error, state, isWrite: true);
- if (callback != null)
- callback(asyncResult);
-
- return asyncResult;
- }
- } finally {
- if (completeSynchronously) // if this is FALSE, we will be entering WriteToUnderlyingStreamAsync and releasing there.
- sem.Release();
- }
- }
-
- // Delegate to the async implementation.
- return BeginWriteToUnderlyingStream(buffer, offset, count, callback, state, semaphoreLockTask);
- }
-
-
- private IAsyncResult BeginWriteToUnderlyingStream(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state,
- Task semaphoreLockTask) {
-
- Task writeOp = WriteToUnderlyingStreamAsync(buffer, offset, count, CancellationToken.None, semaphoreLockTask, useApmPattern: true);
- return TaskToApm.Begin(writeOp, callback, state);
- }
-
-
- public override void EndWrite(IAsyncResult asyncResult) {
-
- if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
- Contract.EndContractBlock();
-
- var sAR = asyncResult as SynchronousAsyncResult;
- if (sAR != null) {
- SynchronousAsyncResult.EndWrite(asyncResult);
- return;
- }
-
- TaskToApm.End(asyncResult);
- }
-
-
- public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
-
- if (buffer == null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- // Fast path check for cancellation already requested
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled<Int32>(cancellationToken);
-
- EnsureNotClosed();
- EnsureCanWrite();
-
- // Try to satisfy the request from the buffer synchronously. But still need a sem-lock in case that another
- // Async IO Task accesses the buffer concurrently. If we fail to acquire the lock without waiting, make this
- // an Async operation.
- SemaphoreSlim sem = base.EnsureAsyncActiveSemaphoreInitialized();
- Task semaphoreLockTask = sem.WaitAsync();
- if (semaphoreLockTask.Status == TaskStatus.RanToCompletion) {
-
- bool completeSynchronously = true;
- try {
-
- if (_writePos == 0)
- ClearReadBufferBeforeWrite();
-
- Contract.Assert(_writePos < _bufferSize);
-
- // If the write completely fits into the buffer, we can complete synchronously:
- completeSynchronously = (count < _bufferSize - _writePos);
-
- if (completeSynchronously) {
-
- Exception error;
- WriteToBuffer(buffer, ref offset, ref count, out error);
- Contract.Assert(count == 0);
-
- return (error == null)
- ? Task.CompletedTask
- : Task.FromException(error);
- }
- } finally {
- if (completeSynchronously) // if this is FALSE, we will be entering WriteToUnderlyingStreamAsync and releasing there.
- sem.Release();
- }
- }
-
- // Delegate to the async implementation.
- return WriteToUnderlyingStreamAsync(buffer, offset, count, cancellationToken, semaphoreLockTask, useApmPattern: false);
- }
-
-
- /// <summary>BufferedStream should be as thin a wrapper as possible. We want that WriteAsync delegates to
- /// WriteAsync of the underlying _stream and that BeginWrite delegates to BeginWrite of the underlying stream,
- /// rather than calling the base Stream which implements the one in terms of the other. This allows BufferedStream
- /// to affect the semantics of the stream it wraps as little as possible. At the same time, we want to share as
- /// much code between the APM and the Async pattern implementations as possible. This method is called by both with
- /// a corresponding useApmPattern value. Recall that Task implements IAsyncResult.</summary>
- private async Task WriteToUnderlyingStreamAsync(Byte[] array, Int32 offset, Int32 count,
- CancellationToken cancellationToken,
- Task semaphoreLockTask, bool useApmPattern) {
-
- // (These should be Contract.Requires(..) but that method had some issues in async methods; using Assert(..) for now.)
- Contract.Assert(array != null);
- Contract.Assert(offset >= 0);
- Contract.Assert(count >= 0);
- Contract.Assert(array.Length - offset >= count);
- Contract.Assert(_stream != null);
- Contract.Assert(_stream.CanWrite);
- Contract.Assert(_bufferSize > 0);
- Contract.Assert(semaphoreLockTask != null);
-
- // See the LARGE COMMENT in Write(..) for the explanation of the write buffer algorithm.
-
- await semaphoreLockTask.ConfigureAwait(false);
- try {
-
- // The buffer might have been changed by another async task while we were waiting on the semaphore.
- // However, note that if we recalculate the sync completion condition to TRUE, then useBuffer will also be TRUE.
-
- if (_writePos == 0)
- ClearReadBufferBeforeWrite();
-
- Int32 totalUserBytes;
- bool useBuffer;
- checked { // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early:
- totalUserBytes = _writePos + count;
- useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize));
- }
-
- if (useBuffer) {
-
- WriteToBuffer(array, ref offset, ref count);
-
- if (_writePos < _bufferSize) {
-
- Contract.Assert(count == 0);
- return;
- }
-
- Contract.Assert(count >= 0);
- Contract.Assert(_writePos == _bufferSize);
- Contract.Assert(_buffer != null);
-
- if (useApmPattern) {
- EnsureBeginEndAwaitableAllocated();
- _stream.BeginWrite(_buffer, 0, _writePos, BeginEndAwaitableAdapter.Callback, _beginEndAwaitable);
- _stream.EndWrite(await _beginEndAwaitable);
- } else {
- await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false);
- }
- _writePos = 0;
-
- WriteToBuffer(array, ref offset, ref count);
-
- Contract.Assert(count == 0);
- Contract.Assert(_writePos < _bufferSize);
-
- } else { // if (!useBuffer)
-
- // Write out the buffer if necessary.
- if (_writePos > 0) {
-
- Contract.Assert(_buffer != null);
- Contract.Assert(totalUserBytes >= _bufferSize);
-
- // Try avoiding extra write to underlying stream by combining previously buffered data with current user data:
- if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize) {
-
- EnsureShadowBufferAllocated();
- Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, count);
- if (useApmPattern) {
- EnsureBeginEndAwaitableAllocated();
- _stream.BeginWrite(_buffer, 0, totalUserBytes, BeginEndAwaitableAdapter.Callback, _beginEndAwaitable);
- _stream.EndWrite(await _beginEndAwaitable);
- } else {
- await _stream.WriteAsync(_buffer, 0, totalUserBytes, cancellationToken).ConfigureAwait(false);
- }
- _writePos = 0;
- return;
- }
-
- if (useApmPattern) {
- EnsureBeginEndAwaitableAllocated();
- _stream.BeginWrite(_buffer, 0, _writePos, BeginEndAwaitableAdapter.Callback, _beginEndAwaitable);
- _stream.EndWrite(await _beginEndAwaitable);
- } else {
- await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false);
- }
- _writePos = 0;
- }
-
- // Write out user data.
- if (useApmPattern) {
- EnsureBeginEndAwaitableAllocated();
- _stream.BeginWrite(array, offset, count, BeginEndAwaitableAdapter.Callback, _beginEndAwaitable);
- _stream.EndWrite(await _beginEndAwaitable);
- } else {
- await _stream.WriteAsync(array, offset, count, cancellationToken).ConfigureAwait(false);
- }
- }
- } finally {
- SemaphoreSlim sem = base.EnsureAsyncActiveSemaphoreInitialized();
- sem.Release();
- }
- }
-
-
- public override void WriteByte(Byte value) {
-
- EnsureNotClosed();
-
- if (_writePos == 0) {
-
- EnsureCanWrite();
- ClearReadBufferBeforeWrite();
- EnsureBufferAllocated();
- }
-
- // We should not be flushing here, but only writing to the underlying stream, but previous version flushed, so we keep this.
- if (_writePos >= _bufferSize - 1)
- FlushWrite();
-
- _buffer[_writePos++] = value;
-
- Contract.Assert(_writePos < _bufferSize);
- }
-
-
- public override Int64 Seek(Int64 offset, SeekOrigin origin) {
-
- EnsureNotClosed();
- EnsureCanSeek();
-
- // If we have bytes in the WRITE buffer, flush them out, seek and be done.
- if (_writePos > 0) {
-
- // We should be only writing the buffer and not flushing,
- // but the previous version did flush and we stick to it for back-compat reasons.
- FlushWrite();
- return _stream.Seek(offset, origin);
- }
-
- // The buffer is either empty or we have a buffered READ.
-
- if (_readLen - _readPos > 0 && origin == SeekOrigin.Current) {
-
- // If we have bytes in the READ buffer, adjust the seek offset to account for the resulting difference
- // between this stream's position and the underlying stream's position.
- offset -= (_readLen - _readPos);
- }
-
- Int64 oldPos = Position;
- Contract.Assert(oldPos == _stream.Position + (_readPos - _readLen));
-
- Int64 newPos = _stream.Seek(offset, origin);
-
- // If the seek destination is still within the data currently in the buffer, we want to keep the buffer data and continue using it.
- // Otherwise we will throw away the buffer. This can only happen on READ, as we flushed WRITE data above.
-
- // The offset of the new/updated seek pointer within _buffer:
- _readPos = (Int32) (newPos - (oldPos - _readPos));
-
- // If the offset of the updated seek pointer in the buffer is still legal, then we can keep using the buffer:
- if (0 <= _readPos && _readPos < _readLen) {
-
- // Adjust the seek pointer of the underlying stream to reflect the amount of useful bytes in the read buffer:
- _stream.Seek(_readLen - _readPos, SeekOrigin.Current);
-
- } else { // The offset of the updated seek pointer is not a legal offset. Loose the buffer.
-
- _readPos = _readLen = 0;
- }
-
- Contract.Assert(newPos == Position, "newPos (=" + newPos + ") == Position (=" + Position + ")");
- return newPos;
- }
-
-
- public override void SetLength(Int64 value) {
-
- if (value < 0)
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NegFileSize"));
- Contract.EndContractBlock();
-
- EnsureNotClosed();
- EnsureCanSeek();
- EnsureCanWrite();
-
- Flush();
- _stream.SetLength(value);
- }
-
-} // class BufferedStream
-} // namespace
diff --git a/src/mscorlib/src/System/IO/Directory.cs b/src/mscorlib/src/System/IO/Directory.cs
index be74538d2d..d6b68222cd 100644
--- a/src/mscorlib/src/System/IO/Directory.cs
+++ b/src/mscorlib/src/System/IO/Directory.cs
@@ -15,168 +15,70 @@
**
===========================================================*/
-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)
{
if (path==null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (path.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"), "path");
+ throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"), nameof(path));
Contract.EndContractBlock();
- String fullPath = Path.GetFullPathInternal(path);
-
- String s = Path.GetDirectoryName(fullPath);
+ string fullPath = Path.GetFullPath(path);
+
+ string s = Path.GetDirectoryName(fullPath);
if (s==null)
return null;
return new DirectoryInfo(s);
}
- [System.Security.SecuritySafeCritical]
public static DirectoryInfo CreateDirectory(String path) {
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
Contract.EndContractBlock();
- return InternalCreateDirectoryHelper(path, true);
+ return InternalCreateDirectoryHelper(path);
}
- [System.Security.SecurityCritical]
- internal static DirectoryInfo UnsafeCreateDirectory(String path)
- {
- if (path == null)
- throw new ArgumentNullException("path");
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
- Contract.EndContractBlock();
-
- return InternalCreateDirectoryHelper(path, false);
- }
-
- [System.Security.SecurityCritical]
- internal static DirectoryInfo InternalCreateDirectoryHelper(String path, bool checkHost)
+ internal static DirectoryInfo InternalCreateDirectoryHelper(String path)
{
Contract.Requires(path != null);
Contract.Requires(path.Length != 0);
- 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);
-
-#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("path");
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
- Contract.EndContractBlock();
-
- String fullPath = Path.GetFullPathInternal(path);
+ String fullPath = Path.GetFullPath(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, null);
- 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
- // everything underneath it.
- internal static String GetDemandDir(string fullPath, bool thisDirOnly)
+ internal unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj)
{
- String demandPath;
-
- if (thisDirOnly) {
- if (fullPath.EndsWith( Path.DirectorySeparatorChar )
- || fullPath.EndsWith( Path.AltDirectorySeparatorChar ) )
- demandPath = fullPath + ".";
- else
- demandPath = fullPath + Path.DirectorySeparatorCharAsString + ".";
- }
- else {
- if (!(fullPath.EndsWith( Path.DirectorySeparatorChar )
- || fullPath.EndsWith( Path.AltDirectorySeparatorChar )) )
- demandPath = fullPath + Path.DirectorySeparatorCharAsString;
- else
- demandPath = fullPath;
- }
- return demandPath;
- }
-
- internal static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj)
- {
- InternalCreateDirectory(fullPath, path, dirSecurityObj, false);
- }
-
-
- [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.
- if (length >= 2 && Path.IsDirectorySeparator(fullPath[length - 1]))
+ if (length >= 2 && PathInternal.IsDirectorySeparator(fullPath[length - 1]))
length--;
- int lengthRoot = Path.GetRootLength(fullPath);
+ int lengthRoot = PathInternal.GetRootLength(fullPath);
// For UNC paths that are only // or ///
- if (length == 2 && Path.IsDirectorySeparator(fullPath[1]))
+ if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
throw new IOException(Environment.GetResourceString("IO.IO_CannotCreateDirectory", path));
// We can save a bunch of work if the directory we want to create already exists. This also
@@ -215,56 +117,9 @@ 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
- )
- {
- String[] securityList = new String[stackDir.Count];
- stackDir.CopyTo(securityList, 0);
- for (int j = 0 ; j < securityList.Length; j++)
- 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)
- {
- FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, String.Empty, demandPath);
- 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;
@@ -290,22 +145,10 @@ namespace System.IO {
firstError = currentError;
else {
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
- if (File.InternalExists(name) || (!InternalExists(name, out currentError) && currentError == Win32Native.ERROR_ACCESS_DENIED)) {
+ if (File.InternalExists(name) || (!InternalExists(name, out currentError) && currentError == Win32Native.ERROR_ACCESS_DENIED))
+ {
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) {}
+ errorString = name;
}
}
}
@@ -335,20 +178,12 @@ 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);
+ return InternalExistsHelper(path);
}
- [System.Security.SecurityCritical]
- internal static bool InternalExistsHelper(String path, bool checkHost) {
+ internal static bool InternalExistsHelper(String path) {
try
{
if (path == null)
@@ -356,23 +191,7 @@ namespace System.IO {
if (path.Length == 0)
return false;
- // Get fully qualified file name ending in \* for security check
-
- String fullPath = Path.GetFullPathInternal(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);
+ return InternalExists(Path.GetFullPath(path));
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
@@ -380,14 +199,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 +213,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,25 +221,6 @@ namespace System.IO {
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0);
}
- 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);
- }
- }
- }
-
public static DateTime GetCreationTime(String path)
{
return File.GetCreationTime(path);
@@ -433,25 +231,6 @@ namespace System.IO {
return File.GetCreationTimeUtc(path);
}
- 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);
- }
- }
- }
-
public static DateTime GetLastWriteTime(String path)
{
return File.GetLastWriteTime(path);
@@ -462,25 +241,6 @@ namespace System.IO {
return File.GetLastWriteTimeUtc(path);
}
- 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);
- }
- }
- }
-
public static DateTime GetLastAccessTime(String path)
{
return File.GetLastAccessTime(path);
@@ -489,36 +249,13 @@ 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("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)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -530,9 +267,9 @@ namespace System.IO {
public static String[] GetFiles(String path, String searchPattern)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -544,11 +281,11 @@ namespace System.IO {
public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -566,7 +303,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);
@@ -580,7 +316,7 @@ namespace System.IO {
public static String[] GetDirectories(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -592,9 +328,9 @@ namespace System.IO {
public static String[] GetDirectories(String path, String searchPattern)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -606,11 +342,11 @@ namespace System.IO {
public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -629,7 +365,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);
@@ -644,7 +379,7 @@ namespace System.IO {
public static String[] GetFileSystemEntries(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -656,9 +391,9 @@ namespace System.IO {
public static String[] GetFileSystemEntries(String path, String searchPattern)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -670,11 +405,11 @@ namespace System.IO {
public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
@@ -690,7 +425,6 @@ namespace System.IO {
return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption, true);
}
-
// Private class that holds search data that is passed around
// in the heap based stack recursion
internal sealed class SearchData
@@ -734,7 +468,7 @@ namespace System.IO {
public static IEnumerable<String> EnumerateDirectories(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
@@ -743,9 +477,9 @@ namespace System.IO {
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
@@ -754,11 +488,11 @@ namespace System.IO {
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, searchOption);
@@ -776,7 +510,7 @@ namespace System.IO {
public static IEnumerable<String> EnumerateFiles(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
@@ -786,9 +520,9 @@ namespace System.IO {
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
@@ -798,11 +532,11 @@ namespace System.IO {
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
@@ -822,7 +556,7 @@ namespace System.IO {
public static IEnumerable<String> EnumerateFileSystemEntries(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
@@ -832,9 +566,9 @@ namespace System.IO {
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
@@ -844,11 +578,11 @@ namespace System.IO {
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
@@ -882,7 +616,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);
@@ -914,29 +647,20 @@ namespace System.IO {
return result;
}
- [System.Security.SecuritySafeCritical]
public static String GetDirectoryRoot(String path) {
if (path==null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
-
- String fullPath = Path.GetFullPathInternal(path);
- String root = fullPath.Substring(0, Path.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
-
+
+ string fullPath = Path.GetFullPath(path);
+ string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath));
+
return root;
}
internal static String InternalGetDirectoryRoot(String path) {
if (path == null) return null;
- return path.Substring(0, Path.GetRootLength(path));
+ return path.Substring(0, PathInternal.GetRootLength(path));
}
/*===============================CurrentDirectory===============================
@@ -946,77 +670,10 @@ 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 = (
-#if FEATURE_PATHCOMPAT
- AppContextSwitches.UseLegacyPathHandling ? LegacyGetCurrentDirectory() :
-#endif
- NewGetCurrentDirectory());
-
- string demandPath = GetDemandDir(currentDirectory, true);
-
-#if FEATURE_CORECLR
- if (checkHost)
- {
- FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPath);
- state.EnsureState();
- }
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandPath, false, false);
-#endif
- return currentDirectory;
- }
-
-#if FEATURE_PATHCOMPAT
- [System.Security.SecurityCritical]
- private static String LegacyGetCurrentDirectory()
- {
- StringBuilder sb = StringBuilderCache.Acquire(Path.MaxPath + 1);
- if (Win32Native.GetCurrentDirectory(sb.Capacity, sb) == 0)
- __Error.WinIOError();
- String currentDirectory = sb.ToString();
- // Note that if we have somehow put our command prompt into short
- // file name mode (ie, by running edlin or a DOS grep, etc), then
- // this will return a short file name.
- if (currentDirectory.IndexOf('~') >= 0) {
- int r = Win32Native.GetLongPathName(currentDirectory, sb, sb.Capacity);
- if (r == 0 || r >= Path.MaxPath) {
- int errorCode = Marshal.GetLastWin32Error();
- if (r >= Path.MaxPath)
- errorCode = Win32Native.ERROR_FILENAME_EXCED_RANGE;
- if (errorCode != Win32Native.ERROR_FILE_NOT_FOUND &&
- errorCode != Win32Native.ERROR_PATH_NOT_FOUND &&
- errorCode != Win32Native.ERROR_INVALID_FUNCTION && // by design - enough said.
- errorCode != Win32Native.ERROR_ACCESS_DENIED)
- __Error.WinIOError(errorCode, String.Empty);
- }
- currentDirectory = sb.ToString();
- }
- StringBuilderCache.Release(sb);
- String demandPath = GetDemandDir(currentDirectory, true);
-
- return currentDirectory;
- }
-#endif // FEATURE_PATHCOMPAT
-
- [System.Security.SecurityCritical]
- private static string NewGetCurrentDirectory()
- {
- using (StringBuffer buffer = new StringBuffer(PathInternal.MaxShortPath))
+ // Start with a buffer the size of MAX_PATH
+ using (StringBuffer buffer = new StringBuffer(260))
{
uint result = 0;
while ((result = Win32Native.GetCurrentDirectoryW(buffer.CharCapacity, buffer.GetHandle())) > buffer.CharCapacity)
@@ -1033,35 +690,23 @@ namespace System.IO {
#if !PLATFORM_UNIX
if (buffer.Contains('~'))
- return LongPathHelper.GetLongPathName(buffer);
+ return Path.GetFullPath(buffer.ToString());
#endif
return buffer.ToString();
}
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
public static void SetCurrentDirectory(String path)
{
if (path==null)
throw new ArgumentNullException("value");
if (path.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
- Contract.EndContractBlock();
if (path.Length >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- // This will have some large effects on the rest of the runtime
- // and other appdomains in this process. Demand unmanaged code.
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#pragma warning restore 618
- String fulldestDirName = Path.GetFullPathInternal(path);
+ String fulldestDirName = Path.GetFullPath(path);
if (!Win32Native.SetCurrentDirectory(fulldestDirName)) {
// If path doesn't exist, this sets last error to 2 (File
@@ -1074,52 +719,19 @@ 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) {
+ public static void Move(String sourceDirName,String destDirName)
+ {
if (sourceDirName==null)
- throw new ArgumentNullException("sourceDirName");
+ throw new ArgumentNullException(nameof(sourceDirName));
if (sourceDirName.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceDirName");
-
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceDirName));
if (destDirName==null)
- throw new ArgumentNullException("destDirName");
+ throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName");
- Contract.EndContractBlock();
-
- String fullsourceDirName = Path.GetFullPathInternal(sourceDirName);
- String sourcePath = GetDemandDir(fullsourceDirName, false);
-
- if (PathInternal.IsDirectoryTooLong(sourcePath))
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- String fulldestDirName = Path.GetFullPathInternal(destDirName);
- String destPath = GetDemandDir(fulldestDirName, false);
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destDirName));
- 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
+ String sourcePath = Path.GetFullPath(sourceDirName);
+ String destPath = Path.GetFullPath(destDirName);
if (String.Compare(sourcePath, destPath, StringComparison.OrdinalIgnoreCase) == 0)
throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent"));
@@ -1135,7 +747,7 @@ namespace System.IO {
if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // Source dir not found
{
hr = Win32Native.ERROR_PATH_NOT_FOUND;
- __Error.WinIOError(hr, fullsourceDirName);
+ __Error.WinIOError(hr, sourcePath);
}
// This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons.
if (hr == Win32Native.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp.
@@ -1144,49 +756,22 @@ namespace System.IO {
}
}
- [System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
- String fullPath = Path.GetFullPathInternal(path);
- Delete(fullPath, path, false, true);
+ String fullPath = Path.GetFullPath(path);
+ Delete(fullPath, path, false);
}
- [System.Security.SecuritySafeCritical]
public static void Delete(String path, bool recursive)
{
- String fullPath = Path.GetFullPathInternal(path);
- Delete(fullPath, path, recursive, true);
+ String fullPath = Path.GetFullPath(path);
+ Delete(fullPath, path, recursive);
}
- [System.Security.SecurityCritical]
- internal static void UnsafeDelete(String path, bool recursive)
- {
- String fullPath = Path.GetFullPathInternal(path);
- Delete(fullPath, path, recursive, false);
- }
-
- // Called from DirectoryInfo as well. FullPath is fully qualified,
+ // 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)
+ internal static void Delete(String fullPath, String userPath, bool recursive)
{
- String demandPath;
-
- // 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,
// but for now we're much safer if we err on the conservative side.
@@ -1206,10 +791,7 @@ namespace System.IO {
DeleteHelper(fullPath, userPath, recursive, true);
}
- // 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
+ // Note that fullPath is fully qualified, while userPath may be relative.
private static void DeleteHelper(String fullPath, String userPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
bool r;
@@ -1229,12 +811,12 @@ namespace System.IO {
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
// Open a Find handle
- using (SafeFindHandle hnd = Win32Native.FindFirstFile(fullPath+Path.DirectorySeparatorCharAsString+"*", data)) {
+ using (SafeFindHandle hnd = Win32Native.FindFirstFile(fullPath + Path.DirectorySeparatorChar + "*", data)) {
if (hnd.IsInvalid) {
hr = Marshal.GetLastWin32Error();
__Error.WinIOError(hr, fullPath);
}
-
+
do {
bool isDir = (0!=(data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY));
if (isDir) {
@@ -1248,8 +830,8 @@ namespace System.IO {
// itself.
bool shouldRecurse = (0 == (data.dwFileAttributes & (int) FileAttributes.ReparsePoint));
if (shouldRecurse) {
- String newFullPath = Path.InternalCombine(fullPath, data.cFileName);
- String newUserPath = Path.InternalCombine(userPath, data.cFileName);
+ String newFullPath = Path.Combine(fullPath, data.cFileName);
+ String newUserPath = Path.Combine(userPath, data.cFileName);
try {
DeleteHelper(newFullPath, newUserPath, recursive, false);
}
@@ -1264,7 +846,7 @@ namespace System.IO {
// unmount it.
if (data.dwReserved0 == Win32Native.IO_REPARSE_TAG_MOUNT_POINT) {
// Use full path plus a trailing '\'
- String mountPoint = Path.InternalCombine(fullPath, data.cFileName + Path.DirectorySeparatorChar);
+ String mountPoint = Path.Combine(fullPath, data.cFileName + Path.DirectorySeparatorChar);
r = Win32Native.DeleteVolumeMountPoint(mountPoint);
if (!r) {
hr = Marshal.GetLastWin32Error();
@@ -1283,7 +865,7 @@ namespace System.IO {
// RemoveDirectory on a symbolic link will
// remove the link itself.
- String reparsePoint = Path.InternalCombine(fullPath, data.cFileName);
+ String reparsePoint = Path.Combine(fullPath, data.cFileName);
r = Win32Native.RemoveDirectory(reparsePoint);
if (!r) {
hr = Marshal.GetLastWin32Error();
@@ -1301,7 +883,7 @@ namespace System.IO {
}
}
else {
- String fileName = Path.InternalCombine(fullPath, data.cFileName);
+ String fileName = Path.Combine(fullPath, data.cFileName);
r = Win32Native.DeleteFile(fileName);
if (!r) {
hr = Marshal.GetLastWin32Error();
@@ -1346,44 +928,6 @@ namespace System.IO {
__Error.WinIOError(hr, fullPath);
}
}
-
- // 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;
- }
-
- 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;
- private const int OPEN_EXISTING = 0x00000003;
- private const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
}
-
}
diff --git a/src/mscorlib/src/System/IO/DirectoryInfo.cs b/src/mscorlib/src/System/IO/DirectoryInfo.cs
index f7b0709e9e..c4c350d245 100644
--- a/src/mscorlib/src/System/IO/DirectoryInfo.cs
+++ b/src/mscorlib/src/System/IO/DirectoryInfo.cs
@@ -15,63 +15,33 @@
**
===========================================================*/
-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;
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 {
- private String[] demandDir;
-
-#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
+ public sealed class DirectoryInfo : FileSystemInfo
+ {
+ // Migrating InheritanceDemands requires this default ctor, so we can annotate it.
private DirectoryInfo(){}
-
- [System.Security.SecurityCritical]
- public static DirectoryInfo UnsafeCreateDirectoryInfo(String path)
- {
- if (path == null)
- throw new ArgumentNullException("path");
- Contract.EndContractBlock();
-
- DirectoryInfo di = new DirectoryInfo();
- di.Init(path, false);
- return di;
- }
-#endif
-
- [System.Security.SecuritySafeCritical]
public DirectoryInfo(String path)
{
if (path==null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
- Init(path, true);
+ Init(path);
}
- [System.Security.SecurityCritical]
- private void Init(String path, bool checkHost)
+ private void Init(String path)
{
// Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead
if ((path.Length == 2) && (path[1] == ':'))
@@ -83,138 +53,79 @@ namespace System.IO {
OriginalPath = path;
}
- // Must fully qualify the path for the security check
- String fullPath = Path.GetFullPathInternal(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;
+ FullPath = Path.GetFullPath(path); ;
DisplayPath = GetDisplayName(OriginalPath, FullPath);
}
-#if FEATURE_CORESYSTEM
- [System.Security.SecuritySafeCritical]
-#endif //FEATURE_CORESYSTEM
internal DirectoryInfo(String fullPath, bool junk)
{
- Contract.Assert(Path.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);
FullPath = fullPath;
DisplayPath = GetDisplayName(OriginalPath, FullPath);
- 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
// those cases, as well as avoiding mangling "c:\".
String s = FullPath;
if (s.Length > 3 && s.EndsWith(Path.DirectorySeparatorChar))
- s = FullPath.Substring(0, FullPath.Length - 1);
+ s = FullPath.Substring(0, FullPath.Length - 1);
parentName = Path.GetDirectoryName(s);
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;
+
+ return new DirectoryInfo(parentName, false);
}
}
-
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
public DirectoryInfo CreateSubdirectory(String path) {
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
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)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return CreateSubdirectoryHelper(path, directorySecurity);
}
-#endif // FEATURE_MACL
- [System.Security.SecurityCritical] // auto-generated
private DirectoryInfo CreateSubdirectoryHelper(String path, Object directorySecurity)
{
Contract.Requires(path != null);
- String newDirs = Path.InternalCombine(FullPath, path);
- String fullPath = Path.GetFullPathInternal(newDirs);
+ String newDirs = Path.Combine(FullPath, path);
+ String fullPath = Path.GetFullPath(newDirs);
if (0!=String.Compare(FullPath,0,fullPath,0, FullPath.Length,StringComparison.OrdinalIgnoreCase)) {
String displayPath = __Error.GetDisplayablePath(DisplayPath, false);
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSubPath", path, displayPath));
}
- // 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);
// Check for read permission to directory we hand back by calling this constructor.
@@ -223,23 +134,11 @@ namespace System.IO {
public void Create()
{
- Directory.InternalCreateDirectory(FullPath, OriginalPath, null, true);
+ Directory.InternalCreateDirectory(FullPath, OriginalPath, null);
}
-#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
@@ -248,7 +147,6 @@ namespace System.IO {
Refresh();
if (_dataInitialised != 0) // Refresh was unable to initialise the data
return false;
-
return _data.fileAttributes != -1 && (_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0;
}
catch
@@ -257,30 +155,13 @@ 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").
public FileInfo[] GetFiles(String searchPattern)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly);
@@ -291,9 +172,9 @@ namespace System.IO {
public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, searchOption);
@@ -328,7 +209,7 @@ namespace System.IO {
public FileSystemInfo[] GetFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
@@ -339,9 +220,9 @@ namespace System.IO {
public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, searchOption);
@@ -372,7 +253,7 @@ namespace System.IO {
public DirectoryInfo[] GetDirectories(String searchPattern)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
@@ -384,9 +265,9 @@ namespace System.IO {
public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, searchOption);
@@ -413,7 +294,7 @@ namespace System.IO {
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly);
@@ -422,9 +303,9 @@ namespace System.IO {
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, searchOption);
@@ -446,7 +327,7 @@ namespace System.IO {
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly);
@@ -455,9 +336,9 @@ namespace System.IO {
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, searchOption);
@@ -479,7 +360,7 @@ namespace System.IO {
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
@@ -488,9 +369,9 @@ namespace System.IO {
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
- throw new ArgumentNullException("searchPattern");
+ throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, searchOption);
@@ -503,7 +384,7 @@ namespace System.IO {
return FileSystemEnumerableFactory.CreateFileSystemInfoIterator(FullPath, OriginalPath, searchPattern, searchOption);
}
-
+
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
@@ -512,61 +393,27 @@ namespace System.IO {
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
- //
-
public DirectoryInfo Root {
- [System.Security.SecuritySafeCritical]
get
{
- String demandPath;
- int rootLength = Path.GetRootLength(FullPath);
+ int rootLength = PathInternal.GetRootLength(FullPath);
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("destDirName");
+ throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName");
+ 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.GetFullPathInternal(destDirName);
- String demandPath;
+
+ String fullDestDirName = Path.GetFullPath(destDirName);
if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar))
fullDestDirName = fullDestDirName + Path.DirectorySeparatorChar;
- demandPath = fullDestDirName + '.';
-
- // Demand read & write permission to destination. The reason is
- // we hand back a DirectoryInfo to the destination that would allow
- // you to read a directory listing from that directory. Sure, you
- // 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;
@@ -599,22 +446,19 @@ namespace System.IO {
FullPath = fullDestDirName;
OriginalPath = destDirName;
DisplayPath = GetDisplayName(OriginalPath, FullPath);
- demandDir = new String[] { Directory.GetDemandDir(FullPath, true) };
// Flush any cached information about the directory.
_dataInitialised = -1;
}
- [System.Security.SecuritySafeCritical]
public override void Delete()
{
- Directory.Delete(FullPath, OriginalPath, false, true);
+ Directory.Delete(FullPath, OriginalPath, false);
}
- [System.Security.SecuritySafeCritical]
public void Delete(bool recursive)
{
- Directory.Delete(FullPath, OriginalPath, recursive, true);
+ Directory.Delete(FullPath, OriginalPath, recursive);
}
// Returns the fully qualified path
@@ -625,8 +469,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 +481,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)
@@ -666,7 +506,6 @@ namespace System.IO {
}
return dirName;
}
-
- }
+ }
}
diff --git a/src/mscorlib/src/System/IO/DriveInfo.cs b/src/mscorlib/src/System/IO/DriveInfo.cs
deleted file mode 100644
index be75e8979d..0000000000
--- a/src/mscorlib/src/System/IO/DriveInfo.cs
+++ /dev/null
@@ -1,281 +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: Exposes routines for exploring a drive.
-**
-**
-===========================================================*/
-
-using System;
-using System.Text;
-using System.Runtime.InteropServices;
-using Microsoft.Win32;
-using System.Security.Permissions;
-using System.Runtime.Serialization;
-using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
-
-namespace System.IO
-{
- // Matches Win32's DRIVE_XXX #defines from winbase.h
- [Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum DriveType
- {
- Unknown = 0,
- NoRootDirectory = 1,
- Removable = 2,
- Fixed = 3,
- Network = 4,
- CDRom = 5,
- Ram = 6
- }
-
- // Ideally we'll get a better security permission, but possibly
- // not for Whidbey.
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- [ComVisible(true)]
- public sealed class DriveInfo
-#if FEATURE_SERIALIZATION
- : ISerializable
-#endif
- {
- private String _name;
-
- private const String NameField = "_name"; // For serialization
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public DriveInfo(String driveName)
- {
- if (driveName == null)
- throw new ArgumentNullException("driveName");
- Contract.EndContractBlock();
- if (driveName.Length == 1)
- _name = driveName + ":\\";
- else {
- // GetPathRoot does not check all invalid characters
- Path.CheckInvalidPathChars(driveName);
- _name = Path.GetPathRoot(driveName);
- // Disallow null or empty drive letters and UNC paths
- if (_name == null || _name.Length == 0 || _name.StartsWith("\\\\", StringComparison.Ordinal))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDriveLetterOrRootDir"));
- }
- // We want to normalize to have a trailing backslash so we don't have two equivalent forms and
- // because some Win32 API don't work without it.
- if (_name.Length == 2 && _name[1] == ':') {
- _name = _name + "\\";
- }
-
- // Now verify that the drive letter could be a real drive name.
- // On Windows this means it's between A and Z, ignoring case.
- // On a Unix platform, perhaps this should be a device name with
- // a partition like /dev/hdc0, or possibly a mount point.
- char letter = driveName[0];
- if (!((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z')))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDriveLetterOrRootDir"));
-
- // Now do a security check.
- String demandPath = _name + '.';
- 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.
- _name = (String) info.GetValue(NameField, typeof(String));
-
- // Now do a security check.
- String demandPath = _name + '.';
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPath).Demand();
- }
-
- public String Name {
- get { return _name; }
- }
-
- public DriveType DriveType {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- // GetDriveType can't fail
- return (DriveType) Win32Native.GetDriveType(Name);
- }
- }
-
- public String DriveFormat {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- const int volNameLen = 50;
- StringBuilder volumeName = new StringBuilder(volNameLen);
- const int fileSystemNameLen = 50;
- StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
- int serialNumber, maxFileNameLen, fileSystemFlags;
-
- int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
- bool r = Win32Native.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
- if (!r) {
- int errorCode = Marshal.GetLastWin32Error();
- __Error.WinIODriveError(Name, errorCode);
- }
- }
- finally {
- Win32Native.SetErrorMode(oldMode);
- }
- return fileSystemName.ToString();
- }
- }
-
- 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);
- try {
- bool r = Win32Native.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
- if (!r)
- __Error.WinIODriveError(Name);
- }
- finally {
- Win32Native.SetErrorMode(oldMode);
- }
- return userBytes;
- }
- }
-
- public long TotalFreeSpace {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- long userBytes, totalBytes, freeBytes;
- int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
- bool r = Win32Native.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
- if (!r)
- __Error.WinIODriveError(Name);
- }
- finally {
- Win32Native.SetErrorMode(oldMode);
- }
- return freeBytes;
- }
- }
-
- 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.
- long userBytes, totalBytes, freeBytes;
- int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
- bool r = Win32Native.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
- if (!r)
- __Error.WinIODriveError(Name);
- }
- finally {
- Win32Native.SetErrorMode(oldMode);
- }
- return totalBytes;
- }
- }
-
- public static DriveInfo[] GetDrives()
- {
- // Directory.GetLogicalDrives demands unmanaged code permission
- String[] drives = Directory.GetLogicalDrives();
- DriveInfo[] di = new DriveInfo[drives.Length];
- for(int i=0; i<drives.Length; i++)
- di[i] = new DriveInfo(drives[i]);
- return di;
- }
-
- public DirectoryInfo RootDirectory {
- get {
- return new DirectoryInfo(Name);
- }
- }
-
- // 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.
- const int volNameLen = 50;
- StringBuilder volumeName = new StringBuilder(volNameLen);
- const int fileSystemNameLen = 50;
- StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
- int serialNumber, maxFileNameLen, fileSystemFlags;
-
- int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
- bool r = Win32Native.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
- if (!r) {
- int errorCode = Marshal.GetLastWin32Error();
- // Win9x appears to return ERROR_INVALID_DATA when a
- // drive doesn't exist.
- if (errorCode == Win32Native.ERROR_INVALID_DATA)
- errorCode = Win32Native.ERROR_INVALID_DRIVE;
- __Error.WinIODriveError(Name, errorCode);
- }
- }
- finally {
- Win32Native.SetErrorMode(oldMode);
- }
- return volumeName.ToString();
- }
- [System.Security.SecuritySafeCritical] // auto-generated
- set {
- String demandPath = _name + '.';
- new FileIOPermission(FileIOPermissionAccess.Write, demandPath).Demand();
-
- int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
- bool r = Win32Native.SetVolumeLabel(Name, value);
- if (!r) {
- int errorCode = Marshal.GetLastWin32Error();
- // Provide better message
- if (errorCode == Win32Native.ERROR_ACCESS_DENIED)
- throw new UnauthorizedAccessException(Environment.GetResourceString("InvalidOperation_SetVolumeLabelFailed"));
- __Error.WinIODriveError(Name, errorCode);
- }
- }
- finally {
- Win32Native.SetErrorMode(oldMode);
- }
- }
- }
-
- public override String ToString()
- {
- return Name;
- }
-
-#if FEATURE_SERIALIZATION
- /// <internalonly/>
- [System.Security.SecurityCritical]
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // No need for an additional security check - everything is public.
- info.AddValue(NameField, _name, typeof(String));
- }
-#endif
-
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsPinned.cs b/src/mscorlib/src/System/IO/EncodingCache.cs
index e796d1a1e7..53379bc77f 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsPinned.cs
+++ b/src/mscorlib/src/System/IO/EncodingCache.cs
@@ -2,10 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Runtime.CompilerServices
+using System.Text;
+
+namespace System.IO
{
- // Indicates that the modified instance is pinned in memory.
- public static class IsPinned
+ internal static class EncodingCache
{
+ internal static readonly Encoding UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
}
}
diff --git a/src/mscorlib/src/System/IO/File.cs b/src/mscorlib/src/System/IO/File.cs
index cfcb469bc3..9f89f81a91 100644
--- a/src/mscorlib/src/System/IO/File.cs
+++ b/src/mscorlib/src/System/IO/File.cs
@@ -14,34 +14,32 @@
**
===========================================================*/
-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)]
public static class File
{
+ private const int ERROR_INVALID_PARAMETER = 87;
+ internal const int GENERIC_READ = unchecked((int)0x80000000);
+
private const int GetFileExInfoStandard = 0;
public static StreamReader OpenText(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return new StreamReader(path);
}
@@ -49,7 +47,7 @@ namespace System.IO {
public static StreamWriter CreateText(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return new StreamWriter(path,false);
}
@@ -57,7 +55,7 @@ namespace System.IO {
public static StreamWriter AppendText(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return new StreamWriter(path,true);
}
@@ -67,88 +65,51 @@ namespace System.IO {
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
- //
- // The caller must have certain FileIOPermissions. The caller must have
- // Read permission to sourceFileName and Create
- // and Write permissions to destFileName.
- //
public static void Copy(String sourceFileName, String destFileName) {
if (sourceFileName == null)
- throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
+ throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
- throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
+ throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceFileName));
if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
Contract.EndContractBlock();
- InternalCopy(sourceFileName, destFileName, false, true);
+ InternalCopy(sourceFileName, destFileName, false);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
- //
- // The caller must have certain FileIOPermissions. The caller must have
- // Read permission to sourceFileName
- // and Write permissions to destFileName.
- //
public static void Copy(String sourceFileName, String destFileName, bool overwrite) {
if (sourceFileName == null)
- throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
+ throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
- throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
+ throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceFileName));
if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
Contract.EndContractBlock();
- InternalCopy(sourceFileName, destFileName, overwrite, true);
- }
-
- [System.Security.SecurityCritical]
- internal static void UnsafeCopy(String sourceFileName, String destFileName, bool overwrite) {
- if (sourceFileName == null)
- throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
- if (destFileName == null)
- throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
- if (sourceFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
- if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
- Contract.EndContractBlock();
-
- InternalCopy(sourceFileName, destFileName, overwrite, false);
+ InternalCopy(sourceFileName, destFileName, overwrite);
}
/// <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)
+ {
Contract.Requires(sourceFileName != null);
Contract.Requires(destFileName != null);
Contract.Requires(sourceFileName.Length > 0);
Contract.Requires(destFileName.Length > 0);
- String fullSourceFileName = Path.GetFullPathInternal(sourceFileName);
- String fullDestFileName = Path.GetFullPathInternal(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
-
+ String fullSourceFileName = Path.GetFullPath(sourceFileName);
+ String fullDestFileName = Path.GetFullPath(destFileName);
+
bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite);
if (!r) {
// Save Win32 error because subsequent checks will overwrite this HRESULT.
@@ -156,14 +117,6 @@ namespace System.IO {
String fileName = destFileName;
if (errorCode != Win32Native.ERROR_FILE_EXISTS) {
- // 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, FileStream.GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) {
- if (handle.IsInvalid)
- fileName = sourceFileName;
- }
-
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
if (Directory.InternalExists(fullDestFileName))
throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName);
@@ -172,19 +125,14 @@ namespace System.IO {
__Error.WinIOError(errorCode, fileName);
}
-
+
return fullDestFileName;
}
-
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite accessand cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
- //
- // Your application must have Create, Read, and Write permissions to
- // the file.
- //
public static FileStream Create(String path) {
return Create(path, FileStream.DefaultBufferSize);
}
@@ -193,10 +141,6 @@ namespace System.IO {
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
- //
- // Your application must have Create, Read, and Write permissions to
- // the file.
- //
public static FileStream Create(String path, int bufferSize) {
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize);
}
@@ -206,57 +150,23 @@ 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.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped.
- //
- // 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("path");
+ throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
-
- InternalDelete(path, true);
- }
- [System.Security.SecurityCritical]
- internal static void UnsafeDelete(String path)
- {
- if (path == null)
- throw new ArgumentNullException("path");
- Contract.EndContractBlock();
-
- InternalDelete(path, false);
+ InternalDelete(path);
}
- [System.Security.SecurityCritical]
- internal static void InternalDelete(String path, bool checkHost)
+ internal static void InternalDelete(String path)
{
- String fullPath = Path.GetFullPathInternal(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
+ String fullPath = Path.GetFullPath(path);
bool r = Win32Native.DeleteFile(fullPath);
if (!r) {
int hr = Marshal.GetLastWin32Error();
@@ -267,76 +177,16 @@ namespace System.IO {
}
}
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public static void Decrypt(String path)
- {
- if (path == null)
- throw new ArgumentNullException("path");
- Contract.EndContractBlock();
-
- String fullPath = Path.GetFullPathInternal(path);
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, fullPath, false, false);
-
- bool r = Win32Native.DecryptFile(fullPath, 0);
- if (!r) {
- int errorCode = Marshal.GetLastWin32Error();
- if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
- // Check to see if the file system is not NTFS. If so,
- // throw a different exception.
- DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath));
- if (!String.Equals("NTFS", di.DriveFormat))
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS"));
- }
- __Error.WinIOError(errorCode, fullPath);
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public static void Encrypt(String path)
- {
- if (path == null)
- throw new ArgumentNullException("path");
- Contract.EndContractBlock();
-
- String fullPath = Path.GetFullPathInternal(path);
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, fullPath, false, false);
-
- bool r = Win32Native.EncryptFile(fullPath);
- if (!r) {
- int errorCode = Marshal.GetLastWin32Error();
- if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
- // Check to see if the file system is not NTFS. If so,
- // throw a different exception.
- DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath));
- if (!String.Equals("NTFS", di.DriveFormat))
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS"));
- }
- __Error.WinIOError(errorCode, fullPath);
- }
- }
-
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
- //
- // Your application must have Read permission for the target directory.
- //
- [System.Security.SecuritySafeCritical]
public static bool Exists(String path)
{
- return InternalExistsHelper(path, true);
+ return InternalExistsHelper(path);
}
- [System.Security.SecurityCritical]
- internal static bool UnsafeExists(String path)
- {
- return InternalExistsHelper(path, false);
- }
-
- [System.Security.SecurityCritical]
- private static bool InternalExistsHelper(String path, bool checkHost)
+ private static bool InternalExistsHelper(String path)
{
try
{
@@ -345,26 +195,17 @@ namespace System.IO {
if (path.Length == 0)
return false;
- path = Path.GetFullPathInternal(path);
+ path = Path.GetFullPath(path);
+
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
- // GetFullPathInternal should never return null
- Contract.Assert(path != null, "File.Exists: GetFullPathInternal returned null");
- if (path.Length > 0 && Path.IsDirectorySeparator(path[path.Length - 1]))
+ // GetFullPath should never return 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);
}
catch (ArgumentException) { }
@@ -376,7 +217,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);
@@ -397,51 +237,19 @@ namespace System.IO {
return new FileStream(path, mode, access, share);
}
- 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);
- }
- }
- }
-
- [System.Security.SecuritySafeCritical]
public static DateTime GetCreationTime(String path)
{
- return InternalGetCreationTimeUtc(path, true).ToLocalTime();
+ return InternalGetCreationTimeUtc(path).ToLocalTime();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetCreationTimeUtc(String path)
{
- return InternalGetCreationTimeUtc(path, false); // this API isn't exposed in Silverlight
+ return InternalGetCreationTimeUtc(path); // this API isn't exposed in Silverlight
}
- [System.Security.SecurityCritical]
- private static DateTime InternalGetCreationTimeUtc(String path, bool checkHost)
+ private static DateTime InternalGetCreationTimeUtc(String path)
{
- String fullPath = Path.GetFullPathInternal(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
+ String fullPath = Path.GetFullPath(path);
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
@@ -452,51 +260,19 @@ namespace System.IO {
return DateTime.FromFileTimeUtc(dt);
}
- 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);
- }
- }
- }
-
- [System.Security.SecuritySafeCritical]
public static DateTime GetLastAccessTime(String path)
{
- return InternalGetLastAccessTimeUtc(path, true).ToLocalTime();
+ return InternalGetLastAccessTimeUtc(path).ToLocalTime();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastAccessTimeUtc(String path)
{
- return InternalGetLastAccessTimeUtc(path, false); // this API isn't exposed in Silverlight
+ return InternalGetLastAccessTimeUtc(path);
}
- [System.Security.SecurityCritical]
- private static DateTime InternalGetLastAccessTimeUtc(String path, bool checkHost)
- {
- String fullPath = Path.GetFullPathInternal(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
+ private static DateTime InternalGetLastAccessTimeUtc(String path)
+ {
+ String fullPath = Path.GetFullPath(path);
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
@@ -507,51 +283,19 @@ namespace System.IO {
return DateTime.FromFileTimeUtc(dt);
}
- 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);
- }
- }
- }
-
- [System.Security.SecuritySafeCritical]
public static DateTime GetLastWriteTime(String path)
{
- return InternalGetLastWriteTimeUtc(path, true).ToLocalTime();
+ return InternalGetLastWriteTimeUtc(path).ToLocalTime();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastWriteTimeUtc(String path)
{
- return InternalGetLastWriteTimeUtc(path, false); // this API isn't exposed in Silverlight
+ return InternalGetLastWriteTimeUtc(path);
}
- [System.Security.SecurityCritical]
- private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost)
+ private static DateTime InternalGetLastWriteTimeUtc(String path)
{
- String fullPath = Path.GetFullPathInternal(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
+ String fullPath = Path.GetFullPath(path);
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
@@ -562,16 +306,9 @@ namespace System.IO {
return DateTime.FromFileTimeUtc(dt);
}
- [System.Security.SecuritySafeCritical]
public static FileAttributes GetAttributes(String path)
{
- String fullPath = Path.GetFullPathInternal(path);
-#if FEATURE_CORECLR
- FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
- state.EnsureState();
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
+ String fullPath = Path.GetFullPath(path);
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true);
@@ -581,17 +318,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.GetFullPathInternal(path);
-#if !FEATURE_CORECLR
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false);
-#endif
+ String fullPath = Path.GetFullPath(path);
bool r = Win32Native.SetFileAttributes(fullPath, (int) fileAttributes);
if (!r) {
int hr = Marshal.GetLastWin32Error();
@@ -601,158 +330,88 @@ 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("fileSecurity");
- Contract.EndContractBlock();
-
- String fullPath = Path.GetFullPathInternal(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);
}
-
public static FileStream OpenWrite(String path) {
return new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
- return InternalReadAllText(path, Encoding.UTF8, true);
+ return InternalReadAllText(path, Encoding.UTF8);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path, Encoding encoding)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (encoding == null)
- throw new ArgumentNullException("encoding");
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
- return InternalReadAllText(path, encoding, true);
- }
-
- [System.Security.SecurityCritical]
- internal static String UnsafeReadAllText(String path)
- {
- if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
- return InternalReadAllText(path, Encoding.UTF8, false);
+ return InternalReadAllText(path, encoding);
}
- [System.Security.SecurityCritical]
- private static String InternalReadAllText(String path, Encoding encoding, bool checkHost)
+ private static String InternalReadAllText(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
- using (StreamReader sr = new StreamReader(path, encoding, true, StreamReader.DefaultBufferSize, checkHost))
+ using (StreamReader sr = new StreamReader(path, encoding, true, StreamReader.DefaultBufferSize))
return sr.ReadToEnd();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
- InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, true);
+ InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents, Encoding encoding)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (encoding == null)
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
- InternalWriteAllText(path, contents, encoding, true);
+ InternalWriteAllText(path, contents, encoding);
}
-
- [System.Security.SecurityCritical]
- internal static void UnsafeWriteAllText(String path, String contents)
- {
- if (path == null)
- throw new ArgumentNullException("path");
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
- InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, false);
- }
-
- [System.Security.SecurityCritical]
- private static void InternalWriteAllText(String path, String contents, Encoding encoding, bool checkHost)
+ private static void InternalWriteAllText(String path, String contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
- using (StreamWriter sw = new StreamWriter(path, false, encoding, StreamWriter.DefaultBufferSize, checkHost))
+ using (StreamWriter sw = new StreamWriter(path, false, encoding, StreamWriter.DefaultBufferSize))
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;
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
- FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost)) {
+ FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false)) {
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
@@ -771,43 +430,27 @@ namespace System.IO {
return bytes;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllBytes(String path, byte[] bytes)
{
if (path == null)
- throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
+ throw new ArgumentNullException(nameof(path), Environment.GetResourceString("ArgumentNull_Path"));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bytes == null)
- throw new ArgumentNullException("bytes");
+ throw new ArgumentNullException(nameof(bytes));
Contract.EndContractBlock();
- InternalWriteAllBytes(path, bytes, true);
+ InternalWriteAllBytes(path, bytes);
}
- [System.Security.SecurityCritical]
- internal static void UnsafeWriteAllBytes(String path, byte[] bytes)
- {
- if (path == null)
- throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- if (bytes == null)
- throw new ArgumentNullException("bytes");
- Contract.EndContractBlock();
-
- InternalWriteAllBytes(path, bytes, false);
- }
-
- [System.Security.SecurityCritical]
- private static void InternalWriteAllBytes(String path, byte[] bytes, bool checkHost)
+ private static void InternalWriteAllBytes(String path, byte[] bytes)
{
Contract.Requires(path != null);
Contract.Requires(path.Length != 0);
Contract.Requires(bytes != null);
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read,
- FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost))
+ FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false))
{
fs.Write(bytes, 0, bytes.Length);
}
@@ -816,7 +459,7 @@ namespace System.IO {
public static String[] ReadAllLines(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -827,9 +470,9 @@ namespace System.IO {
public static String[] ReadAllLines(String path, Encoding encoding)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (encoding == null)
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -856,9 +499,9 @@ namespace System.IO {
public static IEnumerable<String> ReadLines(String path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(path));
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, Encoding.UTF8);
@@ -867,11 +510,11 @@ namespace System.IO {
public static IEnumerable<String> ReadLines(String path, Encoding encoding)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (encoding == null)
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(path));
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, encoding);
@@ -880,9 +523,9 @@ namespace System.IO {
public static void WriteAllLines(String path, String[] contents)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (contents == null)
- throw new ArgumentNullException("contents");
+ throw new ArgumentNullException(nameof(contents));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -893,11 +536,11 @@ namespace System.IO {
public static void WriteAllLines(String path, String[] contents, Encoding encoding)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (contents == null)
- throw new ArgumentNullException("contents");
+ throw new ArgumentNullException(nameof(contents));
if (encoding == null)
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -908,9 +551,9 @@ namespace System.IO {
public static void WriteAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (contents == null)
- throw new ArgumentNullException("contents");
+ throw new ArgumentNullException(nameof(contents));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -921,11 +564,11 @@ namespace System.IO {
public static void WriteAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (contents == null)
- throw new ArgumentNullException("contents");
+ throw new ArgumentNullException(nameof(contents));
if (encoding == null)
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -950,7 +593,7 @@ namespace System.IO {
public static void AppendAllText(String path, String contents)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -961,9 +604,9 @@ namespace System.IO {
public static void AppendAllText(String path, String contents, Encoding encoding)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (encoding == null)
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -984,9 +627,9 @@ namespace System.IO {
public static void AppendAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (contents == null)
- throw new ArgumentNullException("contents");
+ throw new ArgumentNullException(nameof(contents));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -997,11 +640,11 @@ namespace System.IO {
public static void AppendAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (contents == null)
- throw new ArgumentNullException("contents");
+ throw new ArgumentNullException(nameof(contents));
if (encoding == null)
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
@@ -1011,48 +654,23 @@ namespace System.IO {
// Moves a specified file to a new location and potentially a new file name.
// This method does work across volumes.
- //
- // The caller must have certain FileIOPermissions. The caller must
- // have Read and Write permission to
- // 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);
+ InternalMove(sourceFileName, destFileName);
}
- [System.Security.SecurityCritical]
- private static void InternalMove(String sourceFileName, String destFileName, bool checkHost) {
+ private static void InternalMove(String sourceFileName, String destFileName) {
if (sourceFileName == null)
- throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
+ throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
- throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
+ throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceFileName));
if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
Contract.EndContractBlock();
- String fullSourceFileName = Path.GetFullPathInternal(sourceFileName);
- String fullDestFileName = Path.GetFullPathInternal(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
+ String fullSourceFileName = Path.GetFullPath(sourceFileName);
+ String fullDestFileName = Path.GetFullPath(destFileName);
if (!InternalExists(fullSourceFileName))
__Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName);
@@ -1067,9 +685,9 @@ namespace System.IO {
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName)
{
if (sourceFileName == null)
- throw new ArgumentNullException("sourceFileName");
+ throw new ArgumentNullException(nameof(sourceFileName));
if (destinationFileName == null)
- throw new ArgumentNullException("destinationFileName");
+ throw new ArgumentNullException(nameof(destinationFileName));
Contract.EndContractBlock();
InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, false);
@@ -1078,41 +696,24 @@ namespace System.IO {
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
if (sourceFileName == null)
- throw new ArgumentNullException("sourceFileName");
+ throw new ArgumentNullException(nameof(sourceFileName));
if (destinationFileName == null)
- throw new ArgumentNullException("destinationFileName");
+ throw new ArgumentNullException(nameof(destinationFileName));
Contract.EndContractBlock();
InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
}
- [System.Security.SecuritySafeCritical]
private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
Contract.Requires(sourceFileName != null);
Contract.Requires(destinationFileName != null);
- // Write permission to all three files, read permission to source
- // and dest.
- String fullSrcPath = Path.GetFullPathInternal(sourceFileName);
- String fullDestPath = Path.GetFullPathInternal(destinationFileName);
+ String fullSrcPath = Path.GetFullPath(sourceFileName);
+ String fullDestPath = Path.GetFullPath(destinationFileName);
String fullBackupPath = null;
if (destinationBackupFileName != null)
- fullBackupPath = Path.GetFullPathInternal(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
+ fullBackupPath = Path.GetFullPath(destinationBackupFileName);
int flags = Win32Native.REPLACEFILE_WRITE_THROUGH;
if (ignoreMetadataErrors)
@@ -1126,7 +727,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;
@@ -1172,7 +772,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();
}
}
@@ -1187,7 +787,6 @@ namespace System.IO {
}
else
{
-
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
@@ -1222,34 +821,5 @@ namespace System.IO {
return dataInitialised;
}
-
- [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.GetFullPathInternal(path);
- if (hr==__Error.ERROR_PATH_NOT_FOUND && FullPath.Equals(Directory.GetDirectoryRoot(FullPath)))
- hr = __Error.ERROR_ACCESS_DENIED;
-
-
- __Error.WinIOError(hr, path);
- }
- return fs;
- }
-
-
- // Defined in WinError.h
- private const int ERROR_INVALID_PARAMETER = 87;
- private const int ERROR_ACCESS_DENIED = 0x5;
}
}
diff --git a/src/mscorlib/src/System/IO/FileAttributes.cs b/src/mscorlib/src/System/IO/FileAttributes.cs
index 19d5f227d7..51ef597f9d 100644
--- a/src/mscorlib/src/System/IO/FileAttributes.cs
+++ b/src/mscorlib/src/System/IO/FileAttributes.cs
@@ -11,13 +11,13 @@
===========================================================*/
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
}
}
diff --git a/src/mscorlib/src/System/IO/FileInfo.cs b/src/mscorlib/src/System/IO/FileInfo.cs
index 3ab1a5122e..32622c63a1 100644
--- a/src/mscorlib/src/System/IO/FileInfo.cs
+++ b/src/mscorlib/src/System/IO/FileInfo.cs
@@ -2,33 +2,17 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: A collection of methods for manipulating Files.
-**
-** April 09,2000 (some design refactorization)
-**
-===========================================================*/
-
-using System;
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
-using System.Security.Permissions;
-using PermissionSet = System.Security.PermissionSet;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
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,85 +21,40 @@ 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)
- throw new ArgumentNullException("fileName");
- Contract.EndContractBlock();
-
- FileInfo fi = new FileInfo();
- fi.Init(fileName, false);
- return fi;
- }
-#endif
-
- [System.Security.SecuritySafeCritical]
public FileInfo(String fileName)
{
if (fileName == null)
- throw new ArgumentNullException("fileName");
+ throw new ArgumentNullException(nameof(fileName));
Contract.EndContractBlock();
- Init(fileName, true);
+ Init(fileName);
}
- [System.Security.SecurityCritical]
- private void Init(String fileName, bool checkHost)
+ private void Init(String fileName)
{
OriginalPath = fileName;
- // Must fully qualify the path for the security check
- String fullPath = Path.GetFullPathInternal(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;
+ FullPath = Path.GetFullPath(fileName);
DisplayPath = GetDisplayPath(fileName);
}
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(Path.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 +64,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,20 +83,9 @@ 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;
+ return Path.GetDirectoryName(FullPath);
}
}
@@ -171,7 +97,7 @@ namespace System.IO {
String dirName = DirectoryName;
if (dirName == null)
return null;
- return new DirectoryInfo(dirName);
+ return new DirectoryInfo(dirName);
}
}
@@ -187,27 +113,9 @@ 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);
+ return new StreamReader(FullPath, Encoding.UTF8, true, StreamReader.DefaultBufferSize);
}
public StreamWriter CreateText()
@@ -220,45 +128,33 @@ namespace System.IO {
return new StreamWriter(FullPath,true);
}
-
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
- //
- // The caller must have certain FileIOPermissions. The caller must have
- // Read permission to sourceFileName
- // and Write permissions to destFileName.
- //
public FileInfo CopyTo(String destFileName) {
if (destFileName == null)
- throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
+ throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
Contract.EndContractBlock();
- destFileName = File.InternalCopy(FullPath, destFileName, false, true);
+ destFileName = File.InternalCopy(FullPath, destFileName, false);
return new FileInfo(destFileName, false);
}
-
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
- //
- // The caller must have certain FileIOPermissions. The caller must have
- // Read permission to sourceFileName and Create
- // and Write permissions to destFileName.
- //
public FileInfo CopyTo(String destFileName, bool overwrite) {
if (destFileName == null)
- throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
+ throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
Contract.EndContractBlock();
- destFileName = File.InternalCopy(FullPath, destFileName, overwrite, true);
+ destFileName = File.InternalCopy(FullPath, destFileName, overwrite);
return new FileInfo(destFileName, false);
}
@@ -271,22 +167,9 @@ namespace System.IO {
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
- // or a file that is memory mapped. On Win95, the file will be
- // deleted irregardless of whether the file is being used.
- //
- // Your application must have Delete permission to the target file.
- //
- [System.Security.SecuritySafeCritical]
+ // or a file that is memory mapped.
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) {
int hr = Marshal.GetLastWin32Error();
@@ -297,25 +180,10 @@ namespace System.IO {
}
}
- [ComVisible(false)]
- public void Decrypt()
- {
- File.Decrypt(FullPath);
- }
-
- [ComVisible(false)]
- public void Encrypt()
- {
- File.Encrypt(FullPath);
- }
-
// Tests if the given file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false.
- //
- // 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 +203,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,54 +216,28 @@ 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.
- //
- // The caller must have certain FileIOPermissions. The caller must
- // have Read and Write permission to
- // sourceFileName and Write
- // permissions to destFileName.
- //
- [System.Security.SecuritySafeCritical]
public void MoveTo(String destFileName) {
if (destFileName==null)
- throw new ArgumentNullException("destFileName");
+ throw new ArgumentNullException(nameof(destFileName));
if (destFileName.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName));
Contract.EndContractBlock();
- String fullDestFileName = Path.GetFullPathInternal(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
-
+ string fullDestFileName = Path.GetFullPath(destFileName);
+
if (!Win32Native.MoveFile(FullPath, fullDestFileName))
__Error.WinIOError();
FullPath = fullDestFileName;
diff --git a/src/mscorlib/src/System/IO/FileLoadException.cs b/src/mscorlib/src/System/IO/FileLoadException.cs
index fabe2613c3..2b56c00191 100644
--- a/src/mscorlib/src/System/IO/FileLoadException.cs
+++ b/src/mscorlib/src/System/IO/FileLoadException.cs
@@ -91,7 +91,6 @@ namespace System.IO {
if (StackTrace != null)
s += Environment.NewLine + StackTrace;
-#if FEATURE_FUSION
try
{
if(FusionLog!=null)
@@ -107,7 +106,6 @@ namespace System.IO {
{
}
-#endif // FEATURE_FUSION
return s;
}
@@ -117,7 +115,6 @@ namespace System.IO {
_fileName = info.GetString("FileLoad_FileName");
-#if FEATURE_FUSION
try
{
_fusionLog = info.GetString("FileLoad_FusionLog");
@@ -126,7 +123,6 @@ namespace System.IO {
{
_fusionLog = null;
}
-#endif
}
private FileLoadException(String fileName, String fusionLog,int hResult)
@@ -138,15 +134,10 @@ namespace System.IO {
SetMessageField();
}
-#if FEATURE_FUSION
public String FusionLog {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
get { return _fusionLog; }
}
-#endif // FEATURE_FUSION
- [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);
@@ -154,7 +145,6 @@ namespace System.IO {
// Serialize data for this class
info.AddValue("FileLoad_FileName", _fileName, typeof(String));
-#if FEATURE_FUSION
try
{
info.AddValue("FileLoad_FusionLog", FusionLog, typeof(String));
@@ -162,10 +152,8 @@ namespace System.IO {
catch (SecurityException)
{
}
-#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static String FormatFileLoadExceptionMessage(String fileName,
int hResult)
{
@@ -178,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);
diff --git a/src/mscorlib/src/System/IO/FileNotFoundException.cs b/src/mscorlib/src/System/IO/FileNotFoundException.cs
index 933e4fd94c..8cc75f8232 100644
--- a/src/mscorlib/src/System/IO/FileNotFoundException.cs
+++ b/src/mscorlib/src/System/IO/FileNotFoundException.cs
@@ -93,7 +93,6 @@ namespace System.IO {
if (StackTrace != null)
s += Environment.NewLine + StackTrace;
-#if FEATURE_FUSION
try
{
if(FusionLog!=null)
@@ -109,7 +108,6 @@ namespace System.IO {
{
}
-#endif
return s;
}
@@ -118,7 +116,6 @@ namespace System.IO {
// Base class constructor will check info != null.
_fileName = info.GetString("FileNotFound_FileName");
-#if FEATURE_FUSION
try
{
_fusionLog = info.GetString("FileNotFound_FusionLog");
@@ -127,7 +124,6 @@ namespace System.IO {
{
_fusionLog = null;
}
-#endif
}
private FileNotFoundException(String fileName, String fusionLog,int hResult)
@@ -139,15 +135,10 @@ namespace System.IO {
SetMessageField();
}
-#if FEATURE_FUSION
public String FusionLog {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
get { return _fusionLog; }
}
-#endif
- [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);
@@ -155,7 +146,6 @@ namespace System.IO {
// Serialize data for this class
info.AddValue("FileNotFound_FileName", _fileName, typeof(String));
-#if FEATURE_FUSION
try
{
info.AddValue("FileNotFound_FusionLog", FusionLog, typeof(String));
@@ -163,7 +153,6 @@ namespace System.IO {
catch (SecurityException)
{
}
-#endif
}
}
}
diff --git a/src/mscorlib/src/System/IO/FileSecurityState.cs b/src/mscorlib/src/System/IO/FileSecurityState.cs
deleted file mode 100644
index 249848ac02..0000000000
--- a/src/mscorlib/src/System/IO/FileSecurityState.cs
+++ /dev/null
@@ -1,133 +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.
-
-/*============================================================
-**
-** Enum: FileSecurityState
-**
-**
-**
-**
-** Purpose: Determines whether file system access is safe
-**
-**
-===========================================================*/
-
-using System;
-using System.Diagnostics.Contracts;
-using System.IO;
-using System.Security;
-using System.Security.Permissions;
-
-namespace System.IO
-{
- [SecurityCritical]
- [System.Runtime.CompilerServices.FriendAccessAllowed]
- internal class FileSecurityState : SecurityState
- {
-#if !PLATFORM_UNIX
- private static readonly char[] m_illegalCharacters = { '?', '*' };
-#endif // !PLATFORM_UNIX
-
- private FileSecurityStateAccess m_access;
- private String m_userPath;
- private String m_canonicalizedPath;
-
- // default ctor needed for security rule consistency
- [SecurityCritical]
- private FileSecurityState()
- {
- }
-
- internal FileSecurityState(FileSecurityStateAccess access, String path)
- {
- if (path == null)
- {
- throw new ArgumentNullException("path");
- }
- VerifyAccess(access);
- m_access = access;
- m_userPath = path;
- if (path.Equals(String.Empty, StringComparison.OrdinalIgnoreCase))
- {
- m_canonicalizedPath = String.Empty;
- }
- else
- {
- VerifyPath(path);
- m_canonicalizedPath = System.IO.Path.GetFullPathInternal(path);
- }
- }
-
- // slight perf savings for trusted internal callers
- internal FileSecurityState(FileSecurityStateAccess access, String path, String canonicalizedPath)
- {
- VerifyAccess(access);
- VerifyPath(path);
- VerifyPath(canonicalizedPath);
-
- m_access = access;
- m_userPath = path;
- m_canonicalizedPath = canonicalizedPath;
- }
-
- internal FileSecurityStateAccess Access
- {
- get
- {
- return m_access;
- }
- }
-
- public String Path {
- [System.Runtime.CompilerServices.FriendAccessAllowed]
- get
- {
- return m_canonicalizedPath;
- }
- }
-
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- public override void EnsureState()
- {
- // this is the case for empty string machine name, etc
- if (String.Empty.Equals(m_canonicalizedPath))
- return;
-
- if (!IsStateAvailable())
- {
- throw new SecurityException(Environment.GetResourceString("FileSecurityState_OperationNotPermitted", (m_userPath == null) ? String.Empty : m_userPath));
- }
- }
-
- internal static FileSecurityStateAccess ToFileSecurityState(FileIOPermissionAccess access)
- {
- Contract.Requires((access & ~FileIOPermissionAccess.AllAccess) == 0);
- return (FileSecurityStateAccess)access; // flags are identical; just cast
- }
-
- private static void VerifyAccess(FileSecurityStateAccess access)
- {
- if ((access & ~FileSecurityStateAccess.AllAccess) != 0)
- throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("Arg_EnumIllegalVal"));
- }
-
- private static void VerifyPath(String path)
- {
- if (path != null)
- {
- path = path.Trim();
-
-#if !PLATFORM_UNIX
- if (!PathInternal.IsDevice(path) && PathInternal.HasInvalidVolumeSeparator(path))
- throw new ArgumentException(Environment.GetResourceString("Argument_PathFormatNotSupported"));
-#endif
-
- System.IO.Path.CheckInvalidPathChars(path, checkAdditional: true);
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileSecurityStateAccess.cs b/src/mscorlib/src/System/IO/FileSecurityStateAccess.cs
deleted file mode 100644
index b6378c6142..0000000000
--- a/src/mscorlib/src/System/IO/FileSecurityStateAccess.cs
+++ /dev/null
@@ -1,32 +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.
-
-/*============================================================
-**
-** Enum: FileSecurityStateAccess
-**
-**
-**
-**
-** Purpose: FileSecurityState enum
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.IO
-{
- [Flags]
- internal enum FileSecurityStateAccess
- {
- NoAccess = 0,
- Read = 1,
- Write = 2,
- Append = 4,
- PathDiscovery = 8,
- AllAccess = 15
- }
-}
-
diff --git a/src/mscorlib/src/System/IO/FileStream.cs b/src/mscorlib/src/System/IO/FileStream.cs
deleted file mode 100644
index deef30c480..0000000000
--- a/src/mscorlib/src/System/IO/FileStream.cs
+++ /dev/null
@@ -1,2695 +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: Exposes a Stream around a file, with full
-** synchronous and asychronous support, and buffering.
-**
-**
-===========================================================*/
-using System;
-using Microsoft.Win32;
-using Microsoft.Win32.SafeHandles;
-using System.Security;
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
-using System.Security.Permissions;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Runtime.InteropServices;
-#if FEATURE_REMOTING
-using System.Runtime.Remoting.Messaging;
-#endif
-using System.Runtime.CompilerServices;
-using System.Globalization;
-using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
-using System.Diagnostics.Tracing;
-
-/*
- * FileStream supports different modes of accessing the disk - async mode
- * and sync mode. They are two completely different codepaths in the
- * sync & async methods (ie, Read/Write vs. BeginRead/BeginWrite). File
- * handles in NT can be opened in only sync or overlapped (async) mode,
- * and we have to deal with this pain. Stream has implementations of
- * the sync methods in terms of the async ones, so we'll
- * call through to our base class to get those methods when necessary.
- *
- * Also buffering is added into FileStream as well. Folded in the
- * code from BufferedStream, so all the comments about it being mostly
- * aggressive (and the possible perf improvement) apply to FileStream as
- * well. Also added some buffering to the async code paths.
- *
- * Class Invariants:
- * The class has one buffer, shared for reading & writing. It can only be
- * used for one or the other at any point in time - not both. The following
- * should be true:
- * 0 <= _readPos <= _readLen < _bufferSize
- * 0 <= _writePos < _bufferSize
- * _readPos == _readLen && _readPos > 0 implies the read buffer is valid,
- * but we're at the end of the buffer.
- * _readPos == _readLen == 0 means the read buffer contains garbage.
- * Either _writePos can be greater than 0, or _readLen & _readPos can be
- * greater than zero, but neither can be greater than zero at the same time.
- *
- */
-
-namespace System.IO {
-
- // This is an internal object implementing IAsyncResult with fields
- // for all of the relevant data necessary to complete the IO operation.
- // This is used by AsyncFSCallback and all of the async methods.
- // We should probably make this a nested type of FileStream. But
- // I don't know how to define a nested class in mscorlib.h
-
- unsafe internal sealed class FileStreamAsyncResult : IAsyncResult
- {
- // README:
- // If you modify the order of these fields, make sure to update
- // the native VM definition of this class as well!!!
- // User code callback
- private AsyncCallback _userCallback;
- private Object _userStateObject;
- private ManualResetEvent _waitHandle;
- [System.Security.SecurityCritical]
- private SafeFileHandle _handle; // For cancellation support.
-
- [SecurityCritical]
- private NativeOverlapped* _overlapped;
- internal NativeOverlapped* OverLapped { [SecurityCritical]get { return _overlapped; } }
- internal bool IsAsync { [SecuritySafeCritical]get { return _overlapped != null; } }
-
-
- internal int _EndXxxCalled; // Whether we've called EndXxx already.
- private int _numBytes; // number of bytes read OR written
- internal int NumBytes { get { return _numBytes; } }
-
- private int _errorCode;
- internal int ErrorCode { get { return _errorCode; } }
-
- private int _numBufferedBytes;
- internal int NumBufferedBytes { get { return _numBufferedBytes; } }
-
- internal int NumBytesRead { get { return _numBytes + _numBufferedBytes; } }
-
- private bool _isWrite; // Whether this is a read or a write
- internal bool IsWrite { get { return _isWrite; } }
-
- private bool _isComplete; // Value for IsCompleted property
- private bool _completedSynchronously; // Which thread called callback
-
- // The NativeOverlapped struct keeps a GCHandle to this IAsyncResult object.
- // So if the user doesn't call EndRead/EndWrite, a finalizer won't help because
- // it'll never get called.
-
- // Overlapped class will take care of the async IO operations in progress
- // when an appdomain unload occurs.
-
- [System.Security.SecurityCritical] // auto-generated
- private unsafe static IOCompletionCallback s_IOCallback;
-
- [SecuritySafeCritical]
- internal FileStreamAsyncResult(
- int numBufferedBytes,
- byte[] bytes,
- SafeFileHandle handle,
- AsyncCallback userCallback,
- Object userStateObject,
- bool isWrite)
- {
- _userCallback = userCallback;
- _userStateObject = userStateObject;
- _isWrite = isWrite;
- _numBufferedBytes = numBufferedBytes;
- _handle = handle;
-
- // For Synchronous IO, I could go with either a callback and using
- // the managed Monitor class, or I could create a handle and wait on it.
- ManualResetEvent waitHandle = new ManualResetEvent(false);
- _waitHandle = waitHandle;
-
- // Create a managed overlapped class
- // We will set the file offsets later
- Overlapped overlapped = new Overlapped(0, 0, IntPtr.Zero, this);
-
- // Pack the Overlapped class, and store it in the async result
- if (userCallback != null)
- {
- var ioCallback = s_IOCallback; // cached static delegate; delay initialized due to it being SecurityCritical
- if (ioCallback == null) s_IOCallback = ioCallback = new IOCompletionCallback(AsyncFSCallback);
- _overlapped = overlapped.Pack(ioCallback, bytes);
- }
- else
- {
- _overlapped = overlapped.UnsafePack(null, bytes);
- }
-
- Contract.Assert(_overlapped != null, "Did Overlapped.Pack or Overlapped.UnsafePack just return a null?");
- }
-
- internal static FileStreamAsyncResult CreateBufferedReadResult(int numBufferedBytes, AsyncCallback userCallback, Object userStateObject, bool isWrite)
- {
- FileStreamAsyncResult asyncResult = new FileStreamAsyncResult(numBufferedBytes, userCallback, userStateObject, isWrite);
- asyncResult.CallUserCallback();
- return asyncResult;
- }
-
- // This creates a synchronous Async Result. We should consider making this a separate class and maybe merge it with
- // System.IO.Stream.SynchronousAsyncResult
- private FileStreamAsyncResult(int numBufferedBytes, AsyncCallback userCallback, Object userStateObject, bool isWrite)
- {
- _userCallback = userCallback;
- _userStateObject = userStateObject;
- _isWrite = isWrite;
- _numBufferedBytes = numBufferedBytes;
- }
-
- public Object AsyncState
- {
- get { return _userStateObject; }
- }
-
- public bool IsCompleted
- {
- get { return _isComplete; }
- }
-
- public WaitHandle AsyncWaitHandle
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- // Consider uncommenting this someday soon - the EventHandle
- // in the Overlapped struct is really useless half of the
- // time today since the OS doesn't signal it. If users call
- // EndXxx after the OS call happened to complete, there's no
- // reason to create a synchronization primitive here. Fixing
- // this will save us some perf, assuming we can correctly
- // initialize the ManualResetEvent.
- if (_waitHandle == null) {
- ManualResetEvent mre = new ManualResetEvent(false);
- if (_overlapped != null && _overlapped->EventHandle != IntPtr.Zero) {
- mre.SafeWaitHandle = new SafeWaitHandle(_overlapped->EventHandle, true);
- }
-
- // make sure only one thread sets _waitHandle
- if (Interlocked.CompareExchange<ManualResetEvent>(ref _waitHandle, mre, null) == null) {
- if (_isComplete)
- _waitHandle.Set();
- }
- else {
- // There's a slight but acceptable race condition if we weren't
- // the thread that set _waitHandle and this code path
- // returns before the code in the if statement
- // executes (on the other thread). However, the
- // caller is waiting for the wait handle to be set,
- // which will still happen.
- mre.Close();
- }
- }
- return _waitHandle;
- }
- }
-
- // Returns true iff the user callback was called by the thread that
- // called BeginRead or BeginWrite. If we use an async delegate or
- // threadpool thread internally, this will be false. This is used
- // by code to determine whether a successive call to BeginRead needs
- // to be done on their main thread or in their callback to avoid a
- // stack overflow on many reads or writes.
- public bool CompletedSynchronously
- {
- get { return _completedSynchronously; }
- }
-
- private void CallUserCallbackWorker()
- {
- _isComplete = true;
-
- // ensure _isComplete is set before reading _waitHandle
- Thread.MemoryBarrier();
- if (_waitHandle != null)
- _waitHandle.Set();
-
- _userCallback(this);
- }
-
- internal void CallUserCallback()
- {
- // Convenience method for me, since I have to do this in a number
- // of places in the buffering code for fake IAsyncResults.
- // AsyncFSCallback intentionally does not use this method.
-
- if (_userCallback != null) {
- // Call user's callback on a threadpool thread.
- // Set completedSynchronously to false, since it's on another
- // thread, not the main thread.
- _completedSynchronously = false;
- ThreadPool.QueueUserWorkItem(state => ((FileStreamAsyncResult)state).CallUserCallbackWorker(), this);
- }
- else {
- _isComplete = true;
-
- // ensure _isComplete is set before reading _waitHandle
- Thread.MemoryBarrier();
- if (_waitHandle != null)
- _waitHandle.Set();
- }
- }
-
- [SecurityCritical]
- internal void ReleaseNativeResource()
- {
- // Free memory & GC handles.
- if (this._overlapped != null)
- Overlapped.Free(_overlapped);
- }
-
- internal void Wait()
- {
- if (_waitHandle != null)
- {
- // We must block to ensure that AsyncFSCallback has completed,
- // and we should close the WaitHandle in here. AsyncFSCallback
- // and the hand-ported imitation version in COMThreadPool.cpp
- // are the only places that set this event.
- try
- {
- _waitHandle.WaitOne();
- Contract.Assert(_isComplete == true, "FileStreamAsyncResult::Wait - AsyncFSCallback didn't set _isComplete to true!");
- }
- finally
- {
- _waitHandle.Close();
- }
- }
- }
-
- // When doing IO asynchronously (ie, _isAsync==true), this callback is
- // called by a free thread in the threadpool when the IO operation
- // completes.
- [System.Security.SecurityCritical] // auto-generated
- unsafe private static void AsyncFSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
- {
- BCLDebug.Log(String.Format("AsyncFSCallback called. errorCode: " + errorCode + " numBytes: " + numBytes));
-
- // Unpack overlapped
- Overlapped overlapped = Overlapped.Unpack(pOverlapped);
- // Free the overlapped struct in EndRead/EndWrite.
-
- // Extract async result from overlapped
- FileStreamAsyncResult asyncResult =
- (FileStreamAsyncResult)overlapped.AsyncResult;
- asyncResult._numBytes = (int)numBytes;
-
- if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
- FrameworkEventSource.Log.ThreadTransferReceive((long)(asyncResult.OverLapped), 2, string.Empty);
-
- // Handle reading from & writing to closed pipes. While I'm not sure
- // this is entirely necessary anymore, maybe it's possible for
- // an async read on a pipe to be issued and then the pipe is closed,
- // returning this error. This may very well be necessary.
- if (errorCode == FileStream.ERROR_BROKEN_PIPE || errorCode == FileStream.ERROR_NO_DATA)
- errorCode = 0;
-
- asyncResult._errorCode = (int)errorCode;
-
- // Call the user-provided callback. It can and often should
- // call EndRead or EndWrite. There's no reason to use an async
- // delegate here - we're already on a threadpool thread.
- // IAsyncResult's completedSynchronously property must return
- // false here, saying the user callback was called on another thread.
- asyncResult._completedSynchronously = false;
- asyncResult._isComplete = true;
-
- // ensure _isComplete is set before reading _waitHandle
- Thread.MemoryBarrier();
-
- // The OS does not signal this event. We must do it ourselves.
- ManualResetEvent wh = asyncResult._waitHandle;
- if (wh != null)
- {
- Contract.Assert(!wh.SafeWaitHandle.IsClosed, "ManualResetEvent already closed!");
- bool r = wh.Set();
- Contract.Assert(r, "ManualResetEvent::Set failed!");
- if (!r) __Error.WinIOError();
- }
-
- AsyncCallback userCallback = asyncResult._userCallback;
- if (userCallback != null)
- userCallback(asyncResult);
- }
-
- [SecuritySafeCritical]
- [HostProtection(ExternalThreading = true)]
- internal void Cancel()
- {
- Contract.Assert(_handle != null, "_handle should not be null.");
- Contract.Assert(_overlapped != null, "Cancel should only be called on true asynchronous FileStreamAsyncResult, i.e. _overlapped is not null");
-
- if (IsCompleted)
- return;
-
- if (_handle.IsInvalid)
- return;
-
- bool r = Win32Native.CancelIoEx(_handle, _overlapped);
- if (!r)
- {
- int errorCode = Marshal.GetLastWin32Error();
-
- // ERROR_NOT_FOUND is returned if CancelIoEx cannot find the request to cancel.
- // This probably means that the IO operation has completed.
- if (errorCode != Win32Native.ERROR_NOT_FOUND)
- __Error.WinIOError(errorCode, String.Empty);
- }
- }
- }
-
- [ComVisible(true)]
- public class FileStream : Stream
- {
- internal const int DefaultBufferSize = 4096;
-
- private byte[] _buffer; // Shared read/write buffer. Alloc on first use.
- private String _fileName; // Fully qualified file name.
- private bool _isAsync; // Whether we opened the handle for overlapped IO
- private bool _canRead;
- private bool _canWrite;
- private bool _canSeek;
- private bool _exposedHandle; // Could other code be using this handle?
- private bool _isPipe; // Whether to disable async buffering code.
- private int _readPos; // Read pointer within shared buffer.
- private int _readLen; // Number of bytes read in buffer from file.
- private int _writePos; // Write pointer within shared buffer.
- private int _bufferSize; // Length of internal buffer, if it's allocated.
- [System.Security.SecurityCritical] // auto-generated
- private SafeFileHandle _handle;
- private long _pos; // Cache current location in the file.
- private long _appendStart;// When appending, prevent overwriting file.
- private static AsyncCallback s_endReadTask;
- private static AsyncCallback s_endWriteTask;
- private static Action<object> s_cancelReadHandler;
- private static Action<object> s_cancelWriteHandler;
-
- //This exists only to support IsolatedStorageFileStream.
- //Any changes to FileStream must include the corresponding changes in IsolatedStorage.
- internal FileStream() {
- }
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
- public FileStream(String path, FileMode mode)
- : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.Read, DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, true) {
- }
-
- [System.Security.SecuritySafeCritical]
- public FileStream(String path, FileMode mode, FileAccess access)
- : this(path, mode, access, FileShare.Read, DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, true) {
- }
-
- [System.Security.SecuritySafeCritical]
- public FileStream(String path, FileMode mode, FileAccess access, FileShare share)
- : this(path, mode, access, share, DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, true) {
- }
-
- [System.Security.SecuritySafeCritical]
- public FileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
- : this(path, mode, access, share, bufferSize, FileOptions.None, Path.GetFileName(path), false, false, true)
- {
- }
-
-#else // FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileStream(String path, FileMode mode)
- : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.Read, DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false) {
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileStream(String path, FileMode mode, FileAccess access)
- : this(path, mode, access, FileShare.Read, DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false) {
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileStream(String path, FileMode mode, FileAccess access, FileShare share)
- : this(path, mode, access, share, DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false) {
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
- : this(path, mode, access, share, bufferSize, FileOptions.None, Path.GetFileName(path), false)
- {
- }
-#endif // FEATURE_CORECLR
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
- : this(path, mode, access, share, bufferSize, options, Path.GetFileName(path), false)
- {
- }
-
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
- public FileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
- : this(path, mode, access, share, bufferSize, (useAsync ? FileOptions.Asynchronous : FileOptions.None), Path.GetFileName(path), false)
- {
- }
-
-#if FEATURE_MACL
- // This constructor is done differently to avoid loading a few more
- // classes, and more importantly, to build correctly on Rotor.
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileStream(String path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity)
- {
- Object pinningHandle;
- Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share, fileSecurity, out pinningHandle);
- try {
- Init(path, mode, (FileAccess)0, (int)rights, true, share, bufferSize, options, secAttrs, Path.GetFileName(path), false, false, false);
- }
- finally {
- if (pinningHandle != null) {
- GCHandle pinHandle = (GCHandle) pinningHandle;
- pinHandle.Free();
- }
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileStream(String path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options)
- {
- Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
- Init(path, mode, (FileAccess)0, (int)rights, true, share, bufferSize, options, secAttrs, Path.GetFileName(path), false, false, false);
- }
-#endif
-
- [System.Security.SecurityCritical] // auto-generated
- internal FileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, String msgPath, bool bFromProxy)
- {
- Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
- Init(path, mode, access, 0, false, share, bufferSize, options, secAttrs, msgPath, bFromProxy, false, false);
- }
-
- [System.Security.SecurityCritical]
- internal FileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, String msgPath, bool bFromProxy, bool useLongPath)
- {
- Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
- Init(path, mode, access, 0, false, share, bufferSize, options, secAttrs, msgPath, bFromProxy, useLongPath, false);
- }
-
- [System.Security.SecurityCritical]
- internal FileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, String msgPath, bool bFromProxy, bool useLongPath, bool checkHost)
- {
- Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
- Init(path, mode, access, 0, false, share, bufferSize, options, secAttrs, msgPath, bFromProxy, useLongPath, checkHost);
- }
-
- // AccessControl namespace is not defined in Rotor
- [System.Security.SecuritySafeCritical]
- private void Init(String path, FileMode mode, FileAccess access, int rights, bool useRights, FileShare share, int bufferSize, FileOptions options, Win32Native.SECURITY_ATTRIBUTES secAttrs, String msgPath, bool bFromProxy, bool useLongPath, bool checkHost)
- {
- if (path == null)
- throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- Contract.EndContractBlock();
-
-#if FEATURE_MACL
- FileSystemRights fileSystemRights = (FileSystemRights)rights;
-#endif
- // msgPath must be safe to hand back to untrusted code.
-
- _fileName = msgPath; // To handle odd cases of finalizing partially constructed objects.
- _exposedHandle = false;
-
- // don't include inheritable in our bounds check for share
- FileShare tempshare = share & ~FileShare.Inheritable;
- String badArg = null;
-
- if (mode < FileMode.CreateNew || mode > FileMode.Append)
- badArg = "mode";
- else if (!useRights && (access < FileAccess.Read || access > FileAccess.ReadWrite))
- badArg = "access";
-#if FEATURE_MACL
- else if (useRights && (fileSystemRights < FileSystemRights.ReadData || fileSystemRights > FileSystemRights.FullControl))
- badArg = "rights";
-#endif
- else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
- badArg = "share";
-
- if (badArg != null)
- throw new ArgumentOutOfRangeException(badArg, Environment.GetResourceString("ArgumentOutOfRange_Enum"));
-
- // NOTE: any change to FileOptions enum needs to be matched here in the error validation
- if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
- throw new ArgumentOutOfRangeException("options", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
-
- if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
-
- // Write access validation
-#if FEATURE_MACL
- if ((!useRights && (access & FileAccess.Write) == 0)
- || (useRights && (fileSystemRights & FileSystemRights.Write) == 0))
-#else
- if (!useRights && (access & FileAccess.Write) == 0)
-#endif //FEATURE_MACL
- {
- if (mode==FileMode.Truncate || mode==FileMode.CreateNew || mode==FileMode.Create || mode==FileMode.Append) {
- // No write access
- if (!useRights)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo", mode, access));
-#if FEATURE_MACL
- else
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&RightsCombo", mode, fileSystemRights));
-#endif //FEATURE_MACL
- }
- }
-
-#if FEATURE_MACL
- // FileMode.Truncate only works with GENERIC_WRITE (FileAccess.Write), source:MSDN
- // For backcomp use FileAccess.Write when FileSystemRights.Write is specified
- if (useRights && (mode == FileMode.Truncate)) {
- if (fileSystemRights == FileSystemRights.Write) {
- useRights = false;
- access = FileAccess.Write;
- }
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileModeTruncate&RightsCombo", mode, fileSystemRights));
- }
- }
-#endif
-
- int fAccess;
- if (!useRights) {
- fAccess = access == FileAccess.Read? GENERIC_READ:
- access == FileAccess.Write? GENERIC_WRITE:
- GENERIC_READ | GENERIC_WRITE;
- }
- else {
- fAccess = rights;
- }
-
- // Get absolute path - Security needs this to prevent something
- // like trying to create a file in c:\tmp with the name
- // "..\WinNT\System32\ntoskrnl.exe". Store it for user convenience.
- int maxPath = useLongPath ? Path.MaxLongPath : Path.MaxPath;
- String filePath = Path.NormalizePath(path, true, maxPath);
-
- _fileName = filePath;
-
- // Prevent access to your disk drives as raw block devices.
- if (filePath.StartsWith("\\\\.\\", StringComparison.Ordinal))
- throw new ArgumentException(Environment.GetResourceString("Arg_DevicesNotSupported"));
-
- // In 4.0, we always construct a FileIOPermission object below.
- // If filePath contained a ':', we would throw a NotSupportedException in
- // System.Security.Util.StringExpressionSet.CanonicalizePath.
- // If filePath contained other illegal characters, we would throw an ArgumentException in
- // FileIOPermission.CheckIllegalCharacters.
- // In 4.5 we on longer construct the FileIOPermission object in full trust.
- // To preserve the 4.0 behavior we do an explicit check for ':' here and also call Path.CheckInvalidPathChars.
- // Note that we need to call CheckInvalidPathChars before checking for ':' because that is what FileIOPermission does.
-
- Path.CheckInvalidPathChars(filePath, true);
-
-#if !PLATFORM_UNIX
- if (filePath.IndexOf( ':', 2 ) != -1)
- throw new NotSupportedException( Environment.GetResourceString( "Argument_PathFormatNotSupported" ) );
-#endif // !PLATFORM_UNIX
-
- bool read = false;
-
-#if FEATURE_MACL
- if ((!useRights && (access & FileAccess.Read) != 0) || (useRights && (fileSystemRights & FileSystemRights.ReadAndExecute) != 0))
-#else
- if (!useRights && (access & FileAccess.Read) != 0)
-#endif //FEATURE_MACL
- {
- if (mode == FileMode.Append)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidAppendMode"));
- else
- read = true;
- }
-
- // All demands in full trust domains are no-ops, so skip
-#if FEATURE_CAS_POLICY
- if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
-#endif // FEATURE_CAS_POLICY
- {
- // Build up security permissions required, as well as validate we
- // have a sensible set of parameters. IE, creating a brand new file
- // for reading doesn't make much sense.
- FileIOPermissionAccess secAccess = FileIOPermissionAccess.NoAccess;
-
- if (read)
- {
- Contract.Assert(mode != FileMode.Append);
- secAccess = secAccess | FileIOPermissionAccess.Read;
- }
-
- // I can't think of any combos of FileMode we should disallow if we
- // don't have read access. Writing would pretty much always be valid
- // in those cases.
-
- // For any FileSystemRights other than ReadAndExecute, demand Write permission
- // This is probably bit overkill for TakeOwnership etc but we don't have any
- // matching FileIOPermissionAccess to demand. It is better that we ask for Write permission.
-
-#if FEATURE_MACL
- // FileMode.OpenOrCreate & FileSystemRights.Synchronize can create 0-byte file; demand write
- if ((!useRights && (access & FileAccess.Write) != 0)
- || (useRights && (fileSystemRights & (FileSystemRights.Write | FileSystemRights.Delete
- | FileSystemRights.DeleteSubdirectoriesAndFiles
- | FileSystemRights.ChangePermissions
- | FileSystemRights.TakeOwnership)) != 0)
- || (useRights && ((fileSystemRights & FileSystemRights.Synchronize) != 0)
- && mode==FileMode.OpenOrCreate)
- )
-#else
- if (!useRights && (access & FileAccess.Write) != 0)
-#endif //FEATURE_MACL
- {
- if (mode==FileMode.Append)
- secAccess = secAccess | FileIOPermissionAccess.Append;
- else
- secAccess = secAccess | FileIOPermissionAccess.Write;
- }
-
-#if FEATURE_MACL
- bool specifiedAcl;
- unsafe {
- specifiedAcl = secAttrs != null && secAttrs.pSecurityDescriptor != null;
- }
-
- AccessControlActions control = specifiedAcl ? AccessControlActions.Change : AccessControlActions.None;
- new FileIOPermission(secAccess, control, new String[] { filePath }, false, false).Demand();
-#else
-#if FEATURE_CORECLR
- if (checkHost) {
- FileSecurityState state = new FileSecurityState(FileSecurityState.ToFileSecurityState(secAccess), path, filePath);
- state.EnsureState();
- }
-#else
- new FileIOPermission(secAccess, new String[] { filePath }, false, false).Demand();
-#endif // FEATURE_CORECLR
-#endif
- }
-
- // Our Inheritable bit was stolen from Windows, but should be set in
- // the security attributes class. Don't leave this bit set.
- share &= ~FileShare.Inheritable;
-
- bool seekToEnd = (mode==FileMode.Append);
- // Must use a valid Win32 constant here...
- if (mode == FileMode.Append)
- mode = FileMode.OpenOrCreate;
-
- // WRT async IO, do the right thing for whatever platform we're on.
- // This way, someone can easily write code that opens a file
- // asynchronously no matter what their platform is.
- if ((options & FileOptions.Asynchronous) != 0)
- _isAsync = true;
- else
- options &= ~FileOptions.Asynchronous;
-
- int flagsAndAttributes = (int) options;
-
-#if !PLATFORM_UNIX
- // For mitigating local elevation of privilege attack through named pipes
- // make sure we always call CreateFile with SECURITY_ANONYMOUS so that the
- // named pipe server can't impersonate a high privileged client security context
- flagsAndAttributes |= (Win32Native.SECURITY_SQOS_PRESENT | Win32Native.SECURITY_ANONYMOUS);
-#endif
-
- // Don't pop up a dialog for reading from an emtpy floppy drive
- int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
- String tempPath = filePath;
- if (useLongPath)
- tempPath = Path.AddLongPathPrefix(tempPath);
- _handle = Win32Native.SafeCreateFile(tempPath, fAccess, share, secAttrs, mode, flagsAndAttributes, IntPtr.Zero);
-
- if (_handle.IsInvalid) {
- // Return a meaningful exception, using the RELATIVE path to
- // the file to avoid returning extra information to the caller
- // unless they have path discovery permission, in which case
- // the full path is fine & useful.
-
- // 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 errorCode = Marshal.GetLastWin32Error();
- if (errorCode==__Error.ERROR_PATH_NOT_FOUND && filePath.Equals(Directory.InternalGetDirectoryRoot(filePath)))
- errorCode = __Error.ERROR_ACCESS_DENIED;
-
- // We need to give an exception, and preferably it would include
- // the fully qualified path name. Do security check here. If
- // we fail, give back the msgPath, which should not reveal much.
- // While this logic is largely duplicated in
- // __Error.WinIOError, we need this for
- // IsolatedStorageFileStream.
- bool canGiveFullPath = false;
-
- if (!bFromProxy)
- {
- try {
-#if !FEATURE_CORECLR
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { _fileName }, false, false ).Demand();
-#endif
- canGiveFullPath = true;
- }
- catch(SecurityException) {}
- }
-
- if (canGiveFullPath)
- __Error.WinIOError(errorCode, _fileName);
- else
- __Error.WinIOError(errorCode, msgPath);
- }
- }
- finally {
- Win32Native.SetErrorMode(oldMode);
- }
-
- // Disallow access to all non-file devices from the FileStream
- // constructors that take a String. Everyone else can call
- // CreateFile themselves then use the constructor that takes an
- // IntPtr. Disallows "con:", "com1:", "lpt1:", etc.
- int fileType = Win32Native.GetFileType(_handle);
- if (fileType != Win32Native.FILE_TYPE_DISK) {
- _handle.Close();
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"));
- }
-
- // This is necessary for async IO using IO Completion ports via our
- // managed Threadpool API's. This (theoretically) calls the OS's
- // BindIoCompletionCallback method, and passes in a stub for the
- // LPOVERLAPPED_COMPLETION_ROUTINE. This stub looks at the Overlapped
- // struct for this request and gets a delegate to a managed callback
- // from there, which it then calls on a threadpool thread. (We allocate
- // our native OVERLAPPED structs 2 pointers too large and store EE state
- // & GC handles there, one to an IAsyncResult, the other to a delegate.)
- if (_isAsync) {
- bool b = false;
- // BindHandle requires UnmanagedCode permission
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
-#pragma warning restore 618
- try {
- b = ThreadPool.BindHandle(_handle);
- }
- finally {
- CodeAccessPermission.RevertAssert();
- if (!b) {
- // We should close the handle so that the handle is not open until SafeFileHandle GC
- Contract.Assert(!_exposedHandle, "Are we closing handle that we exposed/not own, how?");
- _handle.Close();
- }
- }
- if (!b)
- throw new IOException(Environment.GetResourceString("IO.IO_BindHandleFailed"));
- }
-
- if (!useRights) {
- _canRead = (access & FileAccess.Read) != 0;
- _canWrite = (access & FileAccess.Write) != 0;
- }
-#if FEATURE_MACL
- else {
- _canRead = (fileSystemRights & FileSystemRights.ReadData) != 0;
- _canWrite = ((fileSystemRights & FileSystemRights.WriteData) != 0)
- || ((fileSystemRights & FileSystemRights.AppendData) != 0);
- }
-#endif //FEATURE_MACL
-
- _canSeek = true;
- _isPipe = false;
- _pos = 0;
- _bufferSize = bufferSize;
- _readPos = 0;
- _readLen = 0;
- _writePos = 0;
-
- // For Append mode...
- if (seekToEnd) {
- _appendStart = SeekCore(0, SeekOrigin.End);
- }
- else {
- _appendStart = -1;
- }
- }
-
- [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public FileStream(IntPtr handle, FileAccess access)
- : this(handle, access, true, DefaultBufferSize, false) {
- }
-
- [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
- public FileStream(IntPtr handle, FileAccess access, bool ownsHandle)
- : this(handle, access, ownsHandle, DefaultBufferSize, false) {
- }
-
- [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
- public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
- : this(handle, access, ownsHandle, bufferSize, false) {
- }
-
- // We explicitly do a Demand, not a LinkDemand here.
- [System.Security.SecuritySafeCritical] // auto-generated
- [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
- public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
- : this(new SafeFileHandle(handle, ownsHandle), access, bufferSize, isAsync) {
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileStream(SafeFileHandle handle, FileAccess access)
- : this(handle, access, DefaultBufferSize, false) {
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize)
- : this(handle, access, bufferSize, false) {
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
- public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) {
- // To ensure we don't leak a handle, put it in a SafeFileHandle first
- if (handle.IsInvalid)
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle");
- Contract.EndContractBlock();
-
- _handle = handle;
- _exposedHandle = true;
-
- // Now validate arguments.
- if (access < FileAccess.Read || access > FileAccess.ReadWrite)
- throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
- if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
-
- int handleType = Win32Native.GetFileType(_handle);
- Contract.Assert(handleType == Win32Native.FILE_TYPE_DISK || handleType == Win32Native.FILE_TYPE_PIPE || handleType == Win32Native.FILE_TYPE_CHAR, "FileStream was passed an unknown file type!");
- _isAsync = isAsync;
- _canRead = 0 != (access & FileAccess.Read);
- _canWrite = 0 != (access & FileAccess.Write);
- _canSeek = handleType == Win32Native.FILE_TYPE_DISK;
- _bufferSize = bufferSize;
- _readPos = 0;
- _readLen = 0;
- _writePos = 0;
- _fileName = null;
- _isPipe = handleType == Win32Native.FILE_TYPE_PIPE;
-
- // This is necessary for async IO using IO Completion ports via our
- // managed Threadpool API's. This calls the OS's
- // BindIoCompletionCallback method, and passes in a stub for the
- // LPOVERLAPPED_COMPLETION_ROUTINE. This stub looks at the Overlapped
- // struct for this request and gets a delegate to a managed callback
- // from there, which it then calls on a threadpool thread. (We allocate
- // our native OVERLAPPED structs 2 pointers too large and store EE
- // state & a handle to a delegate there.)
-#if !FEATURE_CORECLR
- if (_isAsync) {
- bool b = false;
- try {
- b = ThreadPool.BindHandle(_handle);
- }
- catch (ApplicationException) {
- // If you passed in a synchronous handle and told us to use
- // it asynchronously, throw here.
- throw new ArgumentException(Environment.GetResourceString("Arg_HandleNotAsync"));
- }
- if (!b) {
- throw new IOException(Environment.GetResourceString("IO.IO_BindHandleFailed"));
- }
- }
- else {
-#endif // FEATURE_CORECLR
- if (handleType != Win32Native.FILE_TYPE_PIPE)
- VerifyHandleIsSync();
-#if !FEATURE_CORECLR
- }
-#endif // FEATURE_CORECLR
-
- if (_canSeek)
- SeekCore(0, SeekOrigin.Current);
- else
- _pos = 0;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- private static Win32Native.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share)
- {
- Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
- if ((share & FileShare.Inheritable) != 0) {
- secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
- secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
- secAttrs.bInheritHandle = 1;
- }
- return secAttrs;
- }
-
-#if FEATURE_MACL
- // If pinningHandle is not null, caller must free it AFTER the call to
- // CreateFile has returned.
- [System.Security.SecuritySafeCritical] // auto-generated
- private unsafe static Win32Native.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share, FileSecurity fileSecurity, out Object pinningHandle)
- {
- pinningHandle = null;
- Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
- if ((share & FileShare.Inheritable) != 0 || fileSecurity != null) {
- secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
- secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
- if ((share & FileShare.Inheritable) != 0) {
- secAttrs.bInheritHandle = 1;
- }
-
- // For ACL's, get the security descriptor from the FileSecurity.
- if (fileSecurity != null) {
- byte[] sd = fileSecurity.GetSecurityDescriptorBinaryForm();
- pinningHandle = GCHandle.Alloc(sd, GCHandleType.Pinned);
- fixed(byte* pSecDescriptor = sd)
- secAttrs.pSecurityDescriptor = pSecDescriptor;
- }
- }
- return secAttrs;
- }
-#endif
-
- // Verifies that this handle supports synchronous IO operations (unless you
- // didn't open it for either reading or writing).
- [System.Security.SecuritySafeCritical] // auto-generated
- private unsafe void VerifyHandleIsSync()
- {
- // Do NOT use this method on pipes. Reading or writing to a pipe may
- // cause an app to block incorrectly, introducing a deadlock (depending
- // on whether a write will wake up an already-blocked thread or this
- // FileStream's thread).
-
- // Do NOT change this to use a byte[] of length 0, or test test won't
- // work. Our ReadFile & WriteFile methods are special cased to return
- // for arrays of length 0, since we'd get an IndexOutOfRangeException
- // while using C#'s fixed syntax.
- byte[] bytes = new byte[1];
- int hr = 0;
- int r = 0;
-
- // If the handle is a pipe, ReadFile will block until there
- // has been a write on the other end. We'll just have to deal with it,
- // For the read end of a pipe, you can mess up and
- // accidentally read synchronously from an async pipe.
- if (CanRead) {
- r = ReadFileNative(_handle, bytes, 0, 0, null, out hr);
- }
- else if (CanWrite) {
- r = WriteFileNative(_handle, bytes, 0, 0, null, out hr);
- }
-
- if (hr==ERROR_INVALID_PARAMETER)
- throw new ArgumentException(Environment.GetResourceString("Arg_HandleNotSync"));
- if (hr == Win32Native.ERROR_INVALID_HANDLE)
- __Error.WinIOError(hr, "<OS handle>");
- }
-
-
- public override bool CanRead {
- [Pure]
- get { return _canRead; }
- }
-
- public override bool CanWrite {
- [Pure]
- get { return _canWrite; }
- }
-
- public override bool CanSeek {
- [Pure]
- get { return _canSeek; }
- }
-
- public virtual bool IsAsync {
- get { return _isAsync; }
- }
-
- public override long Length {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- if (_handle.IsClosed) __Error.FileNotOpen();
- if (!CanSeek) __Error.SeekNotSupported();
- int hi = 0, lo = 0;
-
- lo = Win32Native.GetFileSize(_handle, out hi);
-
- if (lo==-1) { // Check for either an error or a 4GB - 1 byte file.
- int hr = Marshal.GetLastWin32Error();
- if (hr != 0)
- __Error.WinIOError(hr, String.Empty);
- }
- long len = (((long)hi) << 32) | ((uint) lo);
- // If we're writing near the end of the file, we must include our
- // internal buffer in our Length calculation. Don't flush because
- // we use the length of the file in our async write method.
- if (_writePos > 0 && _pos + _writePos > len)
- len = _writePos + _pos;
- return len;
- }
- }
-
- public String Name {
- [System.Security.SecuritySafeCritical]
- get {
- if (_fileName == null)
- return Environment.GetResourceString("IO_UnknownFileName");
-#if FEATURE_CORECLR
- FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, _fileName);
- sourceState.EnsureState();
-#else
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { _fileName }, false, false).Demand();
-#endif
- return _fileName;
- }
- }
-
- internal String NameInternal {
- get {
- if (_fileName == null)
- return "<UnknownFileName>";
- return _fileName;
- }
- }
-
- public override long Position {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- if (_handle.IsClosed) __Error.FileNotOpen();
- if (!CanSeek) __Error.SeekNotSupported();
-
- Contract.Assert((_readPos == 0 && _readLen == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
-
- // Verify that internal position is in sync with the handle
- if (_exposedHandle)
- VerifyOSHandlePosition();
-
- // Compensate for buffer that we read from the handle (_readLen) Vs what the user
- // read so far from the internel buffer (_readPos). Of course add any unwrittern
- // buffered data
- return _pos + (_readPos - _readLen + _writePos);
- }
- set {
- if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
- if (_writePos > 0) FlushWrite(false);
- _readPos = 0;
- _readLen = 0;
- Seek(value, SeekOrigin.Begin);
- }
- }
-
-#if FEATURE_MACL
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileSecurity GetAccessControl()
- {
- if (_handle.IsClosed) __Error.FileNotOpen();
- return new FileSecurity(_handle, _fileName, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public void SetAccessControl(FileSecurity fileSecurity)
- {
- if (fileSecurity == null)
- throw new ArgumentNullException("fileSecurity");
- Contract.EndContractBlock();
-
- if (_handle.IsClosed) __Error.FileNotOpen();
-
- fileSecurity.Persist(_handle, _fileName);
- }
-#endif
-
- [System.Security.SecuritySafeCritical] // auto-generated
- protected override void Dispose(bool disposing)
- {
- // Nothing will be done differently based on whether we are
- // disposing vs. finalizing. This is taking advantage of the
- // weak ordering between normal finalizable objects & critical
- // finalizable objects, which I included in the SafeHandle
- // design for FileStream, which would often "just work" when
- // finalized.
- try {
- if (_handle != null && !_handle.IsClosed) {
- // Flush data to disk iff we were writing. After
- // thinking about this, we also don't need to flush
- // our read position, regardless of whether the handle
- // was exposed to the user. They probably would NOT
- // want us to do this.
- if (_writePos > 0) {
- FlushWrite(!disposing);
- }
- }
- }
- finally {
- if (_handle != null && !_handle.IsClosed)
- _handle.Dispose();
-
- _canRead = false;
- _canWrite = false;
- _canSeek = false;
- // Don't set the buffer to null, to avoid a NullReferenceException
- // when users have a race condition in their code (ie, they call
- // Close when calling another method on Stream like Read).
- //_buffer = null;
- base.Dispose(disposing);
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- ~FileStream()
- {
- if (_handle != null) {
- BCLDebug.Correctness(_handle.IsClosed, "You didn't close a FileStream & it got finalized. Name: \""+_fileName+"\"");
- Dispose(false);
- }
- }
-
- public override void Flush()
- {
- Flush(false);
- }
-
- [System.Security.SecuritySafeCritical]
- public virtual void Flush(Boolean flushToDisk)
- {
- // This code is duplicated in Dispose
- if (_handle.IsClosed) __Error.FileNotOpen();
-
- FlushInternalBuffer();
-
- if (flushToDisk && CanWrite)
- {
- FlushOSBuffer();
- }
- }
-
- private void FlushInternalBuffer()
- {
- if (_writePos > 0)
- {
- FlushWrite(false);
- }
- else if (_readPos < _readLen && CanSeek)
- {
- FlushRead();
- }
- }
-
- [System.Security.SecuritySafeCritical]
- private void FlushOSBuffer()
- {
- if (!Win32Native.FlushFileBuffers(_handle))
- {
- __Error.WinIOError();
- }
- }
-
- // Reading is done by blocks from the file, but someone could read
- // 1 byte from the buffer then write. At that point, the OS's file
- // pointer is out of sync with the stream's position. All write
- // functions should call this function to preserve the position in the file.
- private void FlushRead() {
- Contract.Assert(_writePos == 0, "FileStream: Write buffer must be empty in FlushRead!");
- if (_readPos - _readLen != 0) {
- Contract.Assert(CanSeek, "FileStream will lose buffered read data now.");
- SeekCore(_readPos - _readLen, SeekOrigin.Current);
- }
- _readPos = 0;
- _readLen = 0;
- }
-
- // Writes are buffered. Anytime the buffer fills up
- // (_writePos + delta > _bufferSize) or the buffer switches to reading
- // and there is left over data (_writePos > 0), this function must be called.
- private void FlushWrite(bool calledFromFinalizer) {
- Contract.Assert(_readPos == 0 && _readLen == 0, "FileStream: Read buffer must be empty in FlushWrite!");
-
- if (_isAsync) {
- IAsyncResult asyncResult = BeginWriteCore(_buffer, 0, _writePos, null, null);
- // With our Whidbey async IO & overlapped support for AD unloads,
- // we don't strictly need to block here to release resources
- // since that support takes care of the pinning & freeing the
- // overlapped struct. We need to do this when called from
- // Close so that the handle is closed when Close returns, but
- // we do't need to call EndWrite from the finalizer.
- // Additionally, if we do call EndWrite, we block forever
- // because AD unloads prevent us from running the managed
- // callback from the IO completion port. Blocking here when
- // called from the finalizer during AD unload is clearly wrong,
- // but we can't use any sort of test for whether the AD is
- // unloading because if we weren't unloading, an AD unload
- // could happen on a separate thread before we call EndWrite.
- if (!calledFromFinalizer)
- EndWrite(asyncResult);
- }
- else
- WriteCore(_buffer, 0, _writePos);
-
- _writePos = 0;
- }
-
-
- [Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public virtual IntPtr Handle {
- [System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#endif
- get {
- Flush();
- // Explicitly dump any buffered data, since the user could move our
- // position or write to the file.
- _readPos = 0;
- _readLen = 0;
- _writePos = 0;
- _exposedHandle = true;
-
- return _handle.DangerousGetHandle();
- }
- }
-
- public virtual SafeFileHandle SafeFileHandle {
- [System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#endif
- get {
- Flush();
- // Explicitly dump any buffered data, since the user could move our
- // position or write to the file.
- _readPos = 0;
- _readLen = 0;
- _writePos = 0;
- _exposedHandle = true;
-
- return _handle;
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override void SetLength(long value)
- {
- if (value < 0)
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- if (_handle.IsClosed) __Error.FileNotOpen();
- if (!CanSeek) __Error.SeekNotSupported();
- if (!CanWrite) __Error.WriteNotSupported();
-
- // Handle buffering updates.
- if (_writePos > 0) {
- FlushWrite(false);
- }
- else if (_readPos < _readLen) {
- FlushRead();
- }
- _readPos = 0;
- _readLen = 0;
-
- if (_appendStart != -1 && value < _appendStart)
- throw new IOException(Environment.GetResourceString("IO.IO_SetLengthAppendTruncate"));
- SetLengthCore(value);
- }
-
- // We absolutely need this method broken out so that BeginWriteCore can call
- // a method without having to go through buffering code that might call
- // FlushWrite.
- [System.Security.SecuritySafeCritical] // auto-generated
- private void SetLengthCore(long value)
- {
- Contract.Assert(value >= 0, "value >= 0");
- long origPos = _pos;
-
- if (_exposedHandle)
- VerifyOSHandlePosition();
- if (_pos != value)
- SeekCore(value, SeekOrigin.Begin);
- if (!Win32Native.SetEndOfFile(_handle)) {
- int hr = Marshal.GetLastWin32Error();
- if (hr==__Error.ERROR_INVALID_PARAMETER)
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_FileLengthTooBig"));
- __Error.WinIOError(hr, String.Empty);
- }
- // Return file pointer to where it was before setting length
- if (origPos != value) {
- if (origPos < value)
- SeekCore(origPos, SeekOrigin.Begin);
- else
- SeekCore(0, SeekOrigin.End);
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override int Read([In, Out] byte[] array, int offset, int count) {
- if (array==null)
- throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- if (_handle.IsClosed) __Error.FileNotOpen();
-
- Contract.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
-
- bool isBlocked = false;
- int n = _readLen - _readPos;
- // if the read buffer is empty, read into either user's array or our
- // buffer, depending on number of bytes user asked for and buffer size.
- if (n == 0) {
- if (!CanRead) __Error.ReadNotSupported();
- if (_writePos > 0) FlushWrite(false);
- if (!CanSeek || (count >= _bufferSize)) {
- n = ReadCore(array, offset, count);
- // Throw away read buffer.
- _readPos = 0;
- _readLen = 0;
- return n;
- }
- if (_buffer == null) _buffer = new byte[_bufferSize];
- n = ReadCore(_buffer, 0, _bufferSize);
- if (n == 0) return 0;
- isBlocked = n < _bufferSize;
- _readPos = 0;
- _readLen = n;
- }
- // Now copy min of count or numBytesAvailable (ie, near EOF) to array.
- if (n > count) n = count;
- Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, n);
- _readPos += n;
-
- // We may have read less than the number of bytes the user asked
- // for, but that is part of the Stream contract. Reading again for
- // more data may cause us to block if we're using a device with
- // no clear end of file, such as a serial port or pipe. If we
- // blocked here & this code was used with redirected pipes for a
- // process's standard output, this can lead to deadlocks involving
- // two processes. But leave this here for files to avoid what would
- // probably be a breaking change. --
-
- // If we are reading from a device with no clear EOF like a
- // serial port or a pipe, this will cause us to block incorrectly.
- if (!_isPipe) {
- // If we hit the end of the buffer and didn't have enough bytes, we must
- // read some more from the underlying stream. However, if we got
- // fewer bytes from the underlying stream than we asked for (ie, we're
- // probably blocked), don't ask for more bytes.
- if (n < count && !isBlocked) {
- Contract.Assert(_readPos == _readLen, "Read buffer should be empty!");
- int moreBytesRead = ReadCore(array, offset + n, count - n);
- n += moreBytesRead;
- // We've just made our buffer inconsistent with our position
- // pointer. We must throw away the read buffer.
- _readPos = 0;
- _readLen = 0;
- }
- }
-
- return n;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- private unsafe int ReadCore(byte[] buffer, int offset, int count) {
- Contract.Assert(!_handle.IsClosed, "!_handle.IsClosed");
- Contract.Assert(CanRead, "CanRead");
-
- Contract.Assert(buffer != null, "buffer != null");
- Contract.Assert(_writePos == 0, "_writePos == 0");
- Contract.Assert(offset >= 0, "offset is negative");
- Contract.Assert(count >= 0, "count is negative");
-
- if (_isAsync) {
- IAsyncResult result = BeginReadCore(buffer, offset, count, null, null, 0);
- return EndRead(result);
- }
-
- // Make sure we are reading from the right spot
- if (_exposedHandle)
- VerifyOSHandlePosition();
-
- int hr = 0;
- int r = ReadFileNative(_handle, buffer, offset, count, null, out hr);
- if (r == -1) {
- // For pipes, ERROR_BROKEN_PIPE is the normal end of the pipe.
- if (hr == ERROR_BROKEN_PIPE) {
- r = 0;
- }
- else {
- if (hr == ERROR_INVALID_PARAMETER)
- throw new ArgumentException(Environment.GetResourceString("Arg_HandleNotSync"));
-
- __Error.WinIOError(hr, String.Empty);
- }
- }
- Contract.Assert(r >= 0, "FileStream's ReadCore is likely broken.");
- _pos += r;
-
- return r;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override long Seek(long offset, SeekOrigin origin) {
- if (origin<SeekOrigin.Begin || origin>SeekOrigin.End)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
- Contract.EndContractBlock();
- if (_handle.IsClosed) __Error.FileNotOpen();
- if (!CanSeek) __Error.SeekNotSupported();
-
- Contract.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
-
- // If we've got bytes in our buffer to write, write them out.
- // If we've read in and consumed some bytes, we'll have to adjust
- // our seek positions ONLY IF we're seeking relative to the current
- // position in the stream. This simulates doing a seek to the new
- // position, then a read for the number of bytes we have in our buffer.
- if (_writePos > 0) {
- FlushWrite(false);
- }
- else if (origin == SeekOrigin.Current) {
- // Don't call FlushRead here, which would have caused an infinite
- // loop. Simply adjust the seek origin. This isn't necessary
- // if we're seeking relative to the beginning or end of the stream.
- offset -= (_readLen - _readPos);
- }
-
- // Verify that internal position is in sync with the handle
- if (_exposedHandle)
- VerifyOSHandlePosition();
-
- long oldPos = _pos + (_readPos - _readLen);
- long pos = SeekCore(offset, origin);
-
- // Prevent users from overwriting data in a file that was opened in
- // append mode.
- if (_appendStart != -1 && pos < _appendStart) {
- SeekCore(oldPos, SeekOrigin.Begin);
- throw new IOException(Environment.GetResourceString("IO.IO_SeekAppendOverwrite"));
- }
-
- // We now must update the read buffer. We can in some cases simply
- // update _readPos within the buffer, copy around the buffer so our
- // Position property is still correct, and avoid having to do more
- // reads from the disk. Otherwise, discard the buffer's contents.
- if (_readLen > 0) {
- // We can optimize the following condition:
- // oldPos - _readPos <= pos < oldPos + _readLen - _readPos
- if (oldPos == pos) {
- if (_readPos > 0) {
- //Console.WriteLine("Seek: seeked for 0, adjusting buffer back by: "+_readPos+" _readLen: "+_readLen);
- Buffer.InternalBlockCopy(_buffer, _readPos, _buffer, 0, _readLen - _readPos);
- _readLen -= _readPos;
- _readPos = 0;
- }
- // If we still have buffered data, we must update the stream's
- // position so our Position property is correct.
- if (_readLen > 0)
- SeekCore(_readLen, SeekOrigin.Current);
- }
- else if (oldPos - _readPos < pos && pos < oldPos + _readLen - _readPos) {
- int diff = (int)(pos - oldPos);
- //Console.WriteLine("Seek: diff was "+diff+", readpos was "+_readPos+" adjusting buffer - shrinking by "+ (_readPos + diff));
- Buffer.InternalBlockCopy(_buffer, _readPos+diff, _buffer, 0, _readLen - (_readPos + diff));
- _readLen -= (_readPos + diff);
- _readPos = 0;
- if (_readLen > 0)
- SeekCore(_readLen, SeekOrigin.Current);
- }
- else {
- // Lose the read buffer.
- _readPos = 0;
- _readLen = 0;
- }
- Contract.Assert(_readLen >= 0 && _readPos <= _readLen, "_readLen should be nonnegative, and _readPos should be less than or equal _readLen");
- Contract.Assert(pos == Position, "Seek optimization: pos != Position! Buffer math was mangled.");
- }
- return pos;
- }
-
- // This doesn't do argument checking. Necessary for SetLength, which must
- // set the file pointer beyond the end of the file. This will update the
- // internal position
- [System.Security.SecuritySafeCritical] // auto-generated
- private long SeekCore(long offset, SeekOrigin origin) {
- Contract.Assert(!_handle.IsClosed && CanSeek, "!_handle.IsClosed && CanSeek");
- Contract.Assert(origin>=SeekOrigin.Begin && origin<=SeekOrigin.End, "origin>=SeekOrigin.Begin && origin<=SeekOrigin.End");
- int hr = 0;
- long ret = 0;
-
- ret = Win32Native.SetFilePointer(_handle, offset, origin, out hr);
- if (ret == -1) {
- // #errorInvalidHandle
- // If ERROR_INVALID_HANDLE is returned, it doesn't suffice to set
- // the handle as invalid; the handle must also be closed.
- //
- // Marking the handle as invalid but not closing the handle
- // resulted in exceptions during finalization and locked column
- // values (due to invalid but unclosed handle) in SQL FileStream
- // scenarios.
- //
- // A more mainstream scenario involves accessing a file on a
- // network share. ERROR_INVALID_HANDLE may occur because the network
- // connection was dropped and the server closed the handle. However,
- // the client side handle is still open and even valid for certain
- // operations.
- //
- // Note that Dispose doesn't throw so we don't need to special case.
- // SetHandleAsInvalid only sets _closed field to true (without
- // actually closing handle) so we don't need to call that as well.
- if (hr == Win32Native.ERROR_INVALID_HANDLE)
- _handle.Dispose();
- __Error.WinIOError(hr, String.Empty);
- }
-
- _pos = ret;
- return ret;
- }
-
- // Checks the position of the OS's handle equals what we expect it to.
- // This will fail if someone else moved the FileStream's handle or if
- // we've hit a bug in FileStream's position updating code.
- private void VerifyOSHandlePosition()
- {
- if (!CanSeek)
- return;
-
- // SeekCore will override the current _pos, so save it now
- long oldPos = _pos;
- long curPos = SeekCore(0, SeekOrigin.Current);
-
- if (curPos != oldPos) {
- // For reads, this is non-fatal but we still could have returned corrupted
- // data in some cases. So discard the internal buffer. Potential MDA
- _readPos = 0;
- _readLen = 0;
- if(_writePos > 0) {
- // Discard the buffer and let the user know!
- _writePos = 0;
- throw new IOException(Environment.GetResourceString("IO.IO_FileStreamHandlePosition"));
- }
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override void Write(byte[] array, int offset, int count) {
- if (array==null)
- throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- if (_handle.IsClosed) __Error.FileNotOpen();
-
- if (_writePos == 0)
- {
- // Ensure we can write to the stream, and ready buffer for writing.
- if (!CanWrite) __Error.WriteNotSupported();
- if (_readPos < _readLen) FlushRead();
- _readPos = 0;
- _readLen = 0;
- }
-
- // If our buffer has data in it, copy data from the user's array into
- // the buffer, and if we can fit it all there, return. Otherwise, write
- // the buffer to disk and copy any remaining data into our buffer.
- // The assumption here is memcpy is cheaper than disk (or net) IO.
- // (10 milliseconds to disk vs. ~20-30 microseconds for a 4K memcpy)
- // So the extra copying will reduce the total number of writes, in
- // non-pathological cases (ie, write 1 byte, then write for the buffer
- // size repeatedly)
- if (_writePos > 0) {
- int numBytes = _bufferSize - _writePos; // space left in buffer
- if (numBytes > 0) {
- if (numBytes > count)
- numBytes = count;
- Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, numBytes);
- _writePos += numBytes;
- if (count==numBytes) return;
- offset += numBytes;
- count -= numBytes;
- }
- // Reset our buffer. We essentially want to call FlushWrite
- // without calling Flush on the underlying Stream.
-
- if (_isAsync) {
- IAsyncResult result = BeginWriteCore(_buffer, 0, _writePos, null, null);
- EndWrite(result);
- }
- else
- {
- WriteCore(_buffer, 0, _writePos);
- }
-
- _writePos = 0;
- }
- // If the buffer would slow writes down, avoid buffer completely.
- if (count >= _bufferSize) {
- Contract.Assert(_writePos == 0, "FileStream cannot have buffered data to write here! Your stream will be corrupted.");
- WriteCore(array, offset, count);
- return;
- }
- else if (count == 0)
- return; // Don't allocate a buffer then call memcpy for 0 bytes.
- if (_buffer==null) _buffer = new byte[_bufferSize];
- // Copy remaining bytes into buffer, to write at a later date.
- Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, count);
- _writePos = count;
- return;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- private unsafe void WriteCore(byte[] buffer, int offset, int count) {
- Contract.Assert(!_handle.IsClosed, "!_handle.IsClosed");
- Contract.Assert(CanWrite, "CanWrite");
-
- Contract.Assert(buffer != null, "buffer != null");
- Contract.Assert(_readPos == _readLen, "_readPos == _readLen");
- Contract.Assert(offset >= 0, "offset is negative");
- Contract.Assert(count >= 0, "count is negative");
-
- if (_isAsync) {
- IAsyncResult result = BeginWriteCore(buffer, offset, count, null, null);
- EndWrite(result);
- return;
- }
-
- // Make sure we are writing to the position that we think we are
- if (_exposedHandle)
- VerifyOSHandlePosition();
-
- int hr = 0;
- int r = WriteFileNative(_handle, buffer, offset, count, null, out hr);
- if (r == -1) {
- // For pipes, ERROR_NO_DATA is not an error, but the pipe is closing.
- if (hr == ERROR_NO_DATA) {
- r = 0;
- }
- else {
- // ERROR_INVALID_PARAMETER may be returned for writes
- // where the position is too large (ie, writing at Int64.MaxValue
- // on Win9x) OR for synchronous writes to a handle opened
- // asynchronously.
- if (hr == ERROR_INVALID_PARAMETER)
- throw new IOException(Environment.GetResourceString("IO.IO_FileTooLongOrHandleNotSync"));
- __Error.WinIOError(hr, String.Empty);
- }
- }
- Contract.Assert(r >= 0, "FileStream's WriteCore is likely broken.");
- _pos += r;
- return;
- }
-
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(ExternalThreading = true)]
- public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, Object stateObject)
- {
- if (array==null)
- throw new ArgumentNullException("array");
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (numBytes < 0)
- throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - offset < numBytes)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- if (_handle.IsClosed) __Error.FileNotOpen();
-
- if (!_isAsync)
- return base.BeginRead(array, offset, numBytes, userCallback, stateObject);
- else
- return BeginReadAsync(array, offset, numBytes, userCallback, stateObject);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(ExternalThreading = true)]
- private FileStreamAsyncResult BeginReadAsync(byte[] array, int offset, int numBytes, AsyncCallback userCallback, Object stateObject)
- {
- Contract.Assert(_isAsync);
-
- if (!CanRead) __Error.ReadNotSupported();
-
- Contract.Assert((_readPos == 0 && _readLen == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
-
- if (_isPipe)
- {
- // When redirecting stdout & stderr with the Process class, it's easy to deadlock your
- // parent & child processes when doing writes 4K at a time. The
- // OS appears to use a 4K buffer internally. If you write to a
- // pipe that is full, you will block until someone read from
- // that pipe. If you try reading from an empty pipe and
- // FileStream's BeginRead blocks waiting for data to fill it's
- // internal buffer, you will be blocked. In a case where a child
- // process writes to stdout & stderr while a parent process tries
- // reading from both, you can easily get into a deadlock here.
- // To avoid this deadlock, don't buffer when doing async IO on
- // pipes. But don't completely ignore buffered data either.
- if (_readPos < _readLen)
- {
- int n = _readLen - _readPos;
- if (n > numBytes) n = numBytes;
- Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, n);
- _readPos += n;
-
- // Return a synchronous FileStreamAsyncResult
- return FileStreamAsyncResult.CreateBufferedReadResult(n, userCallback, stateObject, false);
- }
- else
- {
- Contract.Assert(_writePos == 0, "FileStream must not have buffered write data here! Pipes should be unidirectional.");
- return BeginReadCore(array, offset, numBytes, userCallback, stateObject, 0);
- }
- }
-
- Contract.Assert(!_isPipe, "Should not be a pipe.");
-
- // Handle buffering.
- if (_writePos > 0) FlushWrite(false);
- if (_readPos == _readLen)
- {
- // I can't see how to handle buffering of async requests when
- // filling the buffer asynchronously, without a lot of complexity.
- // The problems I see are issuing an async read, we do an async
- // read to fill the buffer, then someone issues another read
- // (either synchronously or asynchronously) before the first one
- // returns. This would involve some sort of complex buffer locking
- // that we probably don't want to get into, at least not in V1.
- // If we did a sync read to fill the buffer, we could avoid the
- // problem, and any async read less than 64K gets turned into a
- // synchronous read by NT anyways... --
-
- if (numBytes < _bufferSize)
- {
- if (_buffer == null) _buffer = new byte[_bufferSize];
- IAsyncResult bufferRead = BeginReadCore(_buffer, 0, _bufferSize, null, null, 0);
- _readLen = EndRead(bufferRead);
- int n = _readLen;
- if (n > numBytes) n = numBytes;
- Buffer.InternalBlockCopy(_buffer, 0, array, offset, n);
- _readPos = n;
-
- // Return a synchronous FileStreamAsyncResult
- return FileStreamAsyncResult.CreateBufferedReadResult(n, userCallback, stateObject, false);
- }
- else
- {
- // Here we're making our position pointer inconsistent
- // with our read buffer. Throw away the read buffer's contents.
- _readPos = 0;
- _readLen = 0;
- return BeginReadCore(array, offset, numBytes, userCallback, stateObject, 0);
- }
- }
- else
- {
- int n = _readLen - _readPos;
- if (n > numBytes) n = numBytes;
- Buffer.InternalBlockCopy(_buffer, _readPos, array, offset, n);
- _readPos += n;
-
- if (n >= numBytes)
- {
- // Return a synchronous FileStreamAsyncResult
- return FileStreamAsyncResult.CreateBufferedReadResult(n, userCallback, stateObject, false);
- }
- else
- {
- // For streams with no clear EOF like serial ports or pipes
- // we cannot read more data without causing an app to block
- // incorrectly. Pipes don't go down this path
- // though. This code needs to be fixed.
- // Throw away read buffer.
- _readPos = 0;
- _readLen = 0;
- return BeginReadCore(array, offset + n, numBytes - n, userCallback, stateObject, n);
- }
- // WARNING: all state on asyncResult objects must be set before
- // we call ReadFile in BeginReadCore, since the OS can run our
- // callback & the user's callback before ReadFile returns.
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- unsafe private FileStreamAsyncResult BeginReadCore(byte[] bytes, int offset, int numBytes, AsyncCallback userCallback, Object stateObject, int numBufferedBytesRead)
- {
- Contract.Assert(!_handle.IsClosed, "!_handle.IsClosed");
- Contract.Assert(CanRead, "CanRead");
- Contract.Assert(bytes != null, "bytes != null");
- Contract.Assert(_writePos == 0, "_writePos == 0");
- Contract.Assert(_isAsync, "BeginReadCore doesn't work on synchronous file streams!");
- Contract.Assert(offset >= 0, "offset is negative");
- Contract.Assert(numBytes >= 0, "numBytes is negative");
-
- // Create and store async stream class library specific data in the async result
-
- // Must pass in _numBufferedBytes here to ensure all the state on the IAsyncResult
- // object is set before we call ReadFile, which gives the OS an
- // opportunity to run our callback (including the user callback &
- // the call to EndRead) before ReadFile has returned.
- FileStreamAsyncResult asyncResult = new FileStreamAsyncResult(numBufferedBytesRead, bytes, _handle, userCallback, stateObject, false);
- NativeOverlapped* intOverlapped = asyncResult.OverLapped;
-
- // Calculate position in the file we should be at after the read is done
- if (CanSeek) {
- long len = Length;
-
- // Make sure we are reading from the position that we think we are
- if (_exposedHandle)
- VerifyOSHandlePosition();
-
- if (_pos + numBytes > len) {
- if (_pos <= len)
- numBytes = (int) (len - _pos);
- else
- numBytes = 0;
- }
-
- // Now set the position to read from in the NativeOverlapped struct
- // For pipes, we should leave the offset fields set to 0.
- intOverlapped->OffsetLow = unchecked((int)_pos);
- intOverlapped->OffsetHigh = (int)(_pos>>32);
-
- // When using overlapped IO, the OS is not supposed to
- // touch the file pointer location at all. We will adjust it
- // ourselves. This isn't threadsafe.
-
- // WriteFile should not update the file pointer when writing
- // in overlapped mode, according to MSDN. But it does update
- // the file pointer when writing to a UNC path!
- // So changed the code below to seek to an absolute
- // location, not a relative one. ReadFile seems consistent though.
- SeekCore(numBytes, SeekOrigin.Current);
- }
-
- if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
- FrameworkEventSource.Log.ThreadTransferSend((long)(asyncResult.OverLapped), 2, string.Empty, false);
-
- // queue an async ReadFile operation and pass in a packed overlapped
- int hr = 0;
- int r = ReadFileNative(_handle, bytes, offset, numBytes, intOverlapped, out hr);
- // ReadFile, the OS version, will return 0 on failure. But
- // my ReadFileNative wrapper returns -1. My wrapper will return
- // the following:
- // On error, r==-1.
- // On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
- // on async requests that completed sequentially, r==0
- // You will NEVER RELIABLY be able to get the number of bytes
- // read back from this call when using overlapped structures! You must
- // not pass in a non-null lpNumBytesRead to ReadFile when using
- // overlapped structures! This is by design NT behavior.
- if (r==-1 && numBytes!=-1) {
-
- // For pipes, when they hit EOF, they will come here.
- if (hr == ERROR_BROKEN_PIPE) {
- // Not an error, but EOF. AsyncFSCallback will NOT be
- // called. Call the user callback here.
-
- // We clear the overlapped status bit for this special case.
- // Failure to do so looks like we are freeing a pending overlapped later.
- intOverlapped->InternalLow = IntPtr.Zero;
- asyncResult.CallUserCallback();
- // EndRead will free the Overlapped struct correctly.
- }
- else if (hr != ERROR_IO_PENDING) {
- if (!_handle.IsClosed && CanSeek) // Update Position - It could be anywhere.
- SeekCore(0, SeekOrigin.Current);
-
- if (hr == ERROR_HANDLE_EOF)
- __Error.EndOfFile();
- else
- __Error.WinIOError(hr, String.Empty);
- }
- }
- else {
- // Due to a workaround for a race condition in NT's ReadFile &
- // WriteFile routines, we will always be returning 0 from ReadFileNative
- // when we do async IO instead of the number of bytes read,
- // irregardless of whether the operation completed
- // synchronously or asynchronously. We absolutely must not
- // set asyncResult._numBytes here, since will never have correct
- // results.
- //Console.WriteLine("ReadFile returned: "+r+" (0x"+Int32.Format(r, "x")+") The IO completed synchronously, but the user callback was called on a separate thread");
- }
-
- return asyncResult;
- }
-
- [System.Security.SecuritySafeCritical] // Although the unsafe code is only required in PAL, the block is wide scoped. Leave it here for desktop to ensure it's reviewed.
- public unsafe override int EndRead(IAsyncResult asyncResult)
- {
- // There are 3 significantly different IAsyncResults we'll accept
- // here. One is from Stream::BeginRead. The other two are variations
- // on our FileStreamAsyncResult. One is from BeginReadCore,
- // while the other is from the BeginRead buffering wrapper.
- if (asyncResult==null)
- throw new ArgumentNullException("asyncResult");
- Contract.EndContractBlock();
-
- if (!_isAsync)
- return base.EndRead(asyncResult);
-
- FileStreamAsyncResult afsar = asyncResult as FileStreamAsyncResult;
- if (afsar==null || afsar.IsWrite)
- __Error.WrongAsyncResult();
-
- // Ensure we don't have any race conditions by doing an interlocked
- // CompareExchange here. Avoids corrupting memory via freeing the
- // NativeOverlapped class or GCHandle twice. --
- if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
- __Error.EndReadCalledTwice();
-
- // Obtain the WaitHandle, but don't use public property in case we
- // delay initialize the manual reset event in the future.
- afsar.Wait();
-
- // Free memory & GC handles.
- afsar.ReleaseNativeResource();
-
- // Now check for any error during the read.
- if (afsar.ErrorCode != 0)
- __Error.WinIOError(afsar.ErrorCode, String.Empty);
-
- return afsar.NumBytesRead;
- }
-
- // Reads a byte from the file stream. Returns the byte cast to an int
- // or -1 if reading from the end of the stream.
- [System.Security.SecuritySafeCritical] // auto-generated
- public override int ReadByte() {
- if (_handle.IsClosed) __Error.FileNotOpen();
- if (_readLen==0 && !CanRead) __Error.ReadNotSupported();
- Contract.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
- if (_readPos == _readLen) {
- if (_writePos > 0) FlushWrite(false);
- Contract.Assert(_bufferSize > 0, "_bufferSize > 0");
- if (_buffer == null) _buffer = new byte[_bufferSize];
- _readLen = ReadCore(_buffer, 0, _bufferSize);
- _readPos = 0;
- }
- if (_readPos == _readLen)
- return -1;
-
- int result = _buffer[_readPos];
- _readPos++;
- return result;
- }
-
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(ExternalThreading=true)]
- public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, Object stateObject)
- {
- if (array==null)
- throw new ArgumentNullException("array");
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (numBytes < 0)
- throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (array.Length - offset < numBytes)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- if (_handle.IsClosed) __Error.FileNotOpen();
-
- if (!_isAsync)
- return base.BeginWrite(array, offset, numBytes, userCallback, stateObject);
- else
- return BeginWriteAsync(array, offset, numBytes, userCallback, stateObject);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(ExternalThreading = true)]
- private FileStreamAsyncResult BeginWriteAsync(byte[] array, int offset, int numBytes, AsyncCallback userCallback, Object stateObject)
- {
- Contract.Assert(_isAsync);
-
- if (!CanWrite) __Error.WriteNotSupported();
-
- Contract.Assert((_readPos == 0 && _readLen == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
-
- if (_isPipe)
- {
- // When redirecting stdout & stderr with the Process class, it's easy to deadlock your
- // parent & child processes when doing writes 4K at a time. The
- // OS appears to use a 4K buffer internally. If you write to a
- // pipe that is full, you will block until someone read from
- // that pipe. If you try reading from an empty pipe and
- // FileStream's BeginRead blocks waiting for data to fill it's
- // internal buffer, you will be blocked. In a case where a child
- // process writes to stdout & stderr while a parent process tries
- // reading from both, you can easily get into a deadlock here.
- // To avoid this deadlock, don't buffer when doing async IO on
- // pipes.
- Contract.Assert(_readPos == 0 && _readLen == 0, "FileStream must not have buffered data here! Pipes should be unidirectional.");
-
- if (_writePos > 0)
- FlushWrite(false);
-
- return BeginWriteCore(array, offset, numBytes, userCallback, stateObject);
- }
-
- // Handle buffering.
- if (_writePos == 0)
- {
- if (_readPos < _readLen) FlushRead();
- _readPos = 0;
- _readLen = 0;
- }
-
- int n = _bufferSize - _writePos;
- if (numBytes <= n)
- {
- if (_writePos == 0) _buffer = new byte[_bufferSize];
- Buffer.InternalBlockCopy(array, offset, _buffer, _writePos, numBytes);
- _writePos += numBytes;
-
- // Return a synchronous FileStreamAsyncResult
- return FileStreamAsyncResult.CreateBufferedReadResult(numBytes, userCallback, stateObject, true);
- }
-
- if (_writePos > 0)
- FlushWrite(false);
-
- return BeginWriteCore(array, offset, numBytes, userCallback, stateObject);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- unsafe private FileStreamAsyncResult BeginWriteCore(byte[] bytes, int offset, int numBytes, AsyncCallback userCallback, Object stateObject)
- {
- Contract.Assert(!_handle.IsClosed, "!_handle.IsClosed");
- Contract.Assert(CanWrite, "CanWrite");
- Contract.Assert(bytes != null, "bytes != null");
- Contract.Assert(_readPos == _readLen, "_readPos == _readLen");
- Contract.Assert(_isAsync, "BeginWriteCore doesn't work on synchronous file streams!");
- Contract.Assert(offset >= 0, "offset is negative");
- Contract.Assert(numBytes >= 0, "numBytes is negative");
-
- // Create and store async stream class library specific data in the async result
- FileStreamAsyncResult asyncResult = new FileStreamAsyncResult(0, bytes, _handle, userCallback, stateObject, true);
- NativeOverlapped* intOverlapped = asyncResult.OverLapped;
-
- if (CanSeek) {
- // Make sure we set the length of the file appropriately.
- long len = Length;
- //Console.WriteLine("BeginWrite - Calculating end pos. pos: "+pos+" len: "+len+" numBytes: "+numBytes);
-
- // Make sure we are writing to the position that we think we are
- if (_exposedHandle)
- VerifyOSHandlePosition();
-
- if (_pos + numBytes > len) {
- //Console.WriteLine("BeginWrite - Setting length to: "+(pos + numBytes));
- SetLengthCore(_pos + numBytes);
- }
-
- // Now set the position to read from in the NativeOverlapped struct
- // For pipes, we should leave the offset fields set to 0.
- intOverlapped->OffsetLow = (int)_pos;
- intOverlapped->OffsetHigh = (int)(_pos>>32);
-
- // When using overlapped IO, the OS is not supposed to
- // touch the file pointer location at all. We will adjust it
- // ourselves. This isn't threadsafe.
-
- SeekCore(numBytes, SeekOrigin.Current);
- }
-
- //Console.WriteLine("BeginWrite finishing. pos: "+pos+" numBytes: "+numBytes+" _pos: "+_pos+" Position: "+Position);
-
- if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
- FrameworkEventSource.Log.ThreadTransferSend((long)(asyncResult.OverLapped), 2, string.Empty, false);
-
- int hr = 0;
- // queue an async WriteFile operation and pass in a packed overlapped
- int r = WriteFileNative(_handle, bytes, offset, numBytes, intOverlapped, out hr);
-
- // WriteFile, the OS version, will return 0 on failure. But
- // my WriteFileNative wrapper returns -1. My wrapper will return
- // the following:
- // On error, r==-1.
- // On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
- // On async requests that completed sequentially, r==0
- // You will NEVER RELIABLY be able to get the number of bytes
- // written back from this call when using overlapped IO! You must
- // not pass in a non-null lpNumBytesWritten to WriteFile when using
- // overlapped structures! This is ByDesign NT behavior.
- if (r==-1 && numBytes!=-1) {
- //Console.WriteLine("WriteFile returned 0; Write will complete asynchronously (if hr==3e5) hr: 0x{0:x}", hr);
-
- // For pipes, when they are closed on the other side, they will come here.
- if (hr == ERROR_NO_DATA) {
- // Not an error, but EOF. AsyncFSCallback will NOT be
- // called. Call the user callback here.
- asyncResult.CallUserCallback();
- // EndWrite will free the Overlapped struct correctly.
- }
- else if (hr != ERROR_IO_PENDING) {
- if (!_handle.IsClosed && CanSeek) // Update Position - It could be anywhere.
- SeekCore(0, SeekOrigin.Current);
-
- if (hr == ERROR_HANDLE_EOF)
- __Error.EndOfFile();
- else
- __Error.WinIOError(hr, String.Empty);
- }
- }
- else {
- // Due to a workaround for a race condition in NT's ReadFile &
- // WriteFile routines, we will always be returning 0 from WriteFileNative
- // when we do async IO instead of the number of bytes written,
- // irregardless of whether the operation completed
- // synchronously or asynchronously. We absolutely must not
- // set asyncResult._numBytes here, since will never have correct
- // results.
- //Console.WriteLine("WriteFile returned: "+r+" (0x"+Int32.Format(r, "x")+") The IO completed synchronously, but the user callback was called on another thread.");
- }
-
- return asyncResult;
- }
-
- [System.Security.SecuritySafeCritical] // Although the unsafe code is only required in PAL, the block is wide scoped. Leave it here for desktop to ensure it's reviewed.
- public unsafe override void EndWrite(IAsyncResult asyncResult)
- {
- if (asyncResult==null)
- throw new ArgumentNullException("asyncResult");
- Contract.EndContractBlock();
-
- if (!_isAsync) {
- base.EndWrite(asyncResult);
- return;
- }
-
- FileStreamAsyncResult afsar = asyncResult as FileStreamAsyncResult;
- if (afsar==null || !afsar.IsWrite)
- __Error.WrongAsyncResult();
-
- // Ensure we can't have any race conditions by doing an interlocked
- // CompareExchange here. Avoids corrupting memory via freeing the
- // NativeOverlapped class or GCHandle twice. --
- if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
- __Error.EndWriteCalledTwice();
-
- // Obtain the WaitHandle, but don't use public property in case we
- // delay initialize the manual reset event in the future.
- afsar.Wait();
-
- // Free memory & GC handles.
- afsar.ReleaseNativeResource();
-
- // Now check for any error during the write.
- if (afsar.ErrorCode != 0)
- __Error.WinIOError(afsar.ErrorCode, String.Empty);
-
- // Number of bytes written is afsar._numBytes + afsar._numBufferedBytes.
- return;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override void WriteByte(byte value)
- {
- if (_handle.IsClosed) __Error.FileNotOpen();
- if (_writePos==0) {
- if (!CanWrite) __Error.WriteNotSupported();
- if (_readPos < _readLen) FlushRead();
- _readPos = 0;
- _readLen = 0;
- Contract.Assert(_bufferSize > 0, "_bufferSize > 0");
- if (_buffer==null) _buffer = new byte[_bufferSize];
- }
- if (_writePos == _bufferSize)
- FlushWrite(false);
-
- _buffer[_writePos] = value;
- _writePos++;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public virtual void Lock(long position, long length) {
- if (position < 0 || length < 0)
- throw new ArgumentOutOfRangeException((position < 0 ? "position" : "length"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
- if (_handle.IsClosed) __Error.FileNotOpen();
-
- int positionLow = unchecked((int)(position ));
- int positionHigh = unchecked((int)(position >> 32));
- int lengthLow = unchecked((int)(length ));
- int lengthHigh = unchecked((int)(length >> 32));
-
- if (!Win32Native.LockFile(_handle, positionLow, positionHigh, lengthLow, lengthHigh))
- __Error.WinIOError();
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public virtual void Unlock(long position, long length) {
- if (position < 0 || length < 0)
- throw new ArgumentOutOfRangeException((position < 0 ? "position" : "length"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
- if (_handle.IsClosed) __Error.FileNotOpen();
-
- int positionLow = unchecked((int)(position ));
- int positionHigh = unchecked((int)(position >> 32));
- int lengthLow = unchecked((int)(length ));
- int lengthHigh = unchecked((int)(length >> 32));
-
- if (!Win32Native.UnlockFile(_handle, positionLow, positionHigh, lengthLow, lengthHigh))
- __Error.WinIOError();
- }
-
- // Windows API definitions, from winbase.h and others
-
- private const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
- private const int FILE_ATTRIBUTE_ENCRYPTED = 0x00004000;
- private const int FILE_FLAG_OVERLAPPED = 0x40000000;
- internal const int GENERIC_READ = unchecked((int)0x80000000);
- private const int GENERIC_WRITE = 0x40000000;
-
- private const int FILE_BEGIN = 0;
- private const int FILE_CURRENT = 1;
- private const int FILE_END = 2;
-
- // Error codes (not HRESULTS), from winerror.h
- internal const int ERROR_BROKEN_PIPE = 109;
- internal const int ERROR_NO_DATA = 232;
- private const int ERROR_HANDLE_EOF = 38;
- private const int ERROR_INVALID_PARAMETER = 87;
- private const int ERROR_IO_PENDING = 997;
-
-
- // __ConsoleStream also uses this code.
- [System.Security.SecurityCritical] // auto-generated
- private unsafe int ReadFileNative(SafeFileHandle handle, byte[] bytes, int offset, int count, NativeOverlapped* overlapped, out int hr)
- {
- Contract.Requires(handle != null, "handle != null");
- Contract.Requires(offset >= 0, "offset >= 0");
- Contract.Requires(count >= 0, "count >= 0");
- Contract.Requires(bytes != null, "bytes != null");
- // Don't corrupt memory when multiple threads are erroneously writing
- // to this stream simultaneously.
- if (bytes.Length - offset < count)
- throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_IORaceCondition"));
- Contract.EndContractBlock();
-
- Contract.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter mismatch in call to ReadFileNative.");
-
- // You can't use the fixed statement on an array of length 0.
- if (bytes.Length==0) {
- hr = 0;
- return 0;
- }
-
- int r = 0;
- int numBytesRead = 0;
-
- fixed(byte* p = bytes) {
- if (_isAsync)
- r = Win32Native.ReadFile(handle, p + offset, count, IntPtr.Zero, overlapped);
- else
- r = Win32Native.ReadFile(handle, p + offset, count, out numBytesRead, IntPtr.Zero);
- }
-
- if (r==0) {
- hr = Marshal.GetLastWin32Error();
- // We should never silently drop an error here without some
- // extra work. We must make sure that BeginReadCore won't return an
- // IAsyncResult that will cause EndRead to block, since the OS won't
- // call AsyncFSCallback for us.
- if (hr == ERROR_BROKEN_PIPE || hr == Win32Native.ERROR_PIPE_NOT_CONNECTED) {
- // This handle was a pipe, and it's done. Not an error, but EOF.
- // However, the OS will not call AsyncFSCallback!
- // Let the caller handle this, since BeginReadCore & ReadCore
- // need to do different things.
- return -1;
- }
-
- // See code:#errorInvalidHandle in "private long SeekCore(long offset, SeekOrigin origin)".
- if (hr == Win32Native.ERROR_INVALID_HANDLE)
- _handle.Dispose();
-
- return -1;
- }
- else
- hr = 0;
- return numBytesRead;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private unsafe int WriteFileNative(SafeFileHandle handle, byte[] bytes, int offset, int count, NativeOverlapped* overlapped, out int hr) {
- Contract.Requires(handle != null, "handle != null");
- Contract.Requires(offset >= 0, "offset >= 0");
- Contract.Requires(count >= 0, "count >= 0");
- Contract.Requires(bytes != null, "bytes != null");
- // Don't corrupt memory when multiple threads are erroneously writing
- // to this stream simultaneously. (the OS is reading from
- // the array we pass to WriteFile, but if we read beyond the end and
- // that memory isn't allocated, we could get an AV.)
- if (bytes.Length - offset < count)
- throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_IORaceCondition"));
- Contract.EndContractBlock();
-
- Contract.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter missmatch in call to WriteFileNative.");
-
- // You can't use the fixed statement on an array of length 0.
- if (bytes.Length==0) {
- hr = 0;
- return 0;
- }
-
- int numBytesWritten = 0;
- int r = 0;
-
- fixed(byte* p = bytes) {
- if (_isAsync)
- r = Win32Native.WriteFile(handle, p + offset, count, IntPtr.Zero, overlapped);
- else
- r = Win32Native.WriteFile(handle, p + offset, count, out numBytesWritten, IntPtr.Zero);
- }
-
- if (r==0) {
- hr = Marshal.GetLastWin32Error();
- // We should never silently drop an error here without some
- // extra work. We must make sure that BeginWriteCore won't return an
- // IAsyncResult that will cause EndWrite to block, since the OS won't
- // call AsyncFSCallback for us.
-
- if (hr==ERROR_NO_DATA) {
- // This handle was a pipe, and the pipe is being closed on the
- // other side. Let the caller handle this, since BeginWriteCore
- // & WriteCore need to do different things.
- return -1;
- }
-
- // See code:#errorInvalidHandle in "private long SeekCore(long offset, SeekOrigin origin)".
- if (hr == Win32Native.ERROR_INVALID_HANDLE)
- _handle.Dispose();
-
- return -1;
- }
- else
- hr = 0;
- return numBytesWritten;
- }
-
-
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- [SecuritySafeCritical]
- public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
- if (buffer == null)
- throw new ArgumentNullException("buffer");
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- // If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Read() or BeginRead() which a subclass might have overriden.
- // To be safe we will only use this implementation in cases where we know it is safe to do so,
- // and delegate to our base class (which will call into Read/BeginRead) when we are not sure.
- if (this.GetType() != typeof(FileStream))
- return base.ReadAsync(buffer, offset, count, cancellationToken);
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled<int>(cancellationToken);
-
- if (_handle.IsClosed)
- __Error.FileNotOpen();
-
- // If async IO is not supported on this platform or
- // if this FileStream was not opened with FileOptions.Asynchronous.
- if (!_isAsync)
- return base.ReadAsync(buffer, offset, count, cancellationToken);
-
- var readTask = new FileStreamReadWriteTask<int>(cancellationToken);
- var endReadTask = s_endReadTask;
- if (endReadTask == null) s_endReadTask = endReadTask = EndReadTask; // benign initialization race condition
- readTask._asyncResult = BeginReadAsync(buffer, offset, count, endReadTask, readTask);
-
- if (readTask._asyncResult.IsAsync && cancellationToken.CanBeCanceled)
- {
- var cancelReadHandler = s_cancelReadHandler;
- if (cancelReadHandler == null) s_cancelReadHandler = cancelReadHandler = CancelTask<int>; // benign initialization race condition
- readTask._registration = cancellationToken.Register(cancelReadHandler, readTask);
-
- // In case the task is completed right before we register the cancellation callback.
- if (readTask._asyncResult.IsCompleted)
- readTask._registration.Dispose();
- }
-
- return readTask;
- }
-
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- [SecuritySafeCritical]
- public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
- if (buffer == null)
- throw new ArgumentNullException("buffer");
- if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- // If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Write() or BeginWrite() which a subclass might have overriden.
- // To be safe we will only use this implementation in cases where we know it is safe to do so,
- // and delegate to our base class (which will call into Write/BeginWrite) when we are not sure.
- if (this.GetType() != typeof(FileStream))
- return base.WriteAsync(buffer, offset, count, cancellationToken);
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled(cancellationToken);
-
- if (_handle.IsClosed)
- __Error.FileNotOpen();
-
- // If async IO is not supported on this platform or
- // if this FileStream was not opened with FileOptions.Asynchronous.
- if (!_isAsync)
- return base.WriteAsync(buffer, offset, count, cancellationToken);
-
- var writeTask = new FileStreamReadWriteTask<VoidTaskResult>(cancellationToken);
- var endWriteTask = s_endWriteTask;
- if (endWriteTask == null) s_endWriteTask = endWriteTask = EndWriteTask; // benign initialization race condition
- writeTask._asyncResult = BeginWriteAsync(buffer, offset, count, endWriteTask, writeTask);
-
- if (writeTask._asyncResult.IsAsync && cancellationToken.CanBeCanceled)
- {
- var cancelWriteHandler = s_cancelWriteHandler;
- if (cancelWriteHandler == null) s_cancelWriteHandler = cancelWriteHandler = CancelTask<VoidTaskResult>; // benign initialization race condition
- writeTask._registration = cancellationToken.Register(cancelWriteHandler, writeTask);
-
- // In case the task is completed right before we register the cancellation callback.
- if (writeTask._asyncResult.IsCompleted)
- writeTask._registration.Dispose();
- }
-
- return writeTask;
- }
-
- // The task instance returned from ReadAsync and WriteAsync.
- // Also stores all of the state necessary for those calls to avoid closures and extraneous delegate allocations.
- private sealed class FileStreamReadWriteTask<T> : Task<T>
- {
- internal CancellationToken _cancellationToken;
- internal CancellationTokenRegistration _registration;
- internal FileStreamAsyncResult _asyncResult; // initialized after Begin call completes
-
- internal FileStreamReadWriteTask(CancellationToken cancellationToken) : base()
- {
- _cancellationToken = cancellationToken;
- }
- }
-
- // Cancellation callback for both ReadAsync and WriteAsync.
- [SecuritySafeCritical]
- private static void CancelTask<T>(object state)
- {
- var task = state as FileStreamReadWriteTask<T>;
- Contract.Assert(task != null);
- FileStreamAsyncResult asyncResult = task._asyncResult;
-
- // This method is used as both the completion callback and the cancellation callback.
- // We should try to cancel the operation if this is running as the completion callback
- // or if cancellation is not applicable:
- // 1. asyncResult is not a FileStreamAsyncResult
- // 2. asyncResult.IsAsync is false: asyncResult is a "synchronous" FileStreamAsyncResult.
- // 3. The asyncResult is completed: this should never happen.
- Contract.Assert((!asyncResult.IsWrite && typeof(T) == typeof(int)) ||
- (asyncResult.IsWrite && typeof(T) == typeof(VoidTaskResult)));
- Contract.Assert(asyncResult != null);
- Contract.Assert(asyncResult.IsAsync);
-
- try
- {
- // Cancel the overlapped read and set the task to cancelled state.
- if (!asyncResult.IsCompleted)
- asyncResult.Cancel();
- }
- catch (Exception ex)
- {
- task.TrySetException(ex);
- }
- }
-
- // Completion callback for ReadAsync
- [SecuritySafeCritical]
- private static void EndReadTask(IAsyncResult iar)
- {
- FileStreamAsyncResult asyncResult = iar as FileStreamAsyncResult;
- Contract.Assert(asyncResult != null);
- Contract.Assert(asyncResult.IsCompleted, "How can we end up in the completion callback if the IAsyncResult is not completed?");
-
- var readTask = asyncResult.AsyncState as FileStreamReadWriteTask<int>;
- Contract.Assert(readTask != null);
-
- try
- {
- if (asyncResult.IsAsync)
- {
- asyncResult.ReleaseNativeResource();
-
- // release the resource held by CancellationTokenRegistration
- readTask._registration.Dispose();
- }
-
- if (asyncResult.ErrorCode == Win32Native.ERROR_OPERATION_ABORTED)
- {
- var cancellationToken = readTask._cancellationToken;
- Contract.Assert(cancellationToken.IsCancellationRequested, "How can the IO operation be aborted if cancellation was not requested?");
- readTask.TrySetCanceled(cancellationToken);
- }
- else
- readTask.TrySetResult(asyncResult.NumBytesRead);
- }
- catch (Exception ex)
- {
- readTask.TrySetException(ex);
- }
- }
-
- // Completion callback for WriteAsync
- [SecuritySafeCritical]
- private static void EndWriteTask(IAsyncResult iar)
- {
- var asyncResult = iar as FileStreamAsyncResult;
- Contract.Assert(asyncResult != null);
- Contract.Assert(asyncResult.IsCompleted, "How can we end up in the completion callback if the IAsyncResult is not completed?");
-
- var writeTask = iar.AsyncState as FileStreamReadWriteTask<VoidTaskResult>;
- Contract.Assert(writeTask != null);
-
- try
- {
- if (asyncResult.IsAsync)
- {
- asyncResult.ReleaseNativeResource();
-
- // release the resource held by CancellationTokenRegistration
- writeTask._registration.Dispose();
- }
-
- if (asyncResult.ErrorCode == Win32Native.ERROR_OPERATION_ABORTED)
- {
- var cancellationToken = writeTask._cancellationToken;
- Contract.Assert(cancellationToken.IsCancellationRequested, "How can the IO operation be aborted if cancellation was not requested?");
- writeTask.TrySetCanceled(cancellationToken);
- }
- else
- writeTask.TrySetResult(default(VoidTaskResult));
- }
- catch (Exception ex)
- {
- writeTask.TrySetException(ex);
- }
- }
-
- // Unlike Flush(), FlushAsync() always flushes to disk. This is intentional.
- // Legend is that we chose not to flush the OS file buffers in Flush() in fear of
- // perf problems with frequent, long running FlushFileBuffers() calls. But we don't
- // have that problem with FlushAsync() because we will call FlushFileBuffers() in the background.
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- [System.Security.SecuritySafeCritical]
- public override Task FlushAsync(CancellationToken cancellationToken)
- {
- // If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Flush() which a subclass might have overriden. To be safe
- // we will only use this implementation in cases where we know it is safe to do so,
- // and delegate to our base class (which will call into Flush) when we are not sure.
- if (this.GetType() != typeof(FileStream))
- return base.FlushAsync(cancellationToken);
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled(cancellationToken);
-
- if (_handle.IsClosed)
- __Error.FileNotOpen();
-
- // The always synchronous data transfer between the OS and the internal buffer is intentional
- // because this is needed to allow concurrent async IO requests. Concurrent data transfer
- // between the OS and the internal buffer will result in race conditions. Since FlushWrite and
- // FlushRead modify internal state of the stream and transfer data between the OS and the
- // internal buffer, they cannot be truly async. We will, however, flush the OS file buffers
- // asynchronously because it doesn't modify any internal state of the stream and is potentially
- // a long running process.
- try
- {
- FlushInternalBuffer();
- }
- catch (Exception e)
- {
- return Task.FromException(e);
- }
-
- if (CanWrite)
- return Task.Factory.StartNew(
- state => ((FileStream)state).FlushOSBuffer(),
- this,
- cancellationToken,
- TaskCreationOptions.DenyChildAttach,
- TaskScheduler.Default);
- else
- return Task.CompletedTask;
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
index c2e603c06a..f861805ccf 100644
--- a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
+++ b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
@@ -12,17 +12,14 @@
**
===========================================================*/
-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;
@@ -158,7 +155,6 @@ namespace System.IO
// For all the dirs/files returned, demands path discovery permission for their parent folders
internal class FileSystemEnumerableIterator<TSource> : Iterator<TSource>
{
-
private const int STATE_INIT = 1;
private const int STATE_SEARCH_NEXT_DIR = 2;
private const int STATE_FIND_NEXT_FILE = 3;
@@ -168,9 +164,7 @@ namespace System.IO
private List<Directory.SearchData> searchStack;
private Directory.SearchData searchData;
private String searchCriteria;
- [System.Security.SecurityCritical]
SafeFindHandle _hnd = null;
- bool needsParentPathDiscoveryDemand;
// empty means we know in advance that we won’t find any search results, which can happen if:
// 1. we don’t have a search pattern
@@ -185,9 +179,7 @@ namespace System.IO
private String fullPath;
private String normalizedSearchPath;
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);
@@ -211,30 +203,10 @@ namespace System.IO
_resultHandler = resultHandler;
this.searchOption = searchOption;
- fullPath = Path.GetFullPathInternal(path);
+ fullPath = Path.GetFullPath(path);
String fullSearchString = GetFullSearchString(fullPath, normalizedSearchPattern);
normalizedSearchPath = Path.GetDirectoryName(fullSearchString);
- // permission demands
- String[] demandPaths = new String[2];
- // Any illegal chars such as *, ? will be caught by FileIOPermission.HasIllegalCharacters
- demandPaths[0] = Directory.GetDemandDir(fullPath, true);
- // 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);
- _checkHost = checkHost;
-#if FEATURE_CORECLR
- if (checkHost)
- {
- FileSecurityState state1 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[0]);
- state1.EnsureState();
- 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,13 +226,12 @@ 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.InternalCombine(searchData.fullPath, searchCriteria);
+ String searchPath = Path.Combine(searchData.fullPath, searchCriteria);
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
@@ -307,8 +278,7 @@ namespace System.IO
}
}
- [System.Security.SecuritySafeCritical]
- private FileSystemEnumerableIterator(String fullPath, String normalizedSearchPath, String searchCriteria, String userPath, SearchOption searchOption, SearchResultHandler<TSource> resultHandler, bool checkHost)
+ private FileSystemEnumerableIterator(String fullPath, String normalizedSearchPath, String searchCriteria, String userPath, SearchOption searchOption, SearchResultHandler<TSource> resultHandler)
{
this.fullPath = fullPath;
this.normalizedSearchPath = normalizedSearchPath;
@@ -316,30 +286,11 @@ namespace System.IO
this._resultHandler = resultHandler;
this.userPath = userPath;
this.searchOption = searchOption;
- this._checkHost = checkHost;
searchStack = new List<Directory.SearchData>();
if (searchCriteria != null)
{
- // permission demands
- String[] demandPaths = new String[2];
- // Any illegal chars such as *, ? will be caught by FileIOPermission.HasIllegalCharacters
- demandPaths[0] = Directory.GetDemandDir(fullPath, true);
- // 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]);
- state1.EnsureState();
- 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();
}
@@ -351,10 +302,9 @@ namespace System.IO
protected override Iterator<TSource> Clone()
{
- return new FileSystemEnumerableIterator<TSource>(fullPath, normalizedSearchPath, searchCriteria, userPath, searchOption, _resultHandler, _checkHost);
+ return new FileSystemEnumerableIterator<TSource>(fullPath, normalizedSearchPath, searchCriteria, userPath, searchOption, _resultHandler);
}
- [System.Security.SecuritySafeCritical]
protected override void Dispose(bool disposing)
{
try
@@ -371,7 +321,6 @@ namespace System.IO
}
}
- [System.Security.SecuritySafeCritical]
public override bool MoveNext()
{
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
@@ -404,19 +353,19 @@ 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
AddSearchableDirsToStack(searchData);
// Execute searchCriteria against the current directory
- String searchPath = Path.InternalCombine(searchData.fullPath, searchCriteria);
+ String searchPath = Path.Combine(searchData.fullPath, searchCriteria);
// Open a Find handle
_hnd = Win32Native.FindFirstFile(searchPath, data);
@@ -431,15 +380,9 @@ namespace System.IO
}
state = STATE_FIND_NEXT_FILE;
- needsParentPathDiscoveryDemand = true;
SearchResult searchResult = CreateSearchResult(searchData, data);
if (_resultHandler.IsResultIncluded(searchResult))
{
- if (needsParentPathDiscoveryDemand)
- {
- DoDemand(searchData.fullPath);
- needsParentPathDiscoveryDemand = false;
- }
current = _resultHandler.CreateObject(searchResult);
return true;
}
@@ -461,11 +404,6 @@ namespace System.IO
SearchResult searchResult = CreateSearchResult(searchData, data);
if (_resultHandler.IsResultIncluded(searchResult))
{
- if (needsParentPathDiscoveryDemand)
- {
- DoDemand(searchData.fullPath);
- needsParentPathDiscoveryDemand = false;
- }
current = _resultHandler.CreateObject(searchResult);
return true;
}
@@ -506,27 +444,24 @@ namespace System.IO
return false;
}
- [System.Security.SecurityCritical]
private SearchResult CreateSearchResult(Directory.SearchData localSearchData, Win32Native.WIN32_FIND_DATA findData)
{
- String userPathFinal = Path.InternalCombine(localSearchData.userPath, findData.cFileName);
- String fullPathFinal = Path.InternalCombine(localSearchData.fullPath, findData.cFileName);
+ String userPathFinal = Path.Combine(localSearchData.userPath, findData.cFileName);
+ String fullPathFinal = Path.Combine(localSearchData.fullPath, findData.cFileName);
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);
- String searchPath = Path.InternalCombine(localSearchData.fullPath, "*");
+ String searchPath = Path.Combine(localSearchData.fullPath, "*");
SafeFindHandle hnd = null;
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
try
@@ -553,8 +488,8 @@ namespace System.IO
{
if (FileSystemEnumerableHelpers.IsDir(data))
{
- String tempFullPath = Path.InternalCombine(localSearchData.fullPath, data.cFileName);
- String tempUserPath = Path.InternalCombine(localSearchData.userPath, data.cFileName);
+ String tempFullPath = Path.Combine(localSearchData.fullPath, data.cFileName);
+ String tempUserPath = Path.Combine(localSearchData.userPath, data.cFileName);
SearchOption option = localSearchData.searchOption;
@@ -578,28 +513,12 @@ 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)
{
Contract.Requires(searchPattern != null);
- // Win32 normalization trims only U+0020.
- String tempSearchPattern = searchPattern.TrimEnd(Path.TrimEndChars);
+ // Win32 normalization trims only U+0020.
+ String tempSearchPattern = searchPattern.TrimEnd(PathInternal.s_trimEndChars);
// Make this corner case more useful, like dir
if (tempSearchPattern.Equals("."))
@@ -607,7 +526,7 @@ namespace System.IO
tempSearchPattern = "*";
}
- Path.CheckSearchPattern(tempSearchPattern);
+ PathInternal.CheckSearchPattern(tempSearchPattern);
return tempSearchPattern;
}
@@ -619,14 +538,14 @@ namespace System.IO
String searchCriteria = null;
char lastChar = fullPathMod[fullPathMod.Length - 1];
- if (Path.IsDirectorySeparator(lastChar))
+ if (PathInternal.IsDirectorySeparator(lastChar))
{
// Can happen if the path is C:\temp, in which case GetDirectoryName would return C:\
searchCriteria = fullSearchString.Substring(fullPathMod.Length);
}
else
{
- Contract.Assert(fullSearchString.Length > fullPathMod.Length);
+ Debug.Assert(fullSearchString.Length > fullPathMod.Length);
searchCriteria = fullSearchString.Substring(fullPathMod.Length + 1);
}
return searchCriteria;
@@ -637,11 +556,11 @@ namespace System.IO
Contract.Requires(fullPath != null);
Contract.Requires(searchPattern != null);
- String tempStr = Path.InternalCombine(fullPath, searchPattern);
+ String tempStr = Path.Combine(fullPath, searchPattern);
// If path ends in a trailing slash (\), append a * or we'll get a "Cannot find the file specified" exception
char lastChar = tempStr[tempStr.Length - 1];
- if (Path.IsDirectorySeparator(lastChar) || lastChar == Path.VolumeSeparatorChar)
+ if (PathInternal.IsDirectorySeparator(lastChar) || lastChar == Path.VolumeSeparatorChar)
{
tempStr = tempStr + '*';
}
@@ -653,10 +572,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 +589,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 +605,14 @@ 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,26 +621,14 @@ 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);
+ DirectoryInfo di = new DirectoryInfo(result.FullPath, false);
di.InitializeFrom(result.FindData);
return di;
}
@@ -743,17 +637,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);
@@ -761,33 +653,14 @@ namespace System.IO
if (isDir)
{
- 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);
+ DirectoryInfo di = new DirectoryInfo(result.FullPath, false);
di.InitializeFrom(result.FindData);
return di;
}
else
{
Contract.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);
+ FileInfo fi = new FileInfo(result.FullPath, false);
fi.InitializeFrom(result.FindData);
return fi;
}
@@ -799,10 +672,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,15 +696,12 @@ namespace System.IO
internal Win32Native.WIN32_FIND_DATA FindData
{
- [System.Security.SecurityCritical]
get { return findData; }
}
-
}
internal static class FileSystemEnumerableHelpers
{
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDir(Win32Native.WIN32_FIND_DATA data)
{
// Don't add "." nor ".."
@@ -841,7 +709,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);
diff --git a/src/mscorlib/src/System/IO/FileSystemInfo.cs b/src/mscorlib/src/System/IO/FileSystemInfo.cs
index 7a17a417af..94cd531b07 100644
--- a/src/mscorlib/src/System/IO/FileSystemInfo.cs
+++ b/src/mscorlib/src/System/IO/FileSystemInfo.cs
@@ -2,43 +2,19 @@
// 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;
-using System.Security.Permissions;
using Microsoft.Win32;
-using System.Text;
using System.Runtime.InteropServices;
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)]
-#if FEATURE_REMOTING
public abstract class FileSystemInfo : MarshalByRefObject, ISerializable {
-#else // FEATURE_REMOTING
- public abstract class FileSystemInfo : ISerializable {
-#endif //FEATURE_REMOTING
- [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
@@ -51,13 +27,6 @@ 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()
{
}
@@ -65,19 +34,18 @@ namespace System.IO {
protected FileSystemInfo(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
-
+
// Must use V1 field names here, since V1 didn't implement
// ISerializable.
- FullPath = Path.GetFullPathInternal(info.GetString("FullPath"));
+ FullPath = Path.GetFullPath(info.GetString("FullPath"));
OriginalPath = info.GetString("OriginalPath");
// Lazily initialize the file attributes.
_dataInitialised = -1;
}
- [System.Security.SecurityCritical]
internal void InitializeFrom(Win32Native.WIN32_FIND_DATA findData)
{
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
@@ -87,37 +55,8 @@ namespace System.IO {
// Full path of the direcory/file
public virtual String FullName {
- [System.Security.SecuritySafeCritical]
get
{
- String demandDir;
- if (this is DirectoryInfo)
- 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;
- if (this is DirectoryInfo)
- demandDir = Directory.GetDemandDir(FullPath, true);
- else
- demandDir = FullPath;
-#if !FEATURE_CORECLR
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand();
-#endif
return FullPath;
}
}
@@ -160,21 +99,11 @@ namespace System.IO {
// depends on the security check in get_CreationTimeUtc
return CreationTimeUtc.ToLocalTime();
}
-
- set {
- CreationTimeUtc = value.ToUniversalTime();
- }
}
[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();
@@ -187,19 +116,10 @@ namespace System.IO {
return DateTime.FromFileTimeUtc(fileTime);
}
-
- set {
- if (this is DirectoryInfo)
- Directory.SetCreationTimeUtc(FullPath,value);
- else
- File.SetCreationTimeUtc(FullPath,value);
- _dataInitialised = -1;
- }
}
-
public DateTime LastAccessTime
- {
+ {
get {
// depends on the security check in get_LastAccessTimeUtc
return LastAccessTimeUtc.ToLocalTime();
@@ -211,13 +131,7 @@ 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();
@@ -228,15 +142,9 @@ namespace System.IO {
long fileTime = ((long)_data.ftLastAccessTimeHigh << 32) | _data.ftLastAccessTimeLow;
return DateTime.FromFileTimeUtc(fileTime);
-
}
set {
- if (this is DirectoryInfo)
- Directory.SetLastAccessTimeUtc(FullPath,value);
- else
- File.SetLastAccessTimeUtc(FullPath,value);
- _dataInitialised = -1;
}
}
@@ -254,13 +162,7 @@ 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();
@@ -275,28 +177,17 @@ namespace System.IO {
}
set {
- if (this is DirectoryInfo)
- Directory.SetLastWriteTimeUtc(FullPath,value);
- else
- File.SetLastWriteTimeUtc(FullPath,value);
- _dataInitialised = -1;
}
}
- [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
@@ -307,15 +198,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();
@@ -334,14 +218,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));
}
@@ -357,5 +236,5 @@ namespace System.IO {
_displayPath = value;
}
}
- }
+ }
}
diff --git a/src/mscorlib/src/System/IO/LongPathHelper.cs b/src/mscorlib/src/System/IO/LongPathHelper.cs
deleted file mode 100644
index 9746fdc0aa..0000000000
--- a/src/mscorlib/src/System/IO/LongPathHelper.cs
+++ /dev/null
@@ -1,521 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics.Contracts;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using Microsoft.Win32;
-
-namespace System.IO
-{
- /// <summary>
- /// Wrapper to help with path normalization.
- /// </summary>
- internal class LongPathHelper
- {
- // Can't be over 8.3 and be a short name
- private const int MaxShortName = 12;
-
- private const char LastAnsi = (char)255;
- private const char Delete = (char)127;
-
- [ThreadStatic]
- private static StringBuffer t_fullPathBuffer;
-
- /// <summary>
- /// Normalize the given path.
- /// </summary>
- /// <remarks>
- /// Normalizes via Win32 GetFullPathName(). It will also trim all "typical" whitespace at the end of the path (see s_trimEndChars). Will also trim initial
- /// spaces if the path is determined to be rooted.
- ///
- /// Note that invalid characters will be checked after the path is normalized, which could remove bad characters. (C:\|\..\a.txt -- C:\a.txt)
- /// </remarks>
- /// <param name="path">Path to normalize</param>
- /// <param name="checkInvalidCharacters">True to check for invalid characters</param>
- /// <param name="expandShortPaths">Attempt to expand short paths if true</param>
- /// <exception cref="ArgumentException">Thrown if the path is an illegal UNC (does not contain a full server/share) or contains illegal characters.</exception>
- /// <exception cref="PathTooLongException">Thrown if the path or a path segment exceeds the filesystem limits.</exception>
- /// <exception cref="FileNotFoundException">Thrown if Windows returns ERROR_FILE_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception>
- /// <exception cref="DirectoryNotFoundException">Thrown if Windows returns ERROR_PATH_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception>
- /// <exception cref="UnauthorizedAccessException">Thrown if Windows returns ERROR_ACCESS_DENIED. (See Win32Marshal.GetExceptionForWin32Error)</exception>
- /// <exception cref="IOException">Thrown if Windows returns an error that doesn't map to the above. (See Win32Marshal.GetExceptionForWin32Error)</exception>
- /// <returns>Normalized path</returns>
- [System.Security.SecurityCritical]
- unsafe internal static string Normalize(string path, uint maxPathLength, bool checkInvalidCharacters, bool expandShortPaths)
- {
- // Get the full path
- StringBuffer fullPath = t_fullPathBuffer ?? (t_fullPathBuffer = new StringBuffer(PathInternal.MaxShortPath));
- try
- {
- GetFullPathName(path, fullPath);
-
- // Trim whitespace off the end of the string. Win32 normalization trims only U+0020.
- fullPath.TrimEnd(Path.TrimEndChars);
-
- if (fullPath.Length >= maxPathLength)
- {
- // Fullpath is genuinely too long
- throw new PathTooLongException();
- }
-
- // Checking path validity used to happen before getting the full path name. To avoid additional input allocation
- // (to trim trailing whitespace) we now do it after the Win32 call. This will allow legitimate paths through that
- // used to get kicked back (notably segments with invalid characters might get removed via "..").
- //
- // There is no way that GetLongPath can invalidate the path so we'll do this (cheaper) check before we attempt to
- // expand short file names.
-
- // Scan the path for:
- //
- // - Illegal path characters.
- // - Invalid UNC paths like \\, \\server, \\server\.
- // - Segments that are too long (over MaxComponentLength)
-
- // As the path could be > 60K, we'll combine the validity scan. None of these checks are performed by the Win32
- // GetFullPathName() API.
-
- bool possibleShortPath = false;
- bool foundTilde = false;
-
- // We can get UNCs as device paths through this code (e.g. \\.\UNC\), we won't validate them as there isn't
- // an easy way to normalize without extensive cost (we'd have to hunt down the canonical name for any device
- // path that contains UNC or to see if the path was doing something like \\.\GLOBALROOT\Device\Mup\,
- // \\.\GLOBAL\UNC\, \\.\GLOBALROOT\GLOBAL??\UNC\, etc.
- bool specialPath = fullPath.Length > 1 && fullPath[0] == '\\' && fullPath[1] == '\\';
- bool isDevice = PathInternal.IsDevice(fullPath);
- bool possibleBadUnc = specialPath && !isDevice;
- uint index = specialPath ? 2u : 0;
- uint lastSeparator = specialPath ? 1u : 0;
- uint segmentLength;
- char* start = fullPath.CharPointer;
- char current;
-
- while (index < fullPath.Length)
- {
- current = start[index];
-
- // Try to skip deeper analysis. '?' and higher are valid/ignorable except for '\', '|', and '~'
- if (current < '?' || current == '\\' || current == '|' || current == '~')
- {
- switch (current)
- {
- case '|':
- case '>':
- case '<':
- case '\"':
- if (checkInvalidCharacters) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
- // No point in expanding a bad path
- foundTilde = false;
- break;
- case '~':
- foundTilde = true;
- break;
- case '\\':
- segmentLength = index - lastSeparator - 1;
- if (segmentLength > (uint)PathInternal.MaxComponentLength)
- throw new PathTooLongException();
- lastSeparator = index;
-
- if (foundTilde)
- {
- if (segmentLength <= MaxShortName)
- {
- // Possibly a short path.
- possibleShortPath = true;
- }
-
- foundTilde = false;
- }
-
- if (possibleBadUnc)
- {
- // If we're at the end of the path and this is the first separator, we're missing the share.
- // Otherwise we're good, so ignore UNC tracking from here.
- if (index == fullPath.Length - 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegalUNC"));
- else
- possibleBadUnc = false;
- }
-
- break;
-
- default:
- if (checkInvalidCharacters && current < ' ') throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
- break;
- }
- }
-
- index++;
- }
-
- if (possibleBadUnc)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegalUNC"));
-
- segmentLength = fullPath.Length - lastSeparator - 1;
- if (segmentLength > (uint)PathInternal.MaxComponentLength)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- if (foundTilde && segmentLength <= MaxShortName)
- possibleShortPath = true;
-
- // Check for a short filename path and try and expand it. Technically you don't need to have a tilde for a short name, but
- // this is how we've always done this. This expansion is costly so we'll continue to let other short paths slide.
- if (expandShortPaths && possibleShortPath)
- {
- return TryExpandShortFileName(fullPath, originalPath: path);
- }
- else
- {
- if (fullPath.Length == (uint)path.Length && fullPath.StartsWith(path))
- {
- // If we have the exact same string we were passed in, don't bother to allocate another string from the StringBuilder.
- return path;
- }
- else
- {
- return fullPath.ToString();
- }
- }
- }
- finally
- {
- // Clear the buffer
- fullPath.Free();
- }
- }
-
- [System.Security.SecurityCritical]
- unsafe private static void GetFullPathName(string path, StringBuffer fullPath)
- {
- // If the string starts with an extended prefix we would need to remove it from the path before we call GetFullPathName as
- // it doesn't root extended paths correctly. We don't currently resolve extended paths, so we'll just assert here.
- Contract.Assert(PathInternal.IsPartiallyQualified(path) || !PathInternal.IsExtended(path));
-
- // Historically we would skip leading spaces *only* if the path started with a drive " C:" or a UNC " \\"
- int startIndex = PathInternal.PathStartSkip(path);
-
- fixed (char* pathStart = path)
- {
- uint result = 0;
- while ((result = Win32Native.GetFullPathNameW(pathStart + startIndex, fullPath.CharCapacity, fullPath.GetHandle(), IntPtr.Zero)) > fullPath.CharCapacity)
- {
- // Reported size (which does not include the null) is greater than the buffer size. Increase the capacity.
- fullPath.EnsureCharCapacity(result);
- }
-
- if (result == 0)
- {
- // Failure, get the error and throw
- int errorCode = Marshal.GetLastWin32Error();
- if (errorCode == 0)
- errorCode = Win32Native.ERROR_BAD_PATHNAME;
- __Error.WinIOError(errorCode, path);
- }
-
- fullPath.Length = result;
- }
- }
-
- [System.Security.SecurityCritical]
- unsafe internal static string GetLongPathName(StringBuffer path)
- {
- using (StringBuffer outputBuffer = new StringBuffer(path.Length))
- {
- uint result = 0;
- while ((result = Win32Native.GetLongPathNameW(path.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity)) > outputBuffer.CharCapacity)
- {
- // Reported size (which does not include the null) is greater than the buffer size. Increase the capacity.
- outputBuffer.EnsureCharCapacity(result);
- }
-
- if (result == 0)
- {
- // Failure, get the error and throw
- GetErrorAndThrow(path.ToString());
- }
-
- outputBuffer.Length = result;
- return outputBuffer.ToString();
- }
- }
-
- [System.Security.SecurityCritical]
- unsafe internal static string GetLongPathName(string path)
- {
- using (StringBuffer outputBuffer = new StringBuffer((uint)path.Length))
- {
- uint result = 0;
- while ((result = Win32Native.GetLongPathNameW(path, outputBuffer.GetHandle(), outputBuffer.CharCapacity)) > outputBuffer.CharCapacity)
- {
- // Reported size (which does not include the null) is greater than the buffer size. Increase the capacity.
- outputBuffer.EnsureCharCapacity(result);
- }
-
- if (result == 0)
- {
- // Failure, get the error and throw
- GetErrorAndThrow(path);
- }
-
- outputBuffer.Length = result;
- return outputBuffer.ToString();
- }
- }
-
- [System.Security.SecurityCritical]
- private static void GetErrorAndThrow(string path)
- {
- int errorCode = Marshal.GetLastWin32Error();
- if (errorCode == 0)
- errorCode = Win32Native.ERROR_BAD_PATHNAME;
- __Error.WinIOError(errorCode, path);
- }
-
- // It is significantly more complicated to get the long path with minimal allocations if we're injecting the extended dos path prefix. The implicit version
- // should match up with what is in CoreFx System.Runtime.Extensions.
-#if !FEATURE_IMPLICIT_LONGPATH
- [System.Security.SecuritySafeCritical]
- private unsafe static string TryExpandShortFileName(StringBuffer outputBuffer, string originalPath)
- {
- // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To
- // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls.
-
- Contract.Assert(!PathInternal.IsPartiallyQualified(outputBuffer), "should have resolved by now");
-
- using (StringBuffer inputBuffer = new StringBuffer(outputBuffer))
- {
- bool success = false;
- uint lastIndex = outputBuffer.Length - 1;
- uint foundIndex = lastIndex;
- uint rootLength = PathInternal.GetRootLength(outputBuffer);
-
- while (!success)
- {
- uint result = Win32Native.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity);
-
- // Replace any temporary null we added
- if (inputBuffer[foundIndex] == '\0') inputBuffer[foundIndex] = '\\';
-
- if (result == 0)
- {
- // Look to see if we couldn't find the file
- int error = Marshal.GetLastWin32Error();
- if (error != Win32Native.ERROR_FILE_NOT_FOUND && error != Win32Native.ERROR_PATH_NOT_FOUND)
- {
- // Some other failure, give up
- break;
- }
-
- // We couldn't find the path at the given index, start looking further back in the string.
- foundIndex--;
-
- for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--) ;
- if (foundIndex == rootLength)
- {
- // Can't trim the path back any further
- break;
- }
- else
- {
- // Temporarily set a null in the string to get Windows to look further up the path
- inputBuffer[foundIndex] = '\0';
- }
- }
- else if (result > outputBuffer.CharCapacity)
- {
- // Not enough space. The result count for this API does not include the null terminator.
- outputBuffer.EnsureCharCapacity(result);
- }
- else
- {
- // Found the path
- success = true;
- outputBuffer.Length = result;
- if (foundIndex < lastIndex)
- {
- // It was a partial find, put the non-existant part of the path back
- outputBuffer.Append(inputBuffer, foundIndex, inputBuffer.Length - foundIndex);
- }
- }
- }
-
- StringBuffer bufferToUse = success ? outputBuffer : inputBuffer;
-
- if (bufferToUse.SubstringEquals(originalPath))
- {
- // Use the original path to avoid allocating
- return originalPath;
- }
-
- return bufferToUse.ToString();
- }
- }
-#else // !FEATURE_IMPLICIT_LONGPATH
-
- private static uint GetInputBuffer(StringBuffer content, bool isDosUnc, out StringBuffer buffer)
- {
- uint length = content.Length;
-
- length += isDosUnc
- ? (uint)PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength
- : PathInternal.DevicePrefixLength;
-
- buffer = new StringBuffer(length);
-
- if (isDosUnc)
- {
- // Put the extended UNC prefix (\\?\UNC\) in front of the path
- buffer.CopyFrom(bufferIndex: 0, source: PathInternal.UncExtendedPathPrefix);
-
- // Copy the source buffer over after the existing UNC prefix
- content.CopyTo(
- bufferIndex: PathInternal.UncPrefixLength,
- destination: buffer,
- destinationIndex: PathInternal.UncExtendedPrefixLength,
- count: content.Length - PathInternal.UncPrefixLength);
-
- // Return the prefix difference
- return (uint)PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength;
- }
- else
- {
- uint prefixSize = (uint)PathInternal.ExtendedPathPrefix.Length;
- buffer.CopyFrom(bufferIndex: 0, source: PathInternal.ExtendedPathPrefix);
- content.CopyTo(bufferIndex: 0, destination: buffer, destinationIndex: prefixSize, count: content.Length);
- return prefixSize;
- }
- }
-
- [System.Security.SecuritySafeCritical]
- private static string TryExpandShortFileName(StringBuffer outputBuffer, string originalPath)
- {
- // We'll have one of a few cases by now (the normalized path will have already:
- //
- // 1. Dos path (C:\)
- // 2. Dos UNC (\\Server\Share)
- // 3. Dos device path (\\.\C:\, \\?\C:\)
- //
- // We want to put the extended syntax on the front if it doesn't already have it, which may mean switching from \\.\.
-
- uint rootLength = PathInternal.GetRootLength(outputBuffer);
- bool isDevice = PathInternal.IsDevice(outputBuffer);
-
- StringBuffer inputBuffer = null;
- bool isDosUnc = false;
- uint rootDifference = 0;
- bool wasDotDevice = false;
-
- // Add the extended prefix before expanding to allow growth over MAX_PATH
- if (isDevice)
- {
- // We have one of the following (\\?\ or \\.\)
- // We will never get \??\ here as GetFullPathName() does not recognize \??\ and will return it as C:\??\ (or whatever the current drive is).
- inputBuffer = new StringBuffer();
- inputBuffer.Append(outputBuffer);
-
- if (outputBuffer[2] == '.')
- {
- wasDotDevice = true;
- inputBuffer[2] = '?';
- }
- }
- else
- {
- // \\Server\Share, but not \\.\ or \\?\.
- // We need to know this to be able to push \\?\UNC\ on if required
- isDosUnc = outputBuffer.Length > 1 && outputBuffer[0] == '\\' && outputBuffer[1] == '\\' && !PathInternal.IsDevice(outputBuffer);
- rootDifference = GetInputBuffer(outputBuffer, isDosUnc, out inputBuffer);
- }
-
- rootLength += rootDifference;
- uint inputLength = inputBuffer.Length;
-
- bool success = false;
- uint foundIndex = inputBuffer.Length - 1;
-
- while (!success)
- {
- uint result = Win32Native.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity);
-
- // Replace any temporary null we added
- if (inputBuffer[foundIndex] == '\0') inputBuffer[foundIndex] = '\\';
-
- if (result == 0)
- {
- // Look to see if we couldn't find the file
- int error = Marshal.GetLastWin32Error();
- if (error != Win32Native.ERROR_FILE_NOT_FOUND && error != Win32Native.ERROR_PATH_NOT_FOUND)
- {
- // Some other failure, give up
- break;
- }
-
- // We couldn't find the path at the given index, start looking further back in the string.
- foundIndex--;
-
- for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--) ;
- if (foundIndex == rootLength)
- {
- // Can't trim the path back any further
- break;
- }
- else
- {
- // Temporarily set a null in the string to get Windows to look further up the path
- inputBuffer[foundIndex] = '\0';
- }
- }
- else if (result > outputBuffer.CharCapacity)
- {
- // Not enough space. The result count for this API does not include the null terminator.
- outputBuffer.EnsureCharCapacity(result);
- result = Win32Native.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity);
- }
- else
- {
- // Found the path
- success = true;
- outputBuffer.Length = result;
- if (foundIndex < inputLength - 1)
- {
- // It was a partial find, put the non-existent part of the path back
- outputBuffer.Append(inputBuffer, foundIndex, inputBuffer.Length - foundIndex);
- }
- }
- }
-
- // Strip out the prefix and return the string
- StringBuffer bufferToUse = success ? outputBuffer : inputBuffer;
-
- // Switch back from \\?\ to \\.\ if necessary
- if (wasDotDevice)
- bufferToUse[2] = '.';
-
- string returnValue = null;
-
- int newLength = (int)(bufferToUse.Length - rootDifference);
- if (isDosUnc)
- {
- // Need to go from \\?\UNC\ to \\?\UN\\
- bufferToUse[PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength] = '\\';
- }
-
- // We now need to strip out any added characters at the front of the string
- if (bufferToUse.SubstringEquals(originalPath, rootDifference, newLength))
- {
- // Use the original path to avoid allocating
- returnValue = originalPath;
- }
- else
- {
- returnValue = bufferToUse.Substring(rootDifference, newLength);
- }
-
- inputBuffer.Dispose();
- return returnValue;
- }
-#endif // FEATURE_IMPLICIT_LONGPATH
- }
-} \ No newline at end of file
diff --git a/src/mscorlib/src/System/IO/MemoryStream.cs b/src/mscorlib/src/System/IO/MemoryStream.cs
index edb583b9b5..bdddc83818 100644
--- a/src/mscorlib/src/System/IO/MemoryStream.cs
+++ b/src/mscorlib/src/System/IO/MemoryStream.cs
@@ -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;
@@ -61,7 +62,7 @@ namespace System.IO {
public MemoryStream(int capacity) {
if (capacity < 0) {
- throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
Contract.EndContractBlock();
@@ -79,7 +80,7 @@ namespace System.IO {
}
public MemoryStream(byte[] buffer, bool writable) {
- if (buffer == null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ if (buffer == null) throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
Contract.EndContractBlock();
_buffer = buffer;
_length = _capacity = buffer.Length;
@@ -99,11 +100,11 @@ namespace System.IO {
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) {
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -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;
}
@@ -276,7 +276,7 @@ namespace System.IO {
set {
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
- if (value < Length) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
Contract.Ensures(_capacity - _origin == value);
Contract.EndContractBlock();
@@ -312,25 +312,25 @@ namespace System.IO {
}
set {
if (value < 0)
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Position == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (value > MemStreamMaxLength)
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
_position = _origin + (int)value;
}
}
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -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,16 +357,15 @@ namespace System.IO {
return n;
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
@@ -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));
}
@@ -402,36 +401,46 @@ namespace System.IO {
return _buffer[_position++];
}
+ public override void CopyTo(Stream destination, int bufferSize)
+ {
+ // Since we did not originally override this method, validate the arguments
+ // the same way Stream does for back-compat.
+ StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
- public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) {
-
- // This implementation offers beter performance compared to the base class version.
-
- // The parameter checks must be in sync with the base version:
- if (destination == null)
- throw new ArgumentNullException("destination");
+ // If we have been inherited into a subclass, the following implementation could be incorrect
+ // since it does not call through to Read() which a subclass might have overridden.
+ // To be safe we will only use this implementation in cases where we know it is safe to do so,
+ // and delegate to our base class (which will call into Read) when we are not sure.
+ if (GetType() != typeof(MemoryStream))
+ {
+ base.CopyTo(destination, bufferSize);
+ return;
+ }
- if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ int originalPosition = _position;
- if (!CanRead && !CanWrite)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+ // Seek to the end of the MemoryStream.
+ int remaining = InternalEmulateRead(_length - originalPosition);
- if (!destination.CanRead && !destination.CanWrite)
- throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+ // If we were already at or past the end, there's no copying to do so just quit.
+ if (remaining > 0)
+ {
+ // Call Write() on the other Stream, using our internal buffer and avoiding any
+ // intermediary allocations.
+ destination.Write(_buffer, originalPosition, remaining);
+ }
+ }
- if (!CanRead)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
+ public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) {
- if (!destination.CanWrite)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
+ // This implementation offers beter performance compared to the base class version.
- Contract.EndContractBlock();
+ StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Read() or Write() which a subclass might have overriden.
+ // since it does not call through to ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
- // and delegate to our base class (which will call into Read/Write) when we are not sure.
+ // and delegate to our base class (which will call into ReadAsync) when we are not sure.
if (this.GetType() != typeof(MemoryStream))
return base.CopyToAsync(destination, bufferSize, cancellationToken);
@@ -467,7 +476,7 @@ namespace System.IO {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > MemStreamMaxLength)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
switch(loc) {
case SeekOrigin.Begin: {
int tempPosition = unchecked(_origin + (int)offset);
@@ -494,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;
}
@@ -510,16 +519,16 @@ namespace System.IO {
//
public override void SetLength(long value) {
if (value < 0 || value > Int32.MaxValue) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
Contract.Ensures(_length - _origin == value);
Contract.EndContractBlock();
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("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
int newLength = _origin + (int)value;
@@ -540,11 +549,11 @@ namespace System.IO {
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -580,16 +589,15 @@ namespace System.IO {
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(...)
@@ -636,7 +644,7 @@ namespace System.IO {
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream) {
if (stream==null)
- throw new ArgumentNullException("stream", Environment.GetResourceString("ArgumentNull_Stream"));
+ throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
diff --git a/src/mscorlib/src/System/IO/Path.cs b/src/mscorlib/src/System/IO/Path.cs
deleted file mode 100644
index 4f7993633b..0000000000
--- a/src/mscorlib/src/System/IO/Path.cs
+++ /dev/null
@@ -1,1435 +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: A collection of path manipulation methods.
-**
-**
-===========================================================*/
-
-using System;
-using System.Security.Permissions;
-using Win32Native = Microsoft.Win32.Win32Native;
-using System.Text;
-using System.Runtime.InteropServices;
-using System.Security;
-#if FEATURE_LEGACYSURFACE
-using System.Security.Cryptography;
-#endif
-using System.Runtime.CompilerServices;
-using System.Globalization;
-using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
-
-namespace System.IO {
- // Provides methods for processing directory strings in an ideally
- // cross-platform manner. Most of the methods don't do a complete
- // full parsing (such as examining a UNC hostname), but they will
- // handle most string operations.
- [ComVisible(true)]
- public static class Path
- {
- // Platform specific directory separator character. This is backslash
- // ('\') on Windows and slash ('/') on Unix.
- //
-#if !PLATFORM_UNIX
- public static readonly char DirectorySeparatorChar = '\\';
- internal const string DirectorySeparatorCharAsString = "\\";
-#else
- public static readonly char DirectorySeparatorChar = '/';
- internal const string DirectorySeparatorCharAsString = "/";
-#endif // !PLATFORM_UNIX
-
- // Platform specific alternate directory separator character.
- // There is only one directory separator char on Unix,
- // so the same definition is used for both Unix and Windows.
- public static readonly char AltDirectorySeparatorChar = '/';
-
- // Platform specific volume separator character. This is colon (':')
- // on Windows and MacOS, and slash ('/') on Unix. This is mostly
- // useful for parsing paths like "c:\windows" or "MacVolume:System Folder".
- //
-#if !PLATFORM_UNIX
- public static readonly char VolumeSeparatorChar = ':';
-#else
- public static readonly char VolumeSeparatorChar = '/';
-#endif // !PLATFORM_UNIX
-
- // Platform specific invalid list of characters in a path.
- // See the "Naming a File" MSDN conceptual docs for more details on
- // what is valid in a file name (which is slightly different from what
- // is legal in a path name).
- // Note: This list is duplicated in CheckInvalidPathChars
- [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")]
-#if !PLATFORM_UNIX
- public static readonly char[] InvalidPathChars = { '\"', '<', '>', '|', '\0', (Char)1, (Char)2, (Char)3, (Char)4, (Char)5, (Char)6, (Char)7, (Char)8, (Char)9, (Char)10, (Char)11, (Char)12, (Char)13, (Char)14, (Char)15, (Char)16, (Char)17, (Char)18, (Char)19, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25, (Char)26, (Char)27, (Char)28, (Char)29, (Char)30, (Char)31 };
-#else
- public static readonly char[] InvalidPathChars = { '\0' };
-#endif // !PLATFORM_UNIX
-
- // Trim trailing white spaces, tabs etc but don't be aggressive in removing everything that has UnicodeCategory of trailing space.
- // String.WhitespaceChars will trim aggressively than what the underlying FS does (for ex, NTFS, FAT).
- internal static readonly char[] TrimEndChars =
- {
- (char)0x09, // Horizontal tab
- (char)0x0A, // Line feed
- (char)0x0B, // Vertical tab
- (char)0x0C, // Form feed
- (char)0x0D, // Carriage return
- (char)0x20, // Space
- (char)0x85, // Next line
- (char)0xA0 // Non breaking space
- };
-
-#if !PLATFORM_UNIX
- private static readonly char[] RealInvalidPathChars = PathInternal.InvalidPathChars;
-
- private static readonly char[] InvalidFileNameChars = { '\"', '<', '>', '|', '\0', (Char)1, (Char)2, (Char)3, (Char)4, (Char)5, (Char)6, (Char)7, (Char)8, (Char)9, (Char)10, (Char)11, (Char)12, (Char)13, (Char)14, (Char)15, (Char)16, (Char)17, (Char)18, (Char)19, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25, (Char)26, (Char)27, (Char)28, (Char)29, (Char)30, (Char)31, ':', '*', '?', '\\', '/' };
-#else
- private static readonly char[] RealInvalidPathChars = { '\0' };
-
- private static readonly char[] InvalidFileNameChars = { '\0', '/' };
-#endif // !PLATFORM_UNIX
-
-#if !PLATFORM_UNIX
- public static readonly char PathSeparator = ';';
-#else
- public static readonly char PathSeparator = ':';
-#endif // !PLATFORM_UNIX
-
-
- // The max total path is 260, and the max individual component length is 255.
- // For example, D:\<256 char file name> isn't legal, even though it's under 260 chars.
- internal static readonly int MaxPath = PathInternal.MaxShortPath;
-
- internal static readonly int MaxPathComponentLength = PathInternal.MaxComponentLength;
-
- // Windows API definitions
- internal const int MAX_PATH = 260; // From WinDef.h
- internal const int MAX_DIRECTORY_PATH = 248; // cannot create directories greater than 248 characters
-
- // Changes the extension of a file path. The path parameter
- // specifies a file path, and the extension parameter
- // specifies a file extension (with a leading period, such as
- // ".exe" or ".cs").
- //
- // The function returns a file path with the same root, directory, and base
- // name parts as path, but with the file extension changed to
- // the specified extension. If path is null, the function
- // returns null. If path does not contain a file extension,
- // the new file extension is appended to the path. If extension
- // is null, any exsiting extension is removed from path.
- //
- public static String ChangeExtension(String path, String extension) {
- if (path != null) {
- CheckInvalidPathChars(path);
-
- String s = path;
- for (int i = path.Length; --i >= 0;) {
- char ch = path[i];
- if (ch == '.') {
- s = path.Substring(0, i);
- break;
- }
- if (ch == DirectorySeparatorChar || ch == AltDirectorySeparatorChar || ch == VolumeSeparatorChar) break;
- }
- if (extension != null && path.Length != 0) {
- if (extension.Length == 0 || extension[0] != '.') {
- s = s + ".";
- }
- s = s + extension;
- }
- return s;
- }
- return null;
- }
-
- // Returns the directory path of a file path. This method effectively
- // removes the last element of the given file path, i.e. it returns a
- // string consisting of all characters up to but not including the last
- // backslash ("\") in the file path. The returned value is null if the file
- // path is null or if the file path denotes a root (such as "\", "C:", or
- // "\\server\share").
- public static String GetDirectoryName(String path)
- {
- return GetDirectoryNameInternal(path);
- }
-
- [System.Security.SecuritySafeCritical]
- private static string GetDirectoryNameInternal(string path)
- {
- if (path != null)
- {
- CheckInvalidPathChars(path);
-
- // Expanding short paths is dangerous in this case as the results will change with the current directory.
- //
- // Suppose you have a path called "PICTUR~1\Foo". Now suppose you have two folders on disk "C:\Mine\Pictures Of Me"
- // and "C:\Yours\Pictures of You". If the current directory is neither you'll get back "PICTUR~1". If it is "C:\Mine"
- // get back "Pictures Of Me". "C:\Yours" would give back "Pictures of You".
- //
- // Because of this and as it isn't documented that short paths are expanded we will not expand short names unless
- // we're in legacy mode.
- string normalizedPath = NormalizePath(path, fullCheck: false, expandShortPaths:
-#if FEATURE_PATHCOMPAT
- AppContextSwitches.UseLegacyPathHandling
-#else
- false
-#endif
- );
-
- // If there are no permissions for PathDiscovery to this path, we should NOT expand the short paths
- // as this would leak information about paths to which the user would not have access to.
- if (path.Length > 0
-#if FEATURE_CAS_POLICY
- // Only do the extra logic if we're not in full trust
- && !CodeAccessSecurityEngine.QuickCheckForAllDemands()
-#endif
- )
- {
- try
- {
- // If we were passed in a path with \\?\ we need to remove it as FileIOPermission does not like it.
- string tempPath = RemoveLongPathPrefix(path);
-
- // FileIOPermission cannot handle paths that contain ? or *
- // So we only pass to FileIOPermission the text up to them.
- int pos = 0;
- while (pos < tempPath.Length && (tempPath[pos] != '?' && tempPath[pos] != '*'))
- pos++;
-
- // GetFullPath will Demand that we have the PathDiscovery FileIOPermission and thus throw
- // SecurityException if we don't.
- // While we don't use the result of this call we are using it as a consistent way of
- // doing the security checks.
- if (pos > 0)
- GetFullPath(tempPath.Substring(0, pos));
- }
- catch (SecurityException)
- {
- // If the user did not have permissions to the path, make sure that we don't leak expanded short paths
- // Only re-normalize if the original path had a ~ in it.
- if (path.IndexOf("~", StringComparison.Ordinal) != -1)
- {
- normalizedPath = NormalizePath(path, fullCheck: false, expandShortPaths: false);
- }
- }
- catch (PathTooLongException) { }
- catch (NotSupportedException) { } // Security can throw this on "c:\foo:"
- catch (IOException) { }
- catch (ArgumentException) { } // The normalizePath with fullCheck will throw this for file: and http:
- }
-
- path = normalizedPath;
-
- int root = GetRootLength(path);
- int i = path.Length;
- if (i > root)
- {
- i = path.Length;
- if (i == root) return null;
- while (i > root && path[--i] != DirectorySeparatorChar && path[i] != AltDirectorySeparatorChar);
- return path.Substring(0, i);
- }
- }
- return null;
- }
-
- // Gets the length of the root DirectoryInfo or whatever DirectoryInfo markers
- // are specified for the first part of the DirectoryInfo name.
- //
- internal static int GetRootLength(string path)
- {
- CheckInvalidPathChars(path);
-
-#if !PLATFORM_UNIX && FEATURE_PATHCOMPAT
- if (AppContextSwitches.UseLegacyPathHandling)
- {
- int i = 0;
- int length = path.Length;
-
- if (length >= 1 && (IsDirectorySeparator(path[0])))
- {
- // handles UNC names and directories off current drive's root.
- i = 1;
- if (length >= 2 && (IsDirectorySeparator(path[1])))
- {
- i = 2;
- int n = 2;
- while (i < length && ((path[i] != DirectorySeparatorChar && path[i] != AltDirectorySeparatorChar) || --n > 0)) i++;
- }
- }
- else if (length >= 2 && path[1] == VolumeSeparatorChar)
- {
- // handles A:\foo.
- i = 2;
- if (length >= 3 && (IsDirectorySeparator(path[2]))) i++;
- }
- return i;
- }
- else
-#endif // !PLATFORM_UNIX && FEATURE_PATHCOMPAT
- {
- return PathInternal.GetRootLength(path);
- }
- }
-
- internal static bool IsDirectorySeparator(char c) {
- return (c==DirectorySeparatorChar || c == AltDirectorySeparatorChar);
- }
-
- public static char[] GetInvalidPathChars()
- {
- return (char[]) RealInvalidPathChars.Clone();
- }
-
- public static char[] GetInvalidFileNameChars()
- {
- return (char[]) InvalidFileNameChars.Clone();
- }
-
- // Returns the extension of the given path. The returned value includes the
- // period (".") character of the extension except when you have a terminal period when you get String.Empty, such as ".exe" or
- // ".cpp". The returned value is null if the given path is
- // null or if the given path does not include an extension.
- //
- [Pure]
- public static String GetExtension(String path) {
- if (path==null)
- return null;
-
- CheckInvalidPathChars(path);
- int length = path.Length;
- for (int i = length; --i >= 0;) {
- char ch = path[i];
- if (ch == '.')
- {
- if (i != length - 1)
- return path.Substring(i, length - i);
- else
- return String.Empty;
- }
- if (ch == DirectorySeparatorChar || ch == AltDirectorySeparatorChar || ch == VolumeSeparatorChar)
- break;
- }
- return String.Empty;
- }
-
- // Expands the given path to a fully qualified path. The resulting string
- // consists of a drive letter, a colon, and a root relative path. This
- // function does not verify that the resulting path
- // refers to an existing file or directory on the associated volume.
- [Pure]
- [System.Security.SecuritySafeCritical]
- public static String GetFullPath(String path) {
- String fullPath = GetFullPathInternal(path);
-#if FEATURE_CORECLR
- FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, path, fullPath);
- state.EnsureState();
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, fullPath, false, false);
-#endif
- return fullPath;
- }
-
- [System.Security.SecurityCritical]
- internal static String UnsafeGetFullPath(String path)
- {
- String fullPath = GetFullPathInternal(path);
-#if !FEATURE_CORECLR
- FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, fullPath, false, false);
-#endif
- return fullPath;
- }
-
- // This method is package access to let us quickly get a string name
- // while avoiding a security check. This also serves a slightly
- // different purpose - when we open a file, we need to resolve the
- // path into a fully qualified, non-relative path name. This
- // method does that, finding the current drive &; directory. But
- // as long as we don't return this info to the user, we're good. However,
- // the public GetFullPath does need to do a security check.
- internal static string GetFullPathInternal(string path)
- {
- if (path == null)
- throw new ArgumentNullException("path");
- Contract.EndContractBlock();
-
- string newPath = NormalizePath(path, fullCheck: true);
- return newPath;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- internal unsafe static string NormalizePath(string path, bool fullCheck)
- {
- return NormalizePath(path, fullCheck,
-#if FEATURE_PATHCOMPAT
- AppContextSwitches.BlockLongPaths ? PathInternal.MaxShortPath :
-#endif
- PathInternal.MaxLongPath);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- internal unsafe static string NormalizePath(string path, bool fullCheck, bool expandShortPaths)
- {
- return NormalizePath(path, fullCheck,
-#if FEATURE_PATHCOMPAT
- AppContextSwitches.BlockLongPaths ? PathInternal.MaxShortPath :
-#endif
- PathInternal.MaxLongPath,
- expandShortPaths);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- internal static string NormalizePath(string path, bool fullCheck, int maxPathLength)
- {
- return NormalizePath(path, fullCheck, maxPathLength, expandShortPaths: true);
- }
-
- [System.Security.SecuritySafeCritical]
- internal static string NormalizePath(string path, bool fullCheck, int maxPathLength, bool expandShortPaths)
- {
-#if FEATURE_PATHCOMPAT
- if (AppContextSwitches.UseLegacyPathHandling)
- {
- return LegacyNormalizePath(path, fullCheck, maxPathLength, expandShortPaths);
- }
- else
-#endif // FEATURE_APPCOMPAT
- {
- if (PathInternal.IsExtended(path))
- {
- // We can't really know what is valid for all cases of extended paths.
- //
- // - object names can include other characters as well (':', '/', etc.)
- // - even file objects have different rules (pipe names can contain most characters)
- //
- // As such we will do no further analysis of extended paths to avoid blocking known and unknown
- // scenarios as well as minimizing compat breaks should we block now and need to unblock later.
- return path;
- }
-
- string normalizedPath = null;
-
- if (fullCheck == false)
- {
- // Disabled fullCheck is only called by GetDirectoryName and GetPathRoot.
- // Avoid adding addtional callers and try going direct to lighter weight NormalizeDirectorySeparators.
- normalizedPath = NewNormalizePathLimitedChecks(path, maxPathLength, expandShortPaths);
- }
- else
- {
- normalizedPath = NewNormalizePath(path, maxPathLength, expandShortPaths: true);
- }
-
- if (string.IsNullOrWhiteSpace(normalizedPath))
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
- return normalizedPath;
- }
- }
-
- [System.Security.SecuritySafeCritical]
- private static string NewNormalizePathLimitedChecks(string path, int maxPathLength, bool expandShortPaths)
- {
- string normalized = PathInternal.NormalizeDirectorySeparators(path);
-
- if (PathInternal.IsPathTooLong(normalized) || PathInternal.AreSegmentsTooLong(normalized))
- throw new PathTooLongException();
-
-#if !PLATFORM_UNIX
- if (!PathInternal.IsDevice(normalized) && PathInternal.HasInvalidVolumeSeparator(path))
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
-
- if (expandShortPaths && normalized.IndexOf('~') != -1)
- {
- try
- {
- return LongPathHelper.GetLongPathName(normalized);
- }
- catch
- {
- // Don't care if we can't get the long path- might not exist, etc.
- }
- }
-#endif
-
- return normalized;
- }
-
- /// <summary>
- /// Normalize the path and check for bad characters or other invalid syntax.
- /// </summary>
- [System.Security.SecuritySafeCritical]
- [ResourceExposure(ResourceScope.Machine)]
- [ResourceConsumption(ResourceScope.Machine)]
- private static string NewNormalizePath(string path, int maxPathLength, bool expandShortPaths)
- {
- Contract.Requires(path != null, "path can't be null");
-
- // Embedded null characters are the only invalid character case we want to check up front.
- // This is because the nulls will signal the end of the string to Win32 and therefore have
- // unpredictable results. Other invalid characters we give a chance to be normalized out.
- if (path.IndexOf('\0') != -1)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
-
-#if !PLATFORM_UNIX
- // Note that colon and wildcard checks happen in FileIOPermissions
-
- // Technically this doesn't matter but we used to throw for this case
- if (string.IsNullOrWhiteSpace(path))
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
-
- // We don't want to check invalid characters for device format- see comments for extended above
- return LongPathHelper.Normalize(path, (uint)maxPathLength, checkInvalidCharacters: !PathInternal.IsDevice(path), expandShortPaths: expandShortPaths);
-#else
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
-
- // Expand with current directory if necessary
- if (!IsPathRooted(path))
- path = Combine(Directory.GetCurrentDirectory(), path);
-
- // We would ideally use realpath to do this, but it resolves symlinks, requires that the file actually exist,
- // and turns it into a full path, which we only want if fullCheck is true.
- string collapsedString = PathInternal.RemoveRelativeSegments(path);
-
- if (collapsedString.Length > maxPathLength)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- return collapsedString.Length == 0 ? "/" : collapsedString;
-#endif // PLATFORM_UNIX
- }
-
-#if FEATURE_PATHCOMPAT
- [System.Security.SecurityCritical] // auto-generated
- internal unsafe static String LegacyNormalizePath(String path, bool fullCheck, int maxPathLength, bool expandShortPaths) {
-
- Contract.Requires(path != null, "path can't be null");
- // If we're doing a full path check, trim whitespace and look for
- // illegal path characters.
- if (fullCheck) {
- // Trim whitespace off the end of the string.
- // Win32 normalization trims only U+0020.
- path = path.TrimEnd(TrimEndChars);
-
- // Look for illegal path characters.
- if (PathInternal.AnyPathHasIllegalCharacters(path))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
- }
-
- int index = 0;
- // We prefer to allocate on the stack for workingset/perf gain. If the
- // starting path is less than MaxPath then we can stackalloc; otherwise we'll
- // use a StringBuilder (PathHelper does this under the hood). The latter may
- // happen in 2 cases:
- // 1. Starting path is greater than MaxPath but it normalizes down to MaxPath.
- // This is relevant for paths containing escape sequences. In this case, we
- // attempt to normalize down to MaxPath, but the caller pays a perf penalty
- // since StringBuilder is used.
- // 2. IsolatedStorage, which supports paths longer than MaxPath (value given
- // by maxPathLength.
- PathHelper newBuffer;
- if (path.Length + 1 <= MaxPath) {
- char* m_arrayPtr = stackalloc char[MaxPath];
- newBuffer = new PathHelper(m_arrayPtr, MaxPath);
- } else {
- newBuffer = new PathHelper(path.Length + Path.MaxPath, maxPathLength);
- }
-
- uint numSpaces = 0;
- uint numDots = 0;
- bool fixupDirectorySeparator = false;
- // Number of significant chars other than potentially suppressible
- // dots and spaces since the last directory or volume separator char
- uint numSigChars = 0;
- int lastSigChar = -1; // Index of last significant character.
- // Whether this segment of the path (not the complete path) started
- // with a volume separator char. Reject "c:...".
- bool startedWithVolumeSeparator = false;
- bool firstSegment = true;
- int lastDirectorySeparatorPos = 0;
-
-#if !PLATFORM_UNIX
- bool mightBeShortFileName = false;
-
- // LEGACY: This code is here for backwards compatibility reasons. It
- // ensures that \\foo.cs\bar.cs stays \\foo.cs\bar.cs instead of being
- // turned into \foo.cs\bar.cs.
- if (path.Length > 0 && (path[0] == DirectorySeparatorChar || path[0] == AltDirectorySeparatorChar)) {
- newBuffer.Append('\\');
- index++;
- lastSigChar = 0;
- }
-#endif
-
- // Normalize the string, stripping out redundant dots, spaces, and
- // slashes.
- while (index < path.Length) {
- char currentChar = path[index];
-
- // We handle both directory separators and dots specially. For
- // directory separators, we consume consecutive appearances.
- // For dots, we consume all dots beyond the second in
- // succession. All other characters are added as is. In
- // addition we consume all spaces after the last other char
- // in a directory name up until the directory separator.
-
- if (currentChar == DirectorySeparatorChar || currentChar == AltDirectorySeparatorChar) {
- // If we have a path like "123.../foo", remove the trailing dots.
- // However, if we found "c:\temp\..\bar" or "c:\temp\...\bar", don't.
- // Also remove trailing spaces from both files & directory names.
- // This was agreed on with the OS team to fix undeletable directory
- // names ending in spaces.
-
- // If we saw a '\' as the previous last significant character and
- // are simply going to write out dots, suppress them.
- // If we only contain dots and slashes though, only allow
- // a string like [dot]+ [space]*. Ignore everything else.
- // Legal: "\.. \", "\...\", "\. \"
- // Illegal: "\.. .\", "\. .\", "\ .\"
- if (numSigChars == 0) {
- // Dot and space handling
- if (numDots > 0) {
- // Look for ".[space]*" or "..[space]*"
- int start = lastSigChar + 1;
- if (path[start] != '.')
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
-
- // Only allow "[dot]+[space]*", and normalize the
- // legal ones to "." or ".."
- if (numDots >= 2) {
- // Reject "C:..."
- if (startedWithVolumeSeparator && numDots > 2)
-
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
-
- if (path[start + 1] == '.') {
- // Search for a space in the middle of the
- // dots and throw
- for(int i=start + 2; i < start + numDots; i++) {
- if (path[i] != '.')
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
- }
-
- numDots = 2;
- }
- else {
- if (numDots > 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
- numDots = 1;
- }
- }
-
- if (numDots == 2) {
- newBuffer.Append('.');
- }
-
- newBuffer.Append('.');
- fixupDirectorySeparator = false;
-
- // Continue in this case, potentially writing out '\'.
- }
-
- if (numSpaces > 0 && firstSegment) {
- // Handle strings like " \\server\share".
- if (index + 1 < path.Length &&
- (path[index + 1] == DirectorySeparatorChar || path[index + 1] == AltDirectorySeparatorChar))
- {
- newBuffer.Append(DirectorySeparatorChar);
- }
- }
- }
- numDots = 0;
- numSpaces = 0; // Suppress trailing spaces
-
- if (!fixupDirectorySeparator) {
- fixupDirectorySeparator = true;
- newBuffer.Append(DirectorySeparatorChar);
- }
- numSigChars = 0;
- lastSigChar = index;
- startedWithVolumeSeparator = false;
- firstSegment = false;
-
-#if !PLATFORM_UNIX
- // For short file names, we must try to expand each of them as
- // soon as possible. We need to allow people to specify a file
- // name that doesn't exist using a path with short file names
- // in it, such as this for a temp file we're trying to create:
- // C:\DOCUME~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp
- // We could try doing this afterwards piece by piece, but it's
- // probably a lot simpler to do it here.
- if (mightBeShortFileName) {
- newBuffer.TryExpandShortFileName();
- mightBeShortFileName = false;
- }
-#endif
- int thisPos = newBuffer.Length - 1;
- if (thisPos - lastDirectorySeparatorPos > MaxPathComponentLength)
- {
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
- }
- lastDirectorySeparatorPos = thisPos;
- } // if (Found directory separator)
- else if (currentChar == '.') {
- // Reduce only multiple .'s only after slash to 2 dots. For
- // instance a...b is a valid file name.
- numDots++;
- // Don't flush out non-terminal spaces here, because they may in
- // the end not be significant. Turn "c:\ . .\foo" -> "c:\foo"
- // which is the conclusion of removing trailing dots & spaces,
- // as well as folding multiple '\' characters.
- }
- else if (currentChar == ' ') {
- numSpaces++;
- }
- else { // Normal character logic
-#if !PLATFORM_UNIX
- if (currentChar == '~' && expandShortPaths)
- mightBeShortFileName = true;
-#endif
-
- fixupDirectorySeparator = false;
-
-#if !PLATFORM_UNIX
- // To reject strings like "C:...\foo" and "C :\foo"
- if (firstSegment && currentChar == VolumeSeparatorChar) {
- // Only accept "C:", not "c :" or ":"
- // Get a drive letter or ' ' if index is 0.
- char driveLetter = (index > 0) ? path[index-1] : ' ';
- bool validPath = ((numDots == 0) && (numSigChars >= 1) && (driveLetter != ' '));
- if (!validPath)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
-
- startedWithVolumeSeparator = true;
- // We need special logic to make " c:" work, we should not fix paths like " foo::$DATA"
- if (numSigChars > 1) { // Common case, simply do nothing
- int spaceCount = 0; // How many spaces did we write out, numSpaces has already been reset.
- while((spaceCount < newBuffer.Length) && newBuffer[spaceCount] == ' ')
- spaceCount++;
- if (numSigChars - spaceCount == 1) {
- //Safe to update stack ptr directly
- newBuffer.Length = 0;
- newBuffer.Append(driveLetter); // Overwrite spaces, we need a special case to not break " foo" as a relative path.
- }
- }
- numSigChars = 0;
- }
- else
-#endif // !PLATFORM_UNIX
- {
- numSigChars += 1 + numDots + numSpaces;
- }
-
- // Copy any spaces & dots since the last significant character
- // to here. Note we only counted the number of dots & spaces,
- // and don't know what order they're in. Hence the copy.
- if (numDots > 0 || numSpaces > 0) {
- int numCharsToCopy = (lastSigChar >= 0) ? index - lastSigChar - 1 : index;
- if (numCharsToCopy > 0) {
- for (int i=0; i<numCharsToCopy; i++) {
- newBuffer.Append(path[lastSigChar + 1 + i]);
- }
- }
- numDots = 0;
- numSpaces = 0;
- }
-
- newBuffer.Append(currentChar);
- lastSigChar = index;
- }
-
- index++;
- } // end while
-
- if (newBuffer.Length - 1 - lastDirectorySeparatorPos > MaxPathComponentLength)
- {
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
- }
-
- // Drop any trailing dots and spaces from file & directory names, EXCEPT
- // we MUST make sure that "C:\foo\.." is correctly handled.
- // Also handle "C:\foo\." -> "C:\foo", while "C:\." -> "C:\"
- if (numSigChars == 0) {
- if (numDots > 0) {
- // Look for ".[space]*" or "..[space]*"
- int start = lastSigChar + 1;
- if (path[start] != '.')
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
-
- // Only allow "[dot]+[space]*", and normalize the
- // legal ones to "." or ".."
- if (numDots >= 2) {
- // Reject "C:..."
- if (startedWithVolumeSeparator && numDots > 2)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
-
- if (path[start + 1] == '.') {
- // Search for a space in the middle of the
- // dots and throw
- for(int i=start + 2; i < start + numDots; i++) {
- if (path[i] != '.')
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
- }
-
- numDots = 2;
- }
- else {
- if (numDots > 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
- numDots = 1;
- }
- }
-
- if (numDots == 2) {
- newBuffer.Append('.');
- }
-
- newBuffer.Append('.');
- }
- } // if (numSigChars == 0)
-
- // If we ended up eating all the characters, bail out.
- if (newBuffer.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
-
- // Disallow URL's here. Some of our other Win32 API calls will reject
- // them later, so we might be better off rejecting them here.
- // Note we've probably turned them into "file:\D:\foo.tmp" by now.
- // But for compatibility, ensure that callers that aren't doing a
- // full check aren't rejected here.
- if (fullCheck) {
- if ( newBuffer.OrdinalStartsWith("http:", false) ||
- newBuffer.OrdinalStartsWith("file:", false))
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_PathUriFormatNotSupported"));
- }
- }
-
-#if !PLATFORM_UNIX
- // If the last part of the path (file or directory name) had a tilde,
- // expand that too.
- if (mightBeShortFileName) {
- newBuffer.TryExpandShortFileName();
- }
-#endif
-
- // Call the Win32 API to do the final canonicalization step.
- int result = 1;
-
- if (fullCheck) {
- // NOTE: Win32 GetFullPathName requires the input buffer to be big enough to fit the initial
- // path which is a concat of CWD and the relative path, this can be of an arbitrary
- // size and could be > MAX_PATH (which becomes an artificial limit at this point),
- // even though the final normalized path after fixing up the relative path syntax
- // might be well within the MAX_PATH restriction. For ex,
- // "c:\SomeReallyLongDirName(thinkGreaterThan_MAXPATH)\..\foo.txt" which actually requires a
- // buffer well with in the MAX_PATH as the normalized path is just "c:\foo.txt"
- // This buffer requirement seems wrong, it could be a bug or a perf optimization
- // like returning required buffer length quickly or avoid stratch buffer etc.
- // Ideally we would get the required buffer length first by calling GetFullPathName
- // once without the buffer and use that in the later call but this doesn't always work
- // due to Win32 GetFullPathName bug. For instance, in Win2k, when the path we are trying to
- // fully qualify is a single letter name (such as "a", "1", ",") GetFullPathName
- // fails to return the right buffer size (i.e, resulting in insufficient buffer).
- // To workaround this bug we will start with MAX_PATH buffer and grow it once if the
- // return value is > MAX_PATH.
-
- result = newBuffer.GetFullPathName();
-
-#if !PLATFORM_UNIX
- // If we called GetFullPathName with something like "foo" and our
- // command window was in short file name mode (ie, by running edlin or
- // DOS versions of grep, etc), we might have gotten back a short file
- // name. So, check to see if we need to expand it.
- mightBeShortFileName = false;
- for(int i=0; i < newBuffer.Length && !mightBeShortFileName; i++) {
- if (newBuffer[i] == '~' && expandShortPaths)
- mightBeShortFileName = true;
- }
-
- if (mightBeShortFileName) {
- bool r = newBuffer.TryExpandShortFileName();
- // Consider how the path "Doesn'tExist" would expand. If
- // we add in the current directory, it too will need to be
- // fully expanded, which doesn't happen if we use a file
- // name that doesn't exist.
- if (!r) {
- int lastSlash = -1;
-
- for (int i = newBuffer.Length - 1; i >= 0; i--) {
- if (newBuffer[i] == DirectorySeparatorChar) {
- lastSlash = i;
- break;
- }
- }
-
- if (lastSlash >= 0) {
-
- // This bounds check is for safe memcpy but we should never get this far
- if (newBuffer.Length >= maxPathLength)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- int lenSavedName = newBuffer.Length - lastSlash - 1;
- Contract.Assert(lastSlash < newBuffer.Length, "path unexpectedly ended in a '\'");
-
- newBuffer.Fixup(lenSavedName, lastSlash);
- }
- }
- }
-#endif // PLATFORM_UNIX
- }
-
- if (result != 0) {
- /* Throw an ArgumentException for paths like \\, \\server, \\server\
- This check can only be properly done after normalizing, so
- \\foo\.. will be properly rejected. Also, reject \\?\GLOBALROOT\
- (an internal kernel path) because it provides aliases for drives. */
- if (newBuffer.Length > 1 && newBuffer[0] == '\\' && newBuffer[1] == '\\') {
- int startIndex = 2;
- while (startIndex < result) {
- if (newBuffer[startIndex] == '\\') {
- startIndex++;
- break;
- }
- else {
- startIndex++;
- }
- }
- if (startIndex == result)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegalUNC"));
-
- // Check for \\?\Globalroot, an internal mechanism to the kernel
- // that provides aliases for drives and other undocumented stuff.
- // The kernel team won't even describe the full set of what
- // is available here - we don't want managed apps mucking
- // with this for security reasons.
- if ( newBuffer.OrdinalStartsWith("\\\\?\\globalroot", true))
- throw new ArgumentException(Environment.GetResourceString("Arg_PathGlobalRoot"));
- }
- }
-
- // Check our result and form the managed string as necessary.
- if (newBuffer.Length >= maxPathLength)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- if (result == 0) {
- int errorCode = Marshal.GetLastWin32Error();
- if (errorCode == 0)
- errorCode = Win32Native.ERROR_BAD_PATHNAME;
- __Error.WinIOError(errorCode, path);
- return null; // Unreachable - silence a compiler error.
- }
-
- return newBuffer.ToStringOrExisting(path);
- }
-#endif // FEATURE_PATHCOMPAT
-
- internal const int MaxLongPath = PathInternal.MaxLongPath;
-
- private const string LongPathPrefix = PathInternal.ExtendedPathPrefix;
- private const string UNCPathPrefix = PathInternal.UncPathPrefix;
- private const string UNCLongPathPrefixToInsert = PathInternal.UncExtendedPrefixToInsert;
- private const string UNCLongPathPrefix = PathInternal.UncExtendedPathPrefix;
-
- internal static bool HasLongPathPrefix(string path)
- {
-#if FEATURE_PATHCOMPAT
- if (AppContextSwitches.UseLegacyPathHandling)
- return path.StartsWith(LongPathPrefix, StringComparison.Ordinal);
- else
-#endif
- return PathInternal.IsExtended(path);
- }
-
- internal static string AddLongPathPrefix(string path)
- {
-#if FEATURE_PATHCOMPAT
- if (AppContextSwitches.UseLegacyPathHandling)
- {
- if (path.StartsWith(LongPathPrefix, StringComparison.Ordinal))
- return path;
-
- if (path.StartsWith(UNCPathPrefix, StringComparison.Ordinal))
- return path.Insert(2, UNCLongPathPrefixToInsert); // Given \\server\share in longpath becomes \\?\UNC\server\share => UNCLongPathPrefix + path.SubString(2); => The actual command simply reduces the operation cost.
-
- return LongPathPrefix + path;
- }
- else
-#endif
- {
- return PathInternal.EnsureExtendedPrefix(path);
- }
- }
-
- internal static string RemoveLongPathPrefix(string path)
- {
-#if FEATURE_PATHCOMPAT
- if (AppContextSwitches.UseLegacyPathHandling)
- {
- if (!path.StartsWith(LongPathPrefix, StringComparison.Ordinal))
- return path;
-
- if (path.StartsWith(UNCLongPathPrefix, StringComparison.OrdinalIgnoreCase))
- return path.Remove(2, 6); // Given \\?\UNC\server\share we return \\server\share => @'\\' + path.SubString(UNCLongPathPrefix.Length) => The actual command simply reduces the operation cost.
-
- return path.Substring(4);
- }
- else
-#endif
- {
- return PathInternal.RemoveExtendedPrefix(path);
- }
- }
-
- internal static StringBuilder RemoveLongPathPrefix(StringBuilder pathSB)
- {
-#if FEATURE_PATHCOMPAT
- if (AppContextSwitches.UseLegacyPathHandling)
- {
- if (!PathInternal.StartsWithOrdinal(pathSB, LongPathPrefix))
- return pathSB;
-
- // Given \\?\UNC\server\share we return \\server\share => @'\\' + path.SubString(UNCLongPathPrefix.Length) => The actual command simply reduces the operation cost.
- if (PathInternal.StartsWithOrdinal(pathSB, UNCLongPathPrefix, ignoreCase: true))
- return pathSB.Remove(2, 6);
-
- return pathSB.Remove(0, 4);
- }
- else
-#endif
- {
- return PathInternal.RemoveExtendedPrefix(pathSB);
- }
- }
-
-
- // Returns the name and extension parts of the given path. The resulting
- // string contains the characters of path that follow the last
- // backslash ("\"), slash ("/"), or colon (":") character in
- // path. The resulting string is the entire path if path
- // contains no backslash after removing trailing slashes, slash, or colon characters. The resulting
- // string is null if path is null.
- //
- [Pure]
- public static String GetFileName(String path) {
- if (path != null) {
- CheckInvalidPathChars(path);
-
- int length = path.Length;
- for (int i = length; --i >= 0;) {
- char ch = path[i];
- if (ch == DirectorySeparatorChar || ch == AltDirectorySeparatorChar || ch == VolumeSeparatorChar)
- return path.Substring(i + 1, length - i - 1);
-
- }
- }
- return path;
- }
-
- [Pure]
- public static String GetFileNameWithoutExtension(String path) {
- path = GetFileName(path);
- if (path != null)
- {
- int i;
- if ((i=path.LastIndexOf('.')) == -1)
- return path; // No path extension found
- else
- return path.Substring(0,i);
- }
- return null;
- }
-
-
-
- // Returns the root portion of the given path. The resulting string
- // consists of those rightmost characters of the path that constitute the
- // root of the path. Possible patterns for the resulting string are: An
- // empty string (a relative path on the current drive), "\" (an absolute
- // path on the current drive), "X:" (a relative path on a given drive,
- // where X is the drive letter), "X:\" (an absolute path on a given drive),
- // and "\\server\share" (a UNC path for a given server and share name).
- // The resulting string is null if path is null.
- //
- [Pure]
- public static String GetPathRoot(String path) {
- if (path == null) return null;
-
- // Expanding short paths has no impact on the path root- there is no such thing as an
- // 8.3 volume or server/share name.
- path = NormalizePath(path, fullCheck: false, expandShortPaths: false);
- return path.Substring(0, GetRootLength(path));
- }
-
- [System.Security.SecuritySafeCritical]
- public static String GetTempPath()
- {
-#if !FEATURE_CORECLR
- new EnvironmentPermission(PermissionState.Unrestricted).Demand();
-#endif
- StringBuilder sb = new StringBuilder(PathInternal.MaxShortPath);
- uint r = Win32Native.GetTempPath(PathInternal.MaxShortPath, sb);
- String path = sb.ToString();
- if (r==0) __Error.WinIOError();
- path = GetFullPathInternal(path);
-#if FEATURE_CORECLR
- FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, String.Empty, path);
- state.EnsureState();
-#endif
- return path;
- }
-
- internal static bool IsRelative(string path)
- {
- Contract.Assert(path != null, "path can't be null");
- return PathInternal.IsPartiallyQualified(path);
- }
-
- // Returns a cryptographically strong random 8.3 string that can be
- // used as either a folder name or a file name.
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
- public static String GetRandomFileName()
- {
- // 5 bytes == 40 bits == 40/5 == 8 chars in our encoding
- // This gives us exactly 8 chars. We want to avoid the 8.3 short name issue
- byte[] key = new byte[10];
-
-#if FEATURE_CORECLR
- Win32Native.Random(true, key, key.Length);
-#else
- // RNGCryptoServiceProvider is disposable in post-Orcas desktop mscorlibs, but not in CoreCLR's
- // mscorlib, so we need to do a manual using block for it.
- RNGCryptoServiceProvider rng = null;
- try
- {
- rng = new RNGCryptoServiceProvider();
-
- rng.GetBytes(key);
- }
- finally
- {
- if (rng != null)
- {
- rng.Dispose();
- }
- }
-#endif
-
- // rndCharArray is expected to be 16 chars
- char[] rndCharArray = Path.ToBase32StringSuitableForDirName(key).ToCharArray();
- rndCharArray[8] = '.';
- return new String(rndCharArray, 0, 12);
- }
-
- // Returns a unique temporary file name, and creates a 0-byte file by that
- // name on disk.
- [System.Security.SecuritySafeCritical]
- public static String GetTempFileName()
- {
- return InternalGetTempFileName(true);
- }
-
- [System.Security.SecurityCritical]
- internal static String UnsafeGetTempFileName()
- {
- return InternalGetTempFileName(false);
- }
-
- [System.Security.SecurityCritical]
- private static String InternalGetTempFileName(bool checkHost)
- {
- String path = GetTempPath();
-
- // Since this can write to the temp directory and theoretically
- // cause a denial of service attack, demand FileIOPermission to
- // that directory.
-
-#if FEATURE_CORECLR
- if (checkHost)
- {
- FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, String.Empty, path);
- state.EnsureState();
- }
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, path);
-#endif
- StringBuilder sb = new StringBuilder(MaxPath);
- uint r = Win32Native.GetTempFileName(path, "tmp", 0, sb);
- if (r==0) __Error.WinIOError();
- return sb.ToString();
- }
-
- // Tests if a path includes a file extension. The result is
- // true if the characters that follow the last directory
- // separator ('\\' or '/') or volume separator (':') in the path include
- // a period (".") other than a terminal period. The result is false otherwise.
- //
- [Pure]
- public static bool HasExtension(String path) {
- if (path != null) {
- CheckInvalidPathChars(path);
-
- for (int i = path.Length; --i >= 0;) {
- char ch = path[i];
- if (ch == '.') {
- if ( i != path.Length - 1)
- return true;
- else
- return false;
- }
- if (ch == DirectorySeparatorChar || ch == AltDirectorySeparatorChar || ch == VolumeSeparatorChar) break;
- }
- }
- return false;
- }
-
- // Tests if the given path contains a root. A path is considered rooted
- // if it starts with a backslash ("\") or a drive letter and a colon (":").
- //
- [Pure]
- public static bool IsPathRooted(String path) {
- if (path != null) {
- CheckInvalidPathChars(path);
-
- int length = path.Length;
-#if !PLATFORM_UNIX
- if ((length >= 1 && (path[0] == DirectorySeparatorChar || path[0] == AltDirectorySeparatorChar)) || (length >= 2 && path[1] == VolumeSeparatorChar))
- return true;
-#else
- if (length >= 1 && (path[0] == DirectorySeparatorChar || path[0] == AltDirectorySeparatorChar))
- return true;
-#endif
- }
- return false;
- }
-
- public static String Combine(String path1, String path2) {
- if (path1==null || path2==null)
- throw new ArgumentNullException((path1==null) ? "path1" : "path2");
- Contract.EndContractBlock();
- CheckInvalidPathChars(path1);
- CheckInvalidPathChars(path2);
-
- return CombineNoChecks(path1, path2);
- }
-
- public static String Combine(String path1, String path2, String path3) {
- if (path1 == null || path2 == null || path3 == null)
- throw new ArgumentNullException((path1 == null) ? "path1" : (path2 == null) ? "path2" : "path3");
- Contract.EndContractBlock();
- CheckInvalidPathChars(path1);
- CheckInvalidPathChars(path2);
- CheckInvalidPathChars(path3);
-
- return CombineNoChecks(CombineNoChecks(path1, path2), path3);
- }
-
- public static String Combine(String path1, String path2, String path3, String path4) {
- if (path1 == null || path2 == null || path3 == null || path4 == null)
- throw new ArgumentNullException((path1 == null) ? "path1" : (path2 == null) ? "path2" : (path3 == null) ? "path3" : "path4");
- Contract.EndContractBlock();
- CheckInvalidPathChars(path1);
- CheckInvalidPathChars(path2);
- CheckInvalidPathChars(path3);
- CheckInvalidPathChars(path4);
-
- return CombineNoChecks(CombineNoChecks(CombineNoChecks(path1, path2), path3), path4);
- }
-
- public static String Combine(params String[] paths) {
- if (paths == null) {
- throw new ArgumentNullException("paths");
- }
- Contract.EndContractBlock();
-
- int finalSize = 0;
- int firstComponent = 0;
-
- // We have two passes, the first calcuates how large a buffer to allocate and does some precondition
- // checks on the paths passed in. The second actually does the combination.
-
- for (int i = 0; i < paths.Length; i++) {
- if (paths[i] == null) {
- throw new ArgumentNullException("paths");
- }
-
- if (paths[i].Length == 0) {
- continue;
- }
-
- CheckInvalidPathChars(paths[i]);
-
- if (Path.IsPathRooted(paths[i])) {
- firstComponent = i;
- finalSize = paths[i].Length;
- } else {
- finalSize += paths[i].Length;
- }
-
- char ch = paths[i][paths[i].Length - 1];
- if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar && ch != VolumeSeparatorChar)
- finalSize++;
- }
-
- StringBuilder finalPath = StringBuilderCache.Acquire(finalSize);
-
- for (int i = firstComponent; i < paths.Length; i++) {
- if (paths[i].Length == 0) {
- continue;
- }
-
- if (finalPath.Length == 0) {
- finalPath.Append(paths[i]);
- } else {
- char ch = finalPath[finalPath.Length - 1];
- if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar && ch != VolumeSeparatorChar) {
- finalPath.Append(DirectorySeparatorChar);
- }
-
- finalPath.Append(paths[i]);
- }
- }
-
- return StringBuilderCache.GetStringAndRelease(finalPath);
- }
-
- private static String CombineNoChecks(String path1, String path2) {
- if (path2.Length == 0)
- return path1;
-
- if (path1.Length == 0)
- return path2;
-
- if (IsPathRooted(path2))
- return path2;
-
- char ch = path1[path1.Length - 1];
- if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar && ch != VolumeSeparatorChar)
- return path1 + DirectorySeparatorCharAsString + path2;
- return path1 + path2;
- }
-
- private static readonly Char[] s_Base32Char = {
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
- 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
- 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
- 'y', 'z', '0', '1', '2', '3', '4', '5'};
-
- internal static String ToBase32StringSuitableForDirName(byte[] buff)
- {
- // This routine is optimised to be used with buffs of length 20
- Contract.Assert(((buff.Length % 5) == 0), "Unexpected hash length");
-
- StringBuilder sb = StringBuilderCache.Acquire();
- byte b0, b1, b2, b3, b4;
- int l, i;
-
- l = buff.Length;
- i = 0;
-
- // Create l chars using the last 5 bits of each byte.
- // Consume 3 MSB bits 5 bytes at a time.
-
- do
- {
- b0 = (i < l) ? buff[i++] : (byte)0;
- b1 = (i < l) ? buff[i++] : (byte)0;
- b2 = (i < l) ? buff[i++] : (byte)0;
- b3 = (i < l) ? buff[i++] : (byte)0;
- b4 = (i < l) ? buff[i++] : (byte)0;
-
- // Consume the 5 Least significant bits of each byte
- sb.Append(s_Base32Char[b0 & 0x1F]);
- sb.Append(s_Base32Char[b1 & 0x1F]);
- sb.Append(s_Base32Char[b2 & 0x1F]);
- sb.Append(s_Base32Char[b3 & 0x1F]);
- sb.Append(s_Base32Char[b4 & 0x1F]);
-
- // Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4
- sb.Append(s_Base32Char[(
- ((b0 & 0xE0) >> 5) |
- ((b3 & 0x60) >> 2))]);
-
- sb.Append(s_Base32Char[(
- ((b1 & 0xE0) >> 5) |
- ((b4 & 0x60) >> 2))]);
-
- // Consume 3 MSB bits of b2, 1 MSB bit of b3, b4
-
- b2 >>= 5;
-
- Contract.Assert(((b2 & 0xF8) == 0), "Unexpected set bits");
-
- if ((b3 & 0x80) != 0)
- b2 |= 0x08;
- if ((b4 & 0x80) != 0)
- b2 |= 0x10;
-
- sb.Append(s_Base32Char[b2]);
-
- } while (i < l);
-
- return StringBuilderCache.GetStringAndRelease(sb);
- }
-
- // ".." can only be used if it is specified as a part of a valid File/Directory name. We disallow
- // the user being able to use it to move up directories. Here are some examples eg
- // Valid: a..b abc..d
- // Invalid: ..ab ab.. .. abc..d\abc..
- //
- internal static void CheckSearchPattern(String searchPattern)
- {
- int index;
- while ((index = searchPattern.IndexOf("..", StringComparison.Ordinal)) != -1) {
-
- if (index + 2 == searchPattern.Length) // Terminal ".." . Files names cannot end in ".."
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidSearchPattern"));
-
- if ((searchPattern[index+2] == DirectorySeparatorChar)
- || (searchPattern[index+2] == AltDirectorySeparatorChar))
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidSearchPattern"));
-
- searchPattern = searchPattern.Substring(index + 2);
- }
-
- }
-
- internal static void CheckInvalidPathChars(String path, bool checkAdditional = false)
- {
- if (path == null)
- throw new ArgumentNullException("path");
-
- if (PathInternal.HasIllegalCharacters(path, checkAdditional))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
- }
-
- internal static String InternalCombine(String path1, String path2) {
- if (path1==null || path2==null)
- throw new ArgumentNullException((path1==null) ? "path1" : "path2");
- Contract.EndContractBlock();
- CheckInvalidPathChars(path1);
- CheckInvalidPathChars(path2);
-
- if (path2.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"), "path2");
- if (IsPathRooted(path2))
- throw new ArgumentException(Environment.GetResourceString("Arg_Path2IsRooted"), "path2");
- int i = path1.Length;
- if (i == 0) return path2;
- char ch = path1[i - 1];
- if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar && ch != VolumeSeparatorChar)
- return path1 + DirectorySeparatorCharAsString + path2;
- return path1 + path2;
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/IO/PathHelper.cs b/src/mscorlib/src/System/IO/PathHelper.cs
deleted file mode 100644
index 8e39b3c537..0000000000
--- a/src/mscorlib/src/System/IO/PathHelper.cs
+++ /dev/null
@@ -1,448 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-#if FEATURE_PATHCOMPAT
-using System;
-using System.Collections;
-using System.Text;
-using Microsoft.Win32;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Globalization;
-using System.Runtime.Versioning;
-using System.Security;
-using System.Security.Permissions;
-using System.Diagnostics.Contracts;
-
-namespace System.IO {
-
- // ABOUT:
- // Helps with path normalization; support allocating on the stack or heap
- //
- // PathHelper can't stackalloc the array for obvious reasons; you must pass
- // in an array of chars allocated on the stack.
- //
- // USAGE:
- // Suppose you need to represent a char array of length len. Then this is the
- // suggested way to instantiate PathHelper:
- // ***************************************************************************
- // PathHelper pathHelper;
- // if (charArrayLength less than stack alloc threshold == Path.MaxPath)
- // char* arrayPtr = stackalloc char[Path.MaxPath];
- // pathHelper = new PathHelper(arrayPtr);
- // else
- // pathHelper = new PathHelper(capacity, maxPath);
- // ***************************************************************************
- //
- // note in the StringBuilder ctor:
- // - maxPath may be greater than Path.MaxPath (for isolated storage)
- // - capacity may be greater than maxPath. This is even used for non-isolated
- // storage scenarios where we want to temporarily allow strings greater
- // than Path.MaxPath if they can be normalized down to Path.MaxPath. This
- // can happen if the path contains escape characters "..".
- //
- unsafe internal struct PathHelper { // should not be serialized
-
- // maximum size, max be greater than max path if contains escape sequence
- private int m_capacity;
- // current length (next character position)
- private int m_length;
- // max path, may be less than capacity
- private int m_maxPath;
-
- // ptr to stack alloc'd array of chars
- [SecurityCritical]
- private char* m_arrayPtr;
-
- // StringBuilder
- private StringBuilder m_sb;
-
- // whether to operate on stack alloc'd or heap alloc'd array
- private bool useStackAlloc;
-
- // Whether to skip calls to Win32Native.GetLongPathName becasue we tried before and failed:
- private bool doNotTryExpandShortFileName;
-
- // Instantiates a PathHelper with a stack alloc'd array of chars
- [System.Security.SecurityCritical]
- internal PathHelper(char* charArrayPtr, int length) {
- Contract.Requires(charArrayPtr != null);
- // force callers to be aware of this
- Contract.Requires(length == Path.MaxPath);
- this.m_length = 0;
- this.m_sb = null;
-
- this.m_arrayPtr = charArrayPtr;
- this.m_capacity = length;
- this.m_maxPath = Path.MaxPath;
- useStackAlloc = true;
- doNotTryExpandShortFileName = false;
- }
-
- // Instantiates a PathHelper with a heap alloc'd array of ints. Will create a StringBuilder
- [System.Security.SecurityCritical]
- internal PathHelper(int capacity, int maxPath)
- {
- this.m_length = 0;
- this.m_arrayPtr = null;
- this.useStackAlloc = false;
-
- this.m_sb = new StringBuilder(capacity);
- this.m_capacity = capacity;
- this.m_maxPath = maxPath;
- doNotTryExpandShortFileName = false;
- }
-
- internal int Length {
- get {
- if (useStackAlloc) {
- return m_length;
- }
- else {
- return m_sb.Length;
- }
- }
- set {
- if (useStackAlloc) {
- m_length = value;
- }
- else {
- m_sb.Length = value;
- }
- }
- }
-
- internal int Capacity {
- get {
- return m_capacity;
- }
- }
-
- internal char this[int index] {
- [System.Security.SecurityCritical]
- get {
- Contract.Requires(index >= 0 && index < Length);
- if (useStackAlloc) {
- return m_arrayPtr[index];
- }
- else {
- return m_sb[index];
- }
- }
- [System.Security.SecurityCritical]
- set {
- Contract.Requires(index >= 0 && index < Length);
- if (useStackAlloc) {
- m_arrayPtr[index] = value;
- }
- else {
- m_sb[index] = value;
- }
- }
- }
-
- [System.Security.SecurityCritical]
- internal unsafe void Append(char value) {
- if (Length + 1 >= m_capacity)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- if (useStackAlloc) {
- m_arrayPtr[Length] = value;
- m_length++;
- }
- else {
- m_sb.Append(value);
- }
- }
-
- [System.Security.SecurityCritical]
- internal unsafe int GetFullPathName() {
- if (useStackAlloc) {
- char* finalBuffer = stackalloc char[Path.MaxPath + 1];
- int result = Win32Native.GetFullPathName(m_arrayPtr, Path.MaxPath + 1, finalBuffer, IntPtr.Zero);
-
- // If success, the return buffer length does not account for the terminating null character.
- // If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
- // If failure, the return buffer length is zero
- if (result > Path.MaxPath) {
- char* tempBuffer = stackalloc char[result];
- finalBuffer = tempBuffer;
- result = Win32Native.GetFullPathName(m_arrayPtr, result, finalBuffer, IntPtr.Zero);
- }
-
- // Full path is genuinely long
- if (result >= Path.MaxPath)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- Contract.Assert(result < Path.MaxPath, "did we accidently remove a PathTooLongException check?");
- if (result == 0 && m_arrayPtr[0] != '\0') {
- __Error.WinIOError();
- }
-
- else if (result < Path.MaxPath) {
- // Null terminate explicitly (may be only needed for some cases such as empty strings)
- // GetFullPathName return length doesn't account for null terminating char...
- finalBuffer[result] = '\0'; // Safe to write directly as result is < Path.MaxPath
- }
-
- // We have expanded the paths and GetLongPathName may or may not behave differently from before.
- // We need to call it again to see:
- doNotTryExpandShortFileName = false;
-
- String.wstrcpy(m_arrayPtr, finalBuffer, result);
- // Doesn't account for null terminating char. Think of this as the last
- // valid index into the buffer but not the length of the buffer
- Length = result;
- return result;
- }
- else {
- StringBuilder finalBuffer = new StringBuilder(m_capacity + 1);
- int result = Win32Native.GetFullPathName(m_sb.ToString(), m_capacity + 1, finalBuffer, IntPtr.Zero);
-
- // If success, the return buffer length does not account for the terminating null character.
- // If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
- // If failure, the return buffer length is zero
- if (result > m_maxPath) {
- finalBuffer.Length = result;
- result = Win32Native.GetFullPathName(m_sb.ToString(), result, finalBuffer, IntPtr.Zero);
- }
-
- // Fullpath is genuinely long
- if (result >= m_maxPath)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- Contract.Assert(result < m_maxPath, "did we accidentally remove a PathTooLongException check?");
- if (result == 0 && m_sb[0] != '\0') {
- if (Length >= m_maxPath) {
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
- }
- __Error.WinIOError();
- }
-
- // We have expanded the paths and GetLongPathName may or may not behave differently from before.
- // We need to call it again to see:
- doNotTryExpandShortFileName = false;
-
- m_sb = finalBuffer;
- return result;
- }
- }
-
- [System.Security.SecurityCritical]
- internal unsafe bool TryExpandShortFileName() {
-
- if (doNotTryExpandShortFileName)
- return false;
-
- if (useStackAlloc) {
- NullTerminate();
- char* buffer = UnsafeGetArrayPtr();
- char* shortFileNameBuffer = stackalloc char[Path.MaxPath + 1];
-
- int r = Win32Native.GetLongPathName(buffer, shortFileNameBuffer, Path.MaxPath);
-
- // If success, the return buffer length does not account for the terminating null character.
- // If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
- // If failure, the return buffer length is zero
- if (r >= Path.MaxPath)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- if (r == 0) {
- // Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a
- // path like \\.\PHYSICALDEVICE0 - some device driver doesn't
- // support GetLongPathName on that string. This behavior is
- // by design, according to the Core File Services team.
- // We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs
- // intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\
-
- // We do not need to call GetLongPathName if we know it will fail becasue the path does not exist:
- int lastErr = Marshal.GetLastWin32Error();
- if (lastErr == Win32Native.ERROR_FILE_NOT_FOUND || lastErr == Win32Native.ERROR_PATH_NOT_FOUND)
- doNotTryExpandShortFileName = true;
-
- return false;
- }
-
- // Safe to copy as we have already done Path.MaxPath bound checking
- String.wstrcpy(buffer, shortFileNameBuffer, r);
- Length = r;
- // We should explicitly null terminate as in some cases the long version of the path
- // might actually be shorter than what we started with because of Win32's normalization
- // Safe to write directly as bufferLength is guaranteed to be < Path.MaxPath
- NullTerminate();
- return true;
- }
- else {
- StringBuilder sb = GetStringBuilder();
-
- String origName = sb.ToString();
- String tempName = origName;
- bool addedPrefix = false;
- if (tempName.Length > Path.MaxPath) {
- tempName = Path.AddLongPathPrefix(tempName);
- addedPrefix = true;
- }
- sb.Capacity = m_capacity;
- sb.Length = 0;
- int r = Win32Native.GetLongPathName(tempName, sb, m_capacity);
-
- if (r == 0) {
- // Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a
- // path like \\.\PHYSICALDEVICE0 - some device driver doesn't
- // support GetLongPathName on that string. This behavior is
- // by design, according to the Core File Services team.
- // We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs
- // intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\
-
- // We do not need to call GetLongPathName if we know it will fail becasue the path does not exist:
- int lastErr = Marshal.GetLastWin32Error();
- if (Win32Native.ERROR_FILE_NOT_FOUND == lastErr || Win32Native.ERROR_PATH_NOT_FOUND == lastErr)
- doNotTryExpandShortFileName = true;
-
- sb.Length = 0;
- sb.Append(origName);
- return false;
- }
-
- if (addedPrefix)
- r -= 4;
-
- // If success, the return buffer length does not account for the terminating null character.
- // If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
- // If failure, the return buffer length is zero
- if (r >= m_maxPath)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
-
- sb = Path.RemoveLongPathPrefix(sb);
- Length = sb.Length;
- return true;
-
- }
- }
-
- [System.Security.SecurityCritical]
- internal unsafe void Fixup(int lenSavedName, int lastSlash) {
- if (useStackAlloc) {
- char* savedName = stackalloc char[lenSavedName];
- String.wstrcpy(savedName, m_arrayPtr + lastSlash + 1, lenSavedName);
- Length = lastSlash;
- NullTerminate();
- doNotTryExpandShortFileName = false;
- bool r = TryExpandShortFileName();
- // Clean up changes made to the newBuffer.
- Append(Path.DirectorySeparatorChar);
- if (Length + lenSavedName >= Path.MaxPath)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
- String.wstrcpy(m_arrayPtr + Length, savedName, lenSavedName);
- Length = Length + lenSavedName;
-
- }
- else {
- String savedName = m_sb.ToString(lastSlash + 1, lenSavedName);
- Length = lastSlash;
- doNotTryExpandShortFileName = false;
- bool r = TryExpandShortFileName();
- // Clean up changes made to the newBuffer.
- Append(Path.DirectorySeparatorChar);
- if (Length + lenSavedName >= m_maxPath)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
- m_sb.Append(savedName);
- }
- }
-
- [System.Security.SecurityCritical]
- internal unsafe bool OrdinalStartsWith(String compareTo, bool ignoreCase) {
- if (Length < compareTo.Length)
- return false;
-
- if (useStackAlloc) {
- NullTerminate();
- if (ignoreCase) {
- String s = new String(m_arrayPtr, 0, compareTo.Length);
- return compareTo.Equals(s, StringComparison.OrdinalIgnoreCase);
- }
- else {
- for (int i = 0; i < compareTo.Length; i++) {
- if (m_arrayPtr[i] != compareTo[i]) {
- return false;
- }
- }
- return true;
- }
- }
- else {
- if (ignoreCase) {
- return m_sb.ToString().StartsWith(compareTo, StringComparison.OrdinalIgnoreCase);
- }
- else {
- return m_sb.ToString().StartsWith(compareTo, StringComparison.Ordinal);
- }
- }
- }
-
- [System.Security.SecurityCritical]
- private unsafe bool OrdinalEqualsStackAlloc(String compareTo)
- {
- Contract.Requires(useStackAlloc, "Currently no efficient implementation for StringBuilder.OrdinalEquals(String)");
-
- if (Length != compareTo.Length) {
- return false;
- }
-
- for (int i = 0; i < compareTo.Length; i++) {
- if (m_arrayPtr[i] != compareTo[i]) {
- return false;
- }
- }
-
- return true;
- }
-
- [System.Security.SecuritySafeCritical]
- public override String ToString() {
- if (useStackAlloc) {
- return new String(m_arrayPtr, 0, Length);
- }
- else {
- return m_sb.ToString();
- }
- }
-
- [System.Security.SecuritySafeCritical]
- internal String ToStringOrExisting(String existingString)
- {
- if (useStackAlloc) {
- return OrdinalEqualsStackAlloc(existingString) ?
- existingString :
- new String(m_arrayPtr, 0, Length);
- }
- else {
- string newString = m_sb.ToString(); // currently no good StringBuilder.OrdinalEquals(string)
- return String.Equals(newString, existingString, StringComparison.Ordinal) ?
- existingString :
- newString;
- }
- }
-
- [System.Security.SecurityCritical]
- private unsafe char* UnsafeGetArrayPtr() {
- Contract.Requires(useStackAlloc, "This should never be called for PathHelpers wrapping a StringBuilder");
- return m_arrayPtr;
- }
-
- private StringBuilder GetStringBuilder() {
- Contract.Requires(!useStackAlloc, "This should never be called for PathHelpers that wrap a stackalloc'd buffer");
- return m_sb;
- }
-
- [System.Security.SecurityCritical]
- private unsafe void NullTerminate() {
- Contract.Requires(useStackAlloc, "This should never be called for PathHelpers wrapping a StringBuilder");
- m_arrayPtr[m_length] = '\0';
- }
-
- }
-}
-#endif // FEATURE_PATHCOMPAT \ No newline at end of file
diff --git a/src/mscorlib/src/System/IO/PathInternal.cs b/src/mscorlib/src/System/IO/PathInternal.cs
deleted file mode 100644
index 3970e2264a..0000000000
--- a/src/mscorlib/src/System/IO/PathInternal.cs
+++ /dev/null
@@ -1,806 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using Microsoft.Win32;
-using System;
-using System.Diagnostics.Contracts;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Security;
-using System.Text;
-
-namespace System.IO
-{
- /// <summary>Contains internal path helpers that are shared between many projects.</summary>
- internal static class PathInternal
- {
- internal const string ExtendedPathPrefix = @"\\?\";
- internal const string UncPathPrefix = @"\\";
- internal const string UncExtendedPrefixToInsert = @"?\UNC\";
- internal const string UncExtendedPathPrefix = @"\\?\UNC\";
- internal const string DevicePathPrefix = @"\\.\";
- // \\?\, \\.\, \??\
- internal const int DevicePrefixLength = 4;
- // \\
- internal const int UncPrefixLength = 2;
- // \\?\UNC\, \\.\UNC\
- internal const int UncExtendedPrefixLength = 8;
-#if !PLATFORM_UNIX
- internal const int MaxShortPath = 260;
- internal const int MaxShortDirectoryPath = 248;
-#else
- internal const int MaxShortPath = 1024;
- internal const int MaxShortDirectoryPath = MaxShortPath;
-#endif
-
- // Windows is limited in long paths by the max size of its internal representation of a unicode string.
- // UNICODE_STRING has a max length of USHORT in _bytes_ without a trailing null.
- // https://msdn.microsoft.com/en-us/library/windows/hardware/ff564879.aspx
- internal const int MaxLongPath = short.MaxValue;
- internal static readonly int MaxComponentLength = 255;
-
-#if !PLATFORM_UNIX
- internal static readonly char[] InvalidPathChars =
- {
- '\"', '<', '>', '|', '\0',
- (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
- (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
- (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
- (char)31
- };
-#else
- internal static readonly char[] InvalidPathChars = { '\0' };
-#endif
-
-
- /// <summary>
- /// Validates volume separator only occurs as C: or \\?\C:. This logic is meant to filter out Alternate Data Streams.
- /// </summary>
- /// <returns>True if the path has an invalid volume separator.</returns>
- internal static bool HasInvalidVolumeSeparator(string path)
- {
- // Toss out paths with colons that aren't a valid drive specifier.
- // Cannot start with a colon and can only be of the form "C:" or "\\?\C:".
- // (Note that we used to explicitly check "http:" and "file:"- these are caught by this check now.)
-
- // We don't care about skipping starting space for extended paths. Assume no knowledge of extended paths if we're forcing old path behavior.
- bool isExtended =
-#if FEATURE_PATHCOMPAT
- !AppContextSwitches.UseLegacyPathHandling &&
-#endif
- IsExtended(path);
- int startIndex = isExtended ? ExtendedPathPrefix.Length : PathStartSkip(path);
-
- // If we start with a colon
- if ((path.Length > startIndex && path[startIndex] == Path.VolumeSeparatorChar)
- // Or have an invalid drive letter and colon
- || (path.Length >= startIndex + 2 && path[startIndex + 1] == Path.VolumeSeparatorChar && !IsValidDriveChar(path[startIndex]))
- // Or have any colons beyond the drive colon
- || (path.Length > startIndex + 2 && path.IndexOf(Path.VolumeSeparatorChar, startIndex + 2) != -1))
- {
- return true;
- }
-
- return false;
- }
-
- /// <summary>
- /// Returns true if the given StringBuilder starts with the given value.
- /// </summary>
- /// <param name="value">The string to compare against the start of the StringBuilder.</param>
- internal static bool StartsWithOrdinal(StringBuilder builder, string value, bool ignoreCase = false)
- {
- if (value == null || builder.Length < value.Length)
- return false;
-
- if (ignoreCase)
- {
- for (int i = 0; i < value.Length; i++)
- if (char.ToUpperInvariant(builder[i]) != char.ToUpperInvariant(value[i])) return false;
- }
- else
- {
- for (int i = 0; i < value.Length; i++)
- if (builder[i] != value[i]) return false;
- }
-
- return true;
- }
-
- /// <summary>
- /// Returns true if the given character is a valid drive letter
- /// </summary>
- internal static bool IsValidDriveChar(char value)
- {
- return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z'));
- }
-
- /// <summary>
- /// Returns true if the path is too long
- /// </summary>
- internal static bool IsPathTooLong(string fullPath)
- {
- // We'll never know precisely what will fail as paths get changed internally in Windows and
- // may grow beyond / shrink below exceed MaxLongPath.
-#if FEATURE_PATHCOMPAT
- if (AppContextSwitches.BlockLongPaths)
- {
- // We allow paths of any length if extended (and not in compat mode)
- if (AppContextSwitches.UseLegacyPathHandling || !IsExtended(fullPath))
- return fullPath.Length >= MaxShortPath;
- }
-#endif
-
- return fullPath.Length >= MaxLongPath;
- }
-
- /// <summary>
- /// Return true if any path segments are too long
- /// </summary>
- internal static bool AreSegmentsTooLong(string fullPath)
- {
- int length = fullPath.Length;
- int lastSeparator = 0;
-
- for (int i = 0; i < length; i++)
- {
- if (IsDirectorySeparator(fullPath[i]))
- {
- if (i - lastSeparator > MaxComponentLength)
- return true;
- lastSeparator = i;
- }
- }
-
- if (length - 1 - lastSeparator > MaxComponentLength)
- return true;
-
- return false;
- }
-
- /// <summary>
- /// Returns true if the directory is too long
- /// </summary>
- internal static bool IsDirectoryTooLong(string fullPath)
- {
-#if FEATURE_PATHCOMPAT
- if (AppContextSwitches.BlockLongPaths)
- {
- // We allow paths of any length if extended (and not in compat mode)
- if (AppContextSwitches.UseLegacyPathHandling || !IsExtended(fullPath))
- return (fullPath.Length >= MaxShortDirectoryPath);
- }
-#endif
-
- return IsPathTooLong(fullPath);
- }
-
- /// <summary>
- /// Adds the extended path prefix (\\?\) if not relative or already a device path.
- /// </summary>
- internal static string EnsureExtendedPrefix(string path)
- {
- // Putting the extended prefix on the path changes the processing of the path. It won't get normalized, which
- // means adding to relative paths will prevent them from getting the appropriate current directory inserted.
-
- // If it already has some variant of a device path (\??\, \\?\, \\.\, //./, etc.) we don't need to change it
- // as it is either correct or we will be changing the behavior. When/if Windows supports long paths implicitly
- // in the future we wouldn't want normalization to come back and break existing code.
-
- // In any case, all internal usages should be hitting normalize path (Path.GetFullPath) before they hit this
- // shimming method. (Or making a change that doesn't impact normalization, such as adding a filename to a
- // normalized base path.)
- if (IsPartiallyQualified(path) || IsDevice(path))
- return path;
-
- // Given \\server\share in longpath becomes \\?\UNC\server\share
- if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase))
- return path.Insert(2, UncExtendedPrefixToInsert);
-
- return ExtendedPathPrefix + path;
- }
-
- /// <summary>
- /// Removes the extended path prefix (\\?\) if present.
- /// </summary>
- internal static string RemoveExtendedPrefix(string path)
- {
- if (!IsExtended(path))
- return path;
-
- // Given \\?\UNC\server\share we return \\server\share
- if (IsExtendedUnc(path))
- return path.Remove(2, 6);
-
- return path.Substring(DevicePrefixLength);
- }
-
- /// <summary>
- /// Removes the extended path prefix (\\?\) if present.
- /// </summary>
- internal static StringBuilder RemoveExtendedPrefix(StringBuilder path)
- {
- if (!IsExtended(path))
- return path;
-
- // Given \\?\UNC\server\share we return \\server\share
- if (IsExtendedUnc(path))
- return path.Remove(2, 6);
-
- return path.Remove(0, DevicePrefixLength);
- }
-
- /// <summary>
- /// Returns true if the path uses any of the DOS device path syntaxes. ("\\.\", "\\?\", or "\??\")
- /// </summary>
- internal static bool IsDevice(string path)
- {
- // If the path begins with any two separators it will be recognized and normalized and prepped with
- // "\??\" for internal usage correctly. "\??\" is recognized and handled, "/??/" is not.
- return IsExtended(path)
- ||
- (
- path.Length >= DevicePrefixLength
- && IsDirectorySeparator(path[0])
- && IsDirectorySeparator(path[1])
- && (path[2] == '.' || path[2] == '?')
- && IsDirectorySeparator(path[3])
- );
- }
-
- /// <summary>
- /// Returns true if the path uses any of the DOS device path syntaxes. ("\\.\", "\\?\", or "\??\")
- /// </summary>
- internal static bool IsDevice(StringBuffer path)
- {
- // If the path begins with any two separators it will be recognized and normalized and prepped with
- // "\??\" for internal usage correctly. "\??\" is recognized and handled, "/??/" is not.
- return IsExtended(path)
- ||
- (
- path.Length >= DevicePrefixLength
- && IsDirectorySeparator(path[0])
- && IsDirectorySeparator(path[1])
- && (path[2] == '.' || path[2] == '?')
- && IsDirectorySeparator(path[3])
- );
- }
-
- /// <summary>
- /// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the
- /// path matches exactly (cannot use alternate directory separators) Windows will skip normalization
- /// and path length checks.
- /// </summary>
- internal static bool IsExtended(string path)
- {
- // While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths.
- // Skipping of normalization will *only* occur if back slashes ('\') are used.
- return path.Length >= DevicePrefixLength
- && path[0] == '\\'
- && (path[1] == '\\' || path[1] == '?')
- && path[2] == '?'
- && path[3] == '\\';
- }
-
- /// <summary>
- /// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the
- /// path matches exactly (cannot use alternate directory separators) Windows will skip normalization
- /// and path length checks.
- /// </summary>
- internal static bool IsExtended(StringBuilder path)
- {
- // While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths.
- // Skipping of normalization will *only* occur if back slashes ('\') are used.
- return path.Length >= DevicePrefixLength
- && path[0] == '\\'
- && (path[1] == '\\' || path[1] == '?')
- && path[2] == '?'
- && path[3] == '\\';
- }
-
- /// <summary>
- /// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the
- /// path matches exactly (cannot use alternate directory separators) Windows will skip normalization
- /// and path length checks.
- /// </summary>
- internal static bool IsExtended(StringBuffer path)
- {
- // While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths.
- // Skipping of normalization will *only* occur if back slashes ('\') are used.
- return path.Length >= DevicePrefixLength
- && path[0] == '\\'
- && (path[1] == '\\' || path[1] == '?')
- && path[2] == '?'
- && path[3] == '\\';
- }
-
- /// <summary>
- /// Returns true if the path uses the extended UNC syntax (\\?\UNC\ or \??\UNC\)
- /// </summary>
- internal static bool IsExtendedUnc(string path)
- {
- return path.Length >= UncExtendedPathPrefix.Length
- && IsExtended(path)
- && char.ToUpper(path[4]) == 'U'
- && char.ToUpper(path[5]) == 'N'
- && char.ToUpper(path[6]) == 'C'
- && path[7] == '\\';
- }
-
- /// <summary>
- /// Returns true if the path uses the extended UNC syntax (\\?\UNC\ or \??\UNC\)
- /// </summary>
- internal static bool IsExtendedUnc(StringBuilder path)
- {
- return path.Length >= UncExtendedPathPrefix.Length
- && IsExtended(path)
- && char.ToUpper(path[4]) == 'U'
- && char.ToUpper(path[5]) == 'N'
- && char.ToUpper(path[6]) == 'C'
- && path[7] == '\\';
- }
-
- /// <summary>
- /// Returns a value indicating if the given path contains invalid characters (", &lt;, &gt;, |
- /// NUL, or any ASCII char whose integer representation is in the range of 1 through 31).
- /// Does not check for wild card characters ? and *.
- ///
- /// Will not check if the path is a device path and not in Legacy mode as many of these
- /// characters are valid for devices (pipes for example).
- /// </summary>
- internal static bool HasIllegalCharacters(string path, bool checkAdditional = false)
- {
- if (
-#if FEATURE_PATHCOMPAT
- !AppContextSwitches.UseLegacyPathHandling &&
-#endif
- IsDevice(path))
- {
- return false;
- }
-
- return AnyPathHasIllegalCharacters(path, checkAdditional: checkAdditional);
- }
-
- /// <summary>
- /// Version of HasIllegalCharacters that checks no AppContextSwitches. Only use if you know you need to skip switches and don't care
- /// about proper device path handling.
- /// </summary>
- internal static bool AnyPathHasIllegalCharacters(string path, bool checkAdditional = false)
- {
- return path.IndexOfAny(InvalidPathChars) >= 0
-#if !PLATFORM_UNIX
- || (checkAdditional && AnyPathHasWildCardCharacters(path))
-#endif
- ;
- }
-
- /// <summary>
- /// Check for ? and *.
- /// </summary>
- internal static bool HasWildCardCharacters(string path)
- {
- // Question mark is part of some device paths
- int startIndex =
-#if FEATURE_PATHCOMPAT
- AppContextSwitches.UseLegacyPathHandling ? 0 :
-#endif
- IsDevice(path) ? ExtendedPathPrefix.Length : 0;
- return AnyPathHasWildCardCharacters(path, startIndex: startIndex);
- }
-
- /// <summary>
- /// Version of HasWildCardCharacters that checks no AppContextSwitches. Only use if you know you need to skip switches and don't care
- /// about proper device path handling.
- /// </summary>
- internal static bool AnyPathHasWildCardCharacters(string path, int startIndex = 0)
- {
- char currentChar;
- for (int i = startIndex; i < path.Length; i++)
- {
- currentChar = path[i];
- if (currentChar == '*' || currentChar == '?') return true;
- }
- return false;
- }
-
- /// <summary>
- /// Gets the length of the root of the path (drive, share, etc.).
- /// </summary>
- [System.Security.SecuritySafeCritical]
- internal unsafe static int GetRootLength(string path)
- {
- fixed (char* value = path)
- {
- return (int)GetRootLength(value, (ulong)path.Length);
- }
- }
-
- /// <summary>
- /// Gets the length of the root of the path (drive, share, etc.).
- /// </summary>
- [System.Security.SecuritySafeCritical]
- internal unsafe static uint GetRootLength(StringBuffer path)
- {
- if (path.Length == 0) return 0;
- return GetRootLength(path.CharPointer, path.Length);
- }
-
- [System.Security.SecurityCritical]
- private unsafe static uint GetRootLength(char* path, ulong pathLength)
- {
- uint i = 0;
-
-#if PLATFORM_UNIX
- if (pathLength >= 1 && (IsDirectorySeparator(path[0])))
- i = 1;
-#else
- uint volumeSeparatorLength = 2; // Length to the colon "C:"
- uint uncRootLength = 2; // Length to the start of the server name "\\"
-
- bool extendedSyntax = StartsWithOrdinal(path, pathLength, ExtendedPathPrefix);
- bool extendedUncSyntax = StartsWithOrdinal(path, pathLength, UncExtendedPathPrefix);
- if (extendedSyntax)
- {
- // Shift the position we look for the root from to account for the extended prefix
- if (extendedUncSyntax)
- {
- // "\\" -> "\\?\UNC\"
- uncRootLength = (uint)UncExtendedPathPrefix.Length;
- }
- else
- {
- // "C:" -> "\\?\C:"
- volumeSeparatorLength += (uint)ExtendedPathPrefix.Length;
- }
- }
-
- if ((!extendedSyntax || extendedUncSyntax) && pathLength > 0 && IsDirectorySeparator(path[0]))
- {
- // UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo")
-
- i = 1; // Drive rooted (\foo) is one character
- if (extendedUncSyntax || (pathLength > 1 && IsDirectorySeparator(path[1])))
- {
- // UNC (\\?\UNC\ or \\), scan past the next two directory separators at most
- // (e.g. to \\?\UNC\Server\Share or \\Server\Share\)
- i = uncRootLength;
- int n = 2; // Maximum separators to skip
- while (i < pathLength && (!IsDirectorySeparator(path[i]) || --n > 0)) i++;
- }
- }
- else if (pathLength >= volumeSeparatorLength && path[volumeSeparatorLength - 1] == Path.VolumeSeparatorChar)
- {
- // Path is at least longer than where we expect a colon, and has a colon (\\?\A:, A:)
- // If the colon is followed by a directory separator, move past it
- i = volumeSeparatorLength;
- if (pathLength >= volumeSeparatorLength + 1 && IsDirectorySeparator(path[volumeSeparatorLength])) i++;
- }
-#endif // !PLATFORM_UNIX
- return i;
- }
-
- [System.Security.SecurityCritical]
- private unsafe static bool StartsWithOrdinal(char* source, ulong sourceLength, string value)
- {
- if (sourceLength < (ulong)value.Length) return false;
- for (int i = 0; i < value.Length; i++)
- {
- if (value[i] != source[i]) return false;
- }
- return true;
- }
-
- /// <summary>
- /// Returns true if the path specified is relative to the current drive or working directory.
- /// Returns false if the path is fixed to a specific drive or UNC path. This method does no
- /// validation of the path (URIs will be returned as relative as a result).
- /// </summary>
- /// <remarks>
- /// Handles paths that use the alternate directory separator. It is a frequent mistake to
- /// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case.
- /// "C:a" is drive relative- meaning that it will be resolved against the current directory
- /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory
- /// will not be used to modify the path).
- /// </remarks>
- internal static bool IsPartiallyQualified(string path)
- {
-#if PLATFORM_UNIX
- return !(path.Length >= 1 && path[0] == Path.DirectorySeparatorChar);
-#else
- if (path.Length < 2)
- {
- // It isn't fixed, it must be relative. There is no way to specify a fixed
- // path with one character (or less).
- return true;
- }
-
- if (IsDirectorySeparator(path[0]))
- {
- // There is no valid way to specify a relative path with two initial slashes or
- // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\
- return !(path[1] == '?' || IsDirectorySeparator(path[1]));
- }
-
- // The only way to specify a fixed path that doesn't begin with two slashes
- // is the drive, colon, slash format- i.e. C:\
- return !((path.Length >= 3)
- && (path[1] == Path.VolumeSeparatorChar)
- && IsDirectorySeparator(path[2])
- // To match old behavior we'll check the drive character for validity as the path is technically
- // not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream.
- && IsValidDriveChar(path[0]));
-#endif // !PLATFORM_UNIX
- }
-
- /// <summary>
- /// Returns true if the path specified is relative to the current drive or working directory.
- /// Returns false if the path is fixed to a specific drive or UNC path. This method does no
- /// validation of the path (URIs will be returned as relative as a result).
- /// </summary>
- /// <remarks>
- /// Handles paths that use the alternate directory separator. It is a frequent mistake to
- /// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case.
- /// "C:a" is drive relative- meaning that it will be resolved against the current directory
- /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory
- /// will not be used to modify the path).
- /// </remarks>
- internal static bool IsPartiallyQualified(StringBuffer path)
- {
-#if PLATFORM_UNIX
- return !(path.Length >= 1 && path[0] == Path.DirectorySeparatorChar);
-#else
- if (path.Length < 2)
- {
- // It isn't fixed, it must be relative. There is no way to specify a fixed
- // path with one character (or less).
- return true;
- }
-
- if (IsDirectorySeparator(path[0]))
- {
- // There is no valid way to specify a relative path with two initial slashes or
- // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\
- return !(path[1] == '?' || IsDirectorySeparator(path[1]));
- }
-
- // The only way to specify a fixed path that doesn't begin with two slashes
- // is the drive, colon, slash format- i.e. C:\
- return !((path.Length >= 3)
- && (path[1] == Path.VolumeSeparatorChar)
- && IsDirectorySeparator(path[2])
- // To match old behavior we'll check the drive character for validity as the path is technically
- // not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream.
- && IsValidDriveChar(path[0]));
-#endif // !PLATFORM_UNIX
- }
-
- /// <summary>
- /// On Windows, returns the characters to skip at the start of the path if it starts with space(s) and a drive or directory separator.
- /// (examples are " C:", " \")
- /// This is a legacy behavior of Path.GetFullPath().
- /// </summary>
- /// <remarks>
- /// Note that this conflicts with IsPathRooted() which doesn't (and never did) such a skip.
- /// </remarks>
- internal static int PathStartSkip(string path)
- {
-#if !PLATFORM_UNIX
- int startIndex = 0;
- while (startIndex < path.Length && path[startIndex] == ' ') startIndex++;
-
- if (startIndex > 0 && (startIndex < path.Length && IsDirectorySeparator(path[startIndex]))
- || (startIndex + 1 < path.Length && path[startIndex + 1] == Path.VolumeSeparatorChar && IsValidDriveChar(path[startIndex])))
- {
- // Go ahead and skip spaces as we're either " C:" or " \"
- return startIndex;
- }
-#endif
-
- return 0;
- }
-
- /// <summary>
- /// True if the given character is a directory separator.
- /// </summary>
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal static bool IsDirectorySeparator(char c)
- {
- return c == Path.DirectorySeparatorChar
-#if !PLATFORM_UNIX
- || c == Path.AltDirectorySeparatorChar
-#endif
- ;
- }
-
- /// <summary>
- /// Normalize separators in the given path. Converts forward slashes into back slashes and compresses slash runs, keeping initial 2 if present.
- /// Also trims initial whitespace in front of "rooted" paths (see PathStartSkip).
- ///
- /// This effectively replicates the behavior of the legacy NormalizePath when it was called with fullCheck=false and expandShortpaths=false.
- /// The current NormalizePath gets directory separator normalization from Win32's GetFullPathName(), which will resolve relative paths and as
- /// such can't be used here (and is overkill for our uses).
- ///
- /// Like the current NormalizePath this will not try and analyze periods/spaces within directory segments.
- /// </summary>
- /// <remarks>
- /// The only callers that used to use Path.Normalize(fullCheck=false) were Path.GetDirectoryName() and Path.GetPathRoot(). Both usages do
- /// not need trimming of trailing whitespace here.
- ///
- /// GetPathRoot() could technically skip normalizing separators after the second segment- consider as a future optimization.
- ///
- /// For legacy desktop behavior with ExpandShortPaths:
- /// - It has no impact on GetPathRoot() so doesn't need consideration.
- /// - It could impact GetDirectoryName(), but only if the path isn't relative (C:\ or \\Server\Share).
- ///
- /// In the case of GetDirectoryName() the ExpandShortPaths behavior was undocumented and provided inconsistent results if the path was
- /// fixed/relative. For example: "C:\PROGRA~1\A.TXT" would return "C:\Program Files" while ".\PROGRA~1\A.TXT" would return ".\PROGRA~1". If you
- /// ultimately call GetFullPath() this doesn't matter, but if you don't or have any intermediate string handling could easily be tripped up by
- /// this undocumented behavior.
- /// </remarks>
- internal static string NormalizeDirectorySeparators(string path)
- {
- if (string.IsNullOrEmpty(path)) return path;
-
- char current;
- int start = PathStartSkip(path);
-
- if (start == 0)
- {
- // Make a pass to see if we need to normalize so we can potentially skip allocating
- bool normalized = true;
-
- for (int i = 0; i < path.Length; i++)
- {
- current = path[i];
- if (IsDirectorySeparator(current)
- && (current != Path.DirectorySeparatorChar
-#if !PLATFORM_UNIX
- // Check for sequential separators past the first position (we need to keep initial two for UNC/extended)
- || (i > 0 && i + 1 < path.Length && IsDirectorySeparator(path[i + 1]))
-#endif
- ))
- {
- normalized = false;
- break;
- }
- }
-
- if (normalized) return path;
- }
-
- StringBuilder builder = StringBuilderCache.Acquire(path.Length);
-
-#if !PLATFORM_UNIX
- // On Windows we always keep the first separator, even if the next is a separator (we need to keep initial two for UNC/extended)
- if (IsDirectorySeparator(path[start]))
- {
- start++;
- builder.Append(Path.DirectorySeparatorChar);
- }
-#endif
-
- for (int i = start; i < path.Length; i++)
- {
- current = path[i];
-
- // If we have a separator
- if (IsDirectorySeparator(current))
- {
- // If the next is a separator, skip adding this
- if (i + 1 < path.Length && IsDirectorySeparator(path[i + 1]))
- {
- continue;
- }
-
- // Ensure it is the primary separator
- current = Path.DirectorySeparatorChar;
- }
-
- builder.Append(current);
- }
-
- return StringBuilderCache.GetStringAndRelease(builder);
- }
-
-#if PLATFORM_UNIX
- // We rely on Windows to remove relative segments on Windows. This would need to be updated to
- // handle the proper rooting on Windows if we for some reason need it.
-
- /// <summary>
- /// Try to remove relative segments from the given path (without combining with a root).
- /// </summary>
- /// <param name="skip">Skip the specified number of characters before evaluating.</param>
- internal static string RemoveRelativeSegments(string path, int skip = 0)
- {
- bool flippedSeparator = false;
-
- // Remove "//", "/./", and "/../" from the path by copying each character to the output,
- // except the ones we're removing, such that the builder contains the normalized path
- // at the end.
- var sb = StringBuilderCache.Acquire(path.Length);
- if (skip > 0)
- {
- sb.Append(path, 0, skip);
- }
-
- int componentCharCount = 0;
- for (int i = skip; i < path.Length; i++)
- {
- char c = path[i];
-
- if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length)
- {
- componentCharCount = 0;
-
- // Skip this character if it's a directory separator and if the next character is, too,
- // e.g. "parent//child" => "parent/child"
- if (PathInternal.IsDirectorySeparator(path[i + 1]))
- {
- continue;
- }
-
- // Skip this character and the next if it's referring to the current directory,
- // e.g. "parent/./child" =? "parent/child"
- if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) &&
- path[i + 1] == '.')
- {
- i++;
- continue;
- }
-
- // Skip this character and the next two if it's referring to the parent directory,
- // e.g. "parent/child/../grandchild" => "parent/grandchild"
- if (i + 2 < path.Length &&
- (i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) &&
- path[i + 1] == '.' && path[i + 2] == '.')
- {
- // Unwind back to the last slash (and if there isn't one, clear out everything).
- int s;
- for (s = sb.Length - 1; s >= 0; s--)
- {
- if (PathInternal.IsDirectorySeparator(sb[s]))
- {
- sb.Length = s;
- break;
- }
- }
- if (s < 0)
- {
- sb.Length = 0;
- }
-
- i += 2;
- continue;
- }
- }
-
- if (++componentCharCount > PathInternal.MaxComponentLength)
- {
- throw new PathTooLongException();
- }
-
- // Normalize the directory separator if needed
- if (c != Path.DirectorySeparatorChar && c == Path.AltDirectorySeparatorChar)
- {
- c = Path.DirectorySeparatorChar;
- flippedSeparator = true;
- }
-
- sb.Append(c);
- }
-
- if (flippedSeparator || sb.Length != path.Length)
- {
- return StringBuilderCache.GetStringAndRelease(sb);
- }
- else
- {
- // We haven't changed the source path, return the original
- StringBuilderCache.Release(sb);
- return path;
- }
- }
-#endif // PLATFORM_UNIX
- }
-} \ No newline at end of file
diff --git a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
index 4fd54f57f5..890669fa58 100644
--- a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
+++ b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
@@ -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) {
diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs
index a1f29364cb..3cdfad613e 100644
--- a/src/mscorlib/src/System/IO/Stream.cs
+++ b/src/mscorlib/src/System/IO/Stream.cs
@@ -15,26 +15,23 @@
**
===========================================================*/
using System;
+using System.Buffers;
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;
namespace System.IO {
[Serializable]
[ComVisible(true)]
-#if FEATURE_REMOTING
public abstract class Stream : MarshalByRefObject, IDisposable {
-#else // FEATURE_REMOTING
- public abstract class Stream : IDisposable {
-#endif // FEATURE_REMOTING
public static readonly Stream Null = new NullStream();
@@ -112,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;
@@ -147,23 +142,20 @@ 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)
{
- ValidateCopyToArguments(destination, bufferSize);
+ StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
@@ -175,11 +167,22 @@ namespace System.IO {
Contract.Requires(CanRead);
Contract.Requires(destination.CanWrite);
- byte[] buffer = new byte[bufferSize];
- int bytesRead;
- while ((bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
+ 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
+ {
+ while (true)
+ {
+ int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
+ if (bytesRead == 0) break;
+ if (bytesRead > bufferSize) bufferSize = bytesRead;
+ await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ finally
{
- await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
+ Array.Clear(buffer, 0, bufferSize); // clear only the most we used
+ ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}
}
@@ -190,7 +193,6 @@ namespace System.IO {
{
int bufferSize = _DefaultCopyBufferSize;
-#if FEATURE_CORECLR
if (CanSeek)
{
long length = Length;
@@ -209,19 +211,30 @@ namespace System.IO {
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
-#endif // FEATURE_CORECLR
-
+
CopyTo(destination, bufferSize);
}
public virtual void CopyTo(Stream destination, int bufferSize)
{
- ValidateCopyToArguments(destination, bufferSize);
-
- byte[] buffer = new byte[bufferSize];
- int read;
- while ((read = Read(buffer, 0, buffer.Length)) != 0)
- destination.Write(buffer, 0, read);
+ StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
+
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
+ int highwaterMark = 0;
+ try
+ {
+ int read;
+ while ((read = Read(buffer, 0, buffer.Length)) != 0)
+ {
+ if (read > highwaterMark) highwaterMark = read;
+ destination.Write(buffer, 0, read);
+ }
+ }
+ finally
+ {
+ Array.Clear(buffer, 0, highwaterMark); // clear only the most we used
+ ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
+ }
}
// Stream used to require that all cleanup logic went into Close(),
@@ -265,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)
{
@@ -287,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)
@@ -326,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
{
@@ -360,7 +369,7 @@ namespace System.IO {
public virtual int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ throw new ArgumentNullException(nameof(asyncResult));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
@@ -389,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)
{
@@ -407,7 +414,6 @@ namespace System.IO {
: BeginEndReadAsync(buffer, offset, count);
}
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndRead();
@@ -436,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)
@@ -475,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
{
@@ -508,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);
@@ -531,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
@@ -545,14 +549,14 @@ 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();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult==null)
- throw new ArgumentNullException("asyncResult");
+ throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
var writeTask = _activeReadWriteTask;
@@ -572,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
{
@@ -613,7 +617,6 @@ namespace System.IO {
_buffer = null;
}
- [SecuritySafeCritical] // necessary for EC.Capture
[MethodImpl(MethodImplOptions.NoInlining)]
public ReadWriteTask(
bool isRead,
@@ -651,7 +654,6 @@ namespace System.IO {
}
}
- [SecurityCritical] // necessary for CoreCLR
private static void InvokeAsyncCallback(object completedTask)
{
var rwc = (ReadWriteTask)completedTask;
@@ -660,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
@@ -690,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)
{
@@ -699,7 +698,6 @@ namespace System.IO {
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
@@ -710,7 +708,6 @@ namespace System.IO {
: BeginEndWriteAsync(buffer, offset, count);
}
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndWrite();
@@ -772,11 +769,10 @@ namespace System.IO {
Write(oneByteArray, 0, 1);
}
- [HostProtection(Synchronization=true)]
public static Stream Synchronized(Stream stream)
{
if (stream==null)
- throw new ArgumentNullException("stream");
+ throw new ArgumentNullException(nameof(stream));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
if (stream is SyncStream)
@@ -853,23 +849,6 @@ namespace System.IO {
{
SynchronousAsyncResult.EndWrite(asyncResult);
}
-
- internal void ValidateCopyToArguments(Stream destination, int bufferSize)
- {
- if (destination == null)
- throw new ArgumentNullException("destination");
- if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
- if (!CanRead && !CanWrite)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
- if (!destination.CanRead && !destination.CanWrite)
- throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed"));
- if (!CanRead)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
- if (!destination.CanWrite)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
- Contract.EndContractBlock();
- }
[Serializable]
private sealed class NullStream : Stream
@@ -900,11 +879,18 @@ namespace System.IO {
set {}
}
+ public override void CopyTo(Stream destination, int bufferSize)
+ {
+ StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
+
+ // After we validate arguments this is a nop.
+ }
+
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
- ValidateCopyToArguments(destination, bufferSize);
+ StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
@@ -928,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();
@@ -939,13 +924,12 @@ namespace System.IO {
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
return BlockingEndRead(asyncResult);
}
- [HostProtection(ExternalThreading = true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanWrite) __Error.WriteNotSupported();
@@ -956,7 +940,7 @@ namespace System.IO {
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
BlockingEndWrite(asyncResult);
@@ -1102,7 +1086,7 @@ namespace System.IO {
internal SyncStream(Stream stream)
{
if (stream == null)
- throw new ArgumentNullException("stream");
+ throw new ArgumentNullException(nameof(stream));
Contract.EndContractBlock();
_stream = stream;
}
@@ -1217,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();
@@ -1239,7 +1222,7 @@ namespace System.IO {
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ throw new ArgumentNullException(nameof(asyncResult));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
@@ -1271,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();
@@ -1293,7 +1275,7 @@ namespace System.IO {
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
lock(_stream)
diff --git a/src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs b/src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs
new file mode 100644
index 0000000000..8ff0e045ca
--- /dev/null
+++ b/src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs
@@ -0,0 +1,46 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.IO
+{
+ /// <summary>Provides methods to help in the implementation of Stream-derived types.</summary>
+ internal static partial class StreamHelpers
+ {
+ /// <summary>Validate the arguments to CopyTo, as would Stream.CopyTo.</summary>
+ public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize)
+ {
+ if (destination == null)
+ {
+ throw new ArgumentNullException(nameof(destination));
+ }
+
+ if (bufferSize <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ }
+
+ bool sourceCanRead = source.CanRead;
+ if (!sourceCanRead && !source.CanWrite)
+ {
+ throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+ }
+
+ bool destinationCanWrite = destination.CanWrite;
+ if (!destinationCanWrite && !destination.CanRead)
+ {
+ throw new ObjectDisposedException(nameof(destination), Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+ }
+
+ if (!sourceCanRead)
+ {
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
+ }
+
+ if (!destinationCanWrite)
+ {
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/IO/StreamReader.cs b/src/mscorlib/src/System/IO/StreamReader.cs
index 549733bb47..708db088e8 100644
--- a/src/mscorlib/src/System/IO/StreamReader.cs
+++ b/src/mscorlib/src/System/IO/StreamReader.cs
@@ -2,22 +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.
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: For reading text from streams in a particular
-** encoding.
-**
-**
-===========================================================*/
-
-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;
@@ -161,11 +149,11 @@ namespace System.IO
public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)
{
if (stream == null || encoding == null)
- throw new ArgumentNullException((stream == null ? "stream" : "encoding"));
+ throw new ArgumentNullException((stream == null ? nameof(stream) : nameof(encoding)));
if (!stream.CanRead)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen);
@@ -187,26 +175,20 @@ 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,
// or we'll create a FileStream on disk and we won't close it until
// the finalizer runs, causing problems for applications.
if (path==null || encoding==null)
- throw new ArgumentNullException((path==null ? "path" : "encoding"));
+ throw new ArgumentNullException((path==null ? nameof(path) : nameof(encoding)));
if (path.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
- Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
+ Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false);
Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false);
}
@@ -358,9 +340,9 @@ namespace System.IO
public override int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -416,9 +398,9 @@ namespace System.IO
public override int ReadBlock([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -434,7 +416,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 +484,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 +495,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 +550,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 +570,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 +632,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 +659,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 +757,6 @@ namespace System.IO
}
#region Task based Async APIs
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task<String> ReadLineAsync()
{
@@ -856,7 +837,6 @@ namespace System.IO
return GetStringAndReleaseSharedStringBuilder(sb);
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task<String> ReadToEndAsync()
{
@@ -893,14 +873,13 @@ namespace System.IO
return GetStringAndReleaseSharedStringBuilder(sb);
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -957,14 +936,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 +964,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 +976,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 +1010,7 @@ namespace System.IO
readToUserBuffer = count >= MaxCharsPerBuffer_Prop;
}
- Contract.Assert(n == 0);
+ Debug.Assert(n == 0);
CharPos_Prop = 0;
if (readToUserBuffer)
@@ -1039,7 +1018,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 +1027,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,14 +1060,13 @@ namespace System.IO
return charsRead;
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -1185,10 +1163,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 +1184,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;
diff --git a/src/mscorlib/src/System/IO/StreamWriter.cs b/src/mscorlib/src/System/IO/StreamWriter.cs
index 65613bb0a6..22eba82605 100644
--- a/src/mscorlib/src/System/IO/StreamWriter.cs
+++ b/src/mscorlib/src/System/IO/StreamWriter.cs
@@ -2,25 +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.
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: For writing text to streams in a particular
-** encoding.
-**
-**
-===========================================================*/
-using System;
using System.Text;
-using System.Threading;
-using System.Globalization;
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;
@@ -45,10 +31,8 @@ namespace System.IO
private const int DefaultFileStreamBufferSize = 4096;
private const int MinBufferSize = 128;
- private const Int32 DontCopyOnWriteLineThreshold = 512;
-
// Bit bucket - Null has no backing store. Non closable.
- public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true);
+ public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, UTF8NoBOM, MinBufferSize, true);
private Stream stream;
private Encoding encoding;
@@ -61,12 +45,6 @@ namespace System.IO
private bool haveWrittenPreamble;
private bool closable;
-#if MDA_SUPPORTED
- [NonSerialized]
- // For StreamWriterBufferedDataLost MDA
- private MdaHelper mdaHelper;
-#endif
-
// We don't guarantee thread safety on StreamWriter, but we should at
// least prevent users from trying to write anything while an Async
// write from the same thread is in progress.
@@ -93,20 +71,9 @@ namespace System.IO
// Even Close() will hit the exception as it would try to flush the unwritten data.
// Maybe we can add a DiscardBufferedData() method to get out of such situation (like
// StreamReader though for different reason). Either way, the buffered data will be lost!
- private static volatile Encoding _UTF8NoBOM;
-
internal static Encoding UTF8NoBOM {
[FriendAccessAllowed]
- get {
- if (_UTF8NoBOM == null) {
- // No need for double lock - we just want to avoid extra
- // allocations in the common case.
- UTF8Encoding noBOM = new UTF8Encoding(false, true);
- Thread.MemoryBarrier();
- _UTF8NoBOM = noBOM;
- }
- return _UTF8NoBOM;
- }
+ get { return EncodingCache.UTF8NoBOM; }
}
@@ -133,10 +100,10 @@ namespace System.IO
: base(null) // Ask for CurrentCulture all the time
{
if (stream == null || encoding == null)
- throw new ArgumentNullException((stream == null ? "stream" : "encoding"));
+ throw new ArgumentNullException((stream == null ? nameof(stream) : nameof(encoding)));
if (!stream.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
- if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Init(stream, encoding, bufferSize, leaveOpen);
@@ -154,28 +121,23 @@ 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)
+ public StreamWriter(String path, bool append, Encoding encoding, int bufferSize)
: base(null)
- { // Ask for CurrentCulture all the time
+ {
+ // Ask for CurrentCulture all the time
if (path == null)
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
if (encoding == null)
- throw new ArgumentNullException("encoding");
+ throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
- if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
- Stream stream = CreateFile(path, append, checkHost);
+ Stream stream = CreateFile(path, append);
Init(stream, encoding, bufferSize, false);
}
- [System.Security.SecuritySafeCritical]
private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
{
this.stream = streamArg;
@@ -190,21 +152,12 @@ namespace System.IO
if (stream.CanSeek && stream.Position > 0)
haveWrittenPreamble = true;
closable = !shouldLeaveOpen;
-#if MDA_SUPPORTED
- if (Mda.StreamWriterBufferedDataLost.Enabled) {
- String callstack = null;
- if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack)
- callstack = Environment.GetStackTrace(null, false);
- mdaHelper = new MdaHelper(this, callstack);
- }
-#endif
}
- [System.Security.SecurityCritical]
- private static Stream CreateFile(String path, bool append, bool checkHost) {
+ private static Stream CreateFile(String path, bool append) {
FileMode mode = append? FileMode.Append: FileMode.Create;
FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read,
- DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
+ DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false);
return f;
}
@@ -221,20 +174,11 @@ 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();
Flush(true, true);
-#if MDA_SUPPORTED
- // Disable buffered data loss mda
- if (mdaHelper != null)
- GC.SuppressFinalize(mdaHelper);
-#endif
}
}
}
@@ -354,7 +298,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;
@@ -365,11 +309,11 @@ namespace System.IO
public override void Write(char[] buffer, int index, int count) {
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -380,7 +324,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;
@@ -402,7 +346,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;
@@ -413,7 +357,6 @@ namespace System.IO
}
#region Task based Async APIs
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char value)
{
@@ -444,7 +387,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,7 +400,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;
}
@@ -468,14 +411,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)
{
@@ -520,7 +462,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;
}
@@ -528,7 +470,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);
@@ -543,7 +485,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;
}
@@ -554,23 +496,22 @@ 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)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -609,14 +550,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));
@@ -631,7 +572,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;
}
@@ -642,14 +583,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()
{
@@ -672,7 +612,6 @@ namespace System.IO
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char value)
{
@@ -695,7 +634,6 @@ namespace System.IO
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(String value)
{
@@ -718,16 +656,15 @@ namespace System.IO
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -751,7 +688,6 @@ namespace System.IO
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task FlushAsync()
{
@@ -825,42 +761,5 @@ namespace System.IO
await stream.FlushAsync().ConfigureAwait(false);
}
#endregion
-
-#if MDA_SUPPORTED
- // StreamWriterBufferedDataLost MDA
- // Instead of adding a finalizer to StreamWriter for detecting buffered data loss
- // (ie, when the user forgets to call Close/Flush on the StreamWriter), we will
- // have a separate object with normal finalization semantics that maintains a
- // back pointer to this StreamWriter and alerts about any data loss
- private sealed class MdaHelper
- {
- private StreamWriter streamWriter;
- private String allocatedCallstack; // captures the callstack when this streamwriter was allocated
-
- internal MdaHelper(StreamWriter sw, String cs)
- {
- streamWriter = sw;
- allocatedCallstack = cs;
- }
-
- // Finalizer
- ~MdaHelper()
- {
- // Make sure people closed this StreamWriter, exclude StreamWriter::Null.
- if (streamWriter.charPos != 0 && streamWriter.stream != null && streamWriter.stream != Stream.Null) {
- String fileName = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>";
- String callStack = allocatedCallstack;
-
- if (callStack == null)
- callStack = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled");
-
- String message = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, fileName, callStack);
-
- Mda.StreamWriterBufferedDataLost.ReportError(message);
- }
- }
- } // class MdaHelper
-#endif // MDA_SUPPORTED
-
} // class StreamWriter
} // namespace
diff --git a/src/mscorlib/src/System/IO/StringReader.cs b/src/mscorlib/src/System/IO/StringReader.cs
deleted file mode 100644
index e5fa811453..0000000000
--- a/src/mscorlib/src/System/IO/StringReader.cs
+++ /dev/null
@@ -1,187 +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: For reading text from strings
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
-using System.Security.Permissions;
-using System.Threading.Tasks;
-
-namespace System.IO {
- // This class implements a text reader that reads from a string.
- //
- [Serializable]
- [ComVisible(true)]
- public class StringReader : TextReader
- {
- private String _s;
- private int _pos;
- private int _length;
-
- public StringReader(String s) {
- if (s == null)
- throw new ArgumentNullException("s");
- Contract.EndContractBlock();
- _s = s;
- _length = s == null? 0: s.Length;
- }
-
- // Closes this StringReader. Following a call to this method, the String
- // Reader will throw an ObjectDisposedException.
- public override void Close() {
- Dispose(true);
- }
-
- protected override void Dispose(bool disposing) {
- _s = null;
- _pos = 0;
- _length = 0;
- base.Dispose(disposing);
- }
-
- // Returns the next available character without actually reading it from
- // the underlying string. The current position of the StringReader is not
- // changed by this operation. The returned value is -1 if no further
- // characters are available.
- //
- [Pure]
- public override int Peek() {
- if (_s == null)
- __Error.ReaderClosed();
- if (_pos == _length) return -1;
- return _s[_pos];
- }
-
- // Reads the next character from the underlying string. The returned value
- // is -1 if no further characters are available.
- //
- public override int Read() {
- if (_s == null)
- __Error.ReaderClosed();
- if (_pos == _length) return -1;
- return _s[_pos++];
- }
-
- // Reads a block of characters. This method will read up to count
- // characters from this StringReader into the buffer character
- // array starting at position index. Returns the actual number of
- // characters read, or zero if the end of the string is reached.
- //
- public override int Read([In, Out] char[] buffer, int index, int count) {
- if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
- if (_s == null)
- __Error.ReaderClosed();
-
- int n = _length - _pos;
- if (n > 0) {
- if (n > count) n = count;
- _s.CopyTo(_pos, buffer, index, n);
- _pos += n;
- }
- return n;
- }
-
- public override String ReadToEnd()
- {
- if (_s == null)
- __Error.ReaderClosed();
- String s;
- if (_pos==0)
- s = _s;
- else
- s = _s.Substring(_pos, _length - _pos);
- _pos = _length;
- return s;
- }
-
- // Reads a line. A line is defined as a sequence of characters followed by
- // a carriage return ('\r'), a line feed ('\n'), or a carriage return
- // immediately followed by a line feed. The resulting string does not
- // contain the terminating carriage return and/or line feed. The returned
- // value is null if the end of the underlying string has been reached.
- //
- public override String ReadLine() {
- if (_s == null)
- __Error.ReaderClosed();
- int i = _pos;
- while (i < _length) {
- char ch = _s[i];
- if (ch == '\r' || ch == '\n') {
- String result = _s.Substring(_pos, i - _pos);
- _pos = i + 1;
- if (ch == '\r' && _pos < _length && _s[_pos] == '\n') _pos++;
- return result;
- }
- i++;
- }
- if (i > _pos) {
- String result = _s.Substring(_pos, i - _pos);
- _pos = i;
- return result;
- }
- return null;
- }
-
- #region Task based Async APIs
- [ComVisible(false)]
- public override Task<String> ReadLineAsync()
- {
- return Task.FromResult(ReadLine());
- }
-
- [ComVisible(false)]
- public override Task<String> ReadToEndAsync()
- {
- return Task.FromResult(ReadToEnd());
- }
-
- [ComVisible(false)]
- public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
- {
- if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
-
- Contract.EndContractBlock();
-
- return Task.FromResult(ReadBlock(buffer, index, count));
- }
-
- [ComVisible(false)]
- public override Task<int> ReadAsync(char[] buffer, int index, int count)
- {
- if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- return Task.FromResult(Read(buffer, index, count));
- }
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/IO/StringWriter.cs b/src/mscorlib/src/System/IO/StringWriter.cs
deleted file mode 100644
index 282a7910c2..0000000000
--- a/src/mscorlib/src/System/IO/StringWriter.cs
+++ /dev/null
@@ -1,196 +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: For writing text to a string
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime;
-using System.Text;
-using System.Globalization;
-using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
-using System.Security.Permissions;
-using System.Threading.Tasks;
-
-namespace System.IO {
- // This class implements a text writer that writes to a string buffer and allows
- // the resulting sequence of characters to be presented as a string.
- //
- [Serializable]
- [ComVisible(true)]
- public class StringWriter : TextWriter
- {
- private static volatile UnicodeEncoding m_encoding=null;
-
- private StringBuilder _sb;
- private bool _isOpen;
-
- // Constructs a new StringWriter. A new StringBuilder is automatically
- // created and associated with the new StringWriter.
- public StringWriter()
- : this(new StringBuilder(), CultureInfo.CurrentCulture)
- {
- }
-
- public StringWriter(IFormatProvider formatProvider)
- : this(new StringBuilder(), formatProvider) {
- }
-
- // Constructs a new StringWriter that writes to the given StringBuilder.
- //
- public StringWriter(StringBuilder sb) : this(sb, CultureInfo.CurrentCulture) {
- }
-
- public StringWriter(StringBuilder sb, IFormatProvider formatProvider) : base(formatProvider) {
- if (sb==null)
- throw new ArgumentNullException("sb", Environment.GetResourceString("ArgumentNull_Buffer"));
- Contract.EndContractBlock();
- _sb = sb;
- _isOpen = true;
- }
-
- public override void Close()
- {
- Dispose(true);
- }
-
- protected override void Dispose(bool disposing)
- {
- // Do not destroy _sb, so that we can extract this after we are
- // done writing (similar to MemoryStream's GetBuffer & ToArray methods)
- _isOpen = false;
- base.Dispose(disposing);
- }
-
-
- public override Encoding Encoding {
- get {
- if (m_encoding==null) {
- m_encoding = new UnicodeEncoding(false, false);
- }
- return m_encoding;
- }
- }
-
- // Returns the underlying StringBuilder. This is either the StringBuilder
- // that was passed to the constructor, or the StringBuilder that was
- // automatically created.
- //
- public virtual StringBuilder GetStringBuilder() {
- return _sb;
- }
-
- // Writes a character to the underlying string buffer.
- //
- public override void Write(char value) {
- if (!_isOpen)
- __Error.WriterClosed();
- _sb.Append(value);
- }
-
- // Writes a range of a character array to the underlying string buffer.
- // This method will write count characters of data into this
- // StringWriter from the buffer character array starting at position
- // index.
- //
- public override void Write(char[] buffer, int index, int count) {
- if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
- if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- if (!_isOpen)
- __Error.WriterClosed();
-
- _sb.Append(buffer, index, count);
- }
-
- // Writes a string to the underlying string buffer. If the given string is
- // null, nothing is written.
- //
- public override void Write(String value) {
- if (!_isOpen)
- __Error.WriterClosed();
- if (value != null) _sb.Append(value);
- }
-
-
- #region Task based Async APIs
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- public override Task WriteAsync(char value)
- {
- Write(value);
- return Task.CompletedTask;
- }
-
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- public override Task WriteAsync(String value)
- {
- Write(value);
- return Task.CompletedTask;
- }
-
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- public override Task WriteAsync(char[] buffer, int index, int count)
- {
- Write(buffer, index, count);
- return Task.CompletedTask;
- }
-
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- public override Task WriteLineAsync(char value)
- {
- WriteLine(value);
- return Task.CompletedTask;
- }
-
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- public override Task WriteLineAsync(String value)
- {
- WriteLine(value);
- return Task.CompletedTask;
- }
-
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- public override Task WriteLineAsync(char[] buffer, int index, int count)
- {
- WriteLine(buffer, index, count);
- return Task.CompletedTask;
- }
-
- [HostProtection(ExternalThreading = true)]
- [ComVisible(false)]
- public override Task FlushAsync()
- {
- return Task.CompletedTask;
- }
- #endregion
-
- // Returns a string containing the characters written to this TextWriter
- // so far.
- //
- public override String ToString() {
- return _sb.ToString();
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/TextReader.cs b/src/mscorlib/src/System/IO/TextReader.cs
index ede482784a..6cbadfbce5 100644
--- a/src/mscorlib/src/System/IO/TextReader.cs
+++ b/src/mscorlib/src/System/IO/TextReader.cs
@@ -14,11 +14,9 @@
**
===========================================================*/
-using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-using System.Reflection;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
@@ -35,11 +33,7 @@ namespace System.IO {
// There are methods on the Stream class for reading bytes.
[Serializable]
[ComVisible(true)]
-#if FEATURE_REMOTING
public abstract class TextReader : MarshalByRefObject, IDisposable {
-#else // FEATURE_REMOTING
- public abstract class TextReader : IDisposable {
-#endif // FEATURE_REMOTING
public static readonly TextReader Null = new NullTextReader();
@@ -101,11 +95,11 @@ namespace System.IO {
public virtual int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<int>() >= 0);
@@ -176,7 +170,6 @@ namespace System.IO {
}
#region Task based Async APIs
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<String> ReadLineAsync()
{
@@ -187,7 +180,6 @@ namespace System.IO {
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public async virtual Task<String> ReadToEndAsync()
{
@@ -201,14 +193,13 @@ namespace System.IO {
return sb.ToString();
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -232,14 +223,13 @@ 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)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
@@ -248,7 +238,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);
@@ -267,11 +256,10 @@ namespace System.IO {
}
#endregion
- [HostProtection(Synchronization=true)]
public static TextReader Synchronized(TextReader reader)
{
if (reader==null)
- throw new ArgumentNullException("reader");
+ throw new ArgumentNullException(nameof(reader));
Contract.Ensures(Contract.Result<TextReader>() != null);
Contract.EndContractBlock();
@@ -383,9 +371,9 @@ namespace System.IO {
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
@@ -399,9 +387,9 @@ namespace System.IO {
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/IO/TextWriter.cs b/src/mscorlib/src/System/IO/TextWriter.cs
index 165001e1a6..131f69d35d 100644
--- a/src/mscorlib/src/System/IO/TextWriter.cs
+++ b/src/mscorlib/src/System/IO/TextWriter.cs
@@ -2,24 +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.
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Abstract base class for Text-only Writers.
-** Subclasses will include StreamWriter & StringWriter.
-**
-**
-===========================================================*/
-
-using System;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Reflection;
using System.Security.Permissions;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
@@ -35,11 +21,7 @@ namespace System.IO {
// There are methods on the Stream class for writing bytes.
[Serializable]
[ComVisible(true)]
-#if FEATURE_REMOTING
public abstract class TextWriter : MarshalByRefObject, IDisposable {
-#else // FEATURE_REMOTING
- public abstract class TextWriter : IDisposable {
-#endif // FEATURE_REMOTING
public static readonly TextWriter Null = new NullTextWriter();
// This should be initialized to Environment.NewLine, but
@@ -128,10 +110,9 @@ namespace System.IO {
}
- [HostProtection(Synchronization=true)]
public static TextWriter Synchronized(TextWriter writer) {
if (writer==null)
- throw new ArgumentNullException("writer");
+ throw new ArgumentNullException(nameof(writer));
Contract.Ensures(Contract.Result<TextWriter>() != null);
Contract.EndContractBlock();
@@ -162,11 +143,11 @@ namespace System.IO {
//
public virtual void Write(char[] buffer, int index, int count) {
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -490,7 +471,6 @@ namespace System.IO {
}
#region Task based Async APIs
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(char value)
{
@@ -503,7 +483,6 @@ namespace System.IO {
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(String value)
{
@@ -516,7 +495,6 @@ namespace System.IO {
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteAsync(char[] buffer)
{
@@ -524,7 +502,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)
{
@@ -537,7 +514,6 @@ namespace System.IO {
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(char value)
{
@@ -550,7 +526,6 @@ namespace System.IO {
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(String value)
{
@@ -563,7 +538,6 @@ namespace System.IO {
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteLineAsync(char[] buffer)
{
@@ -571,7 +545,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)
{
@@ -584,14 +557,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()
{
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
index ea70057217..4208ebfb6d 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
@@ -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,35 +46,29 @@ 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("buffer");
+ throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0) {
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (capacity < 0) {
- throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (buffer.ByteLength < (UInt64)(offset + capacity)) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndCapacityOutOfBounds"));
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
- throw new ArgumentOutOfRangeException("access");
+ throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
@@ -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,18 +291,63 @@ namespace System.IO {
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private unsafe Int32 UnsafeReadInt32(byte* pointer)
+ {
+ Int32 result;
+ // check if pointer is aligned
+ if (((int)pointer & (sizeof(Int32) - 1)) == 0)
+ {
+ result = *((Int32*)pointer);
+ }
+ else
+ {
+ result = (Int32)(*(pointer) | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24);
+ }
+
+ return result;
+ }
public Decimal ReadDecimal(Int64 position) {
+ const int ScaleMask = 0x00FF0000;
+ const int SignMask = unchecked((int)0x80000000);
+
int sizeOfType = sizeof(Decimal);
EnsureSafeToRead(position, sizeOfType);
- int[] decimalArray = new int[4];
- ReadArray<int>(position, decimalArray, 0, decimalArray.Length);
+ unsafe
+ {
+ byte* pointer = null;
+ try
+ {
+ _buffer.AcquirePointer(ref pointer);
+ pointer += (_offset + position);
- return new Decimal(decimalArray);
+ int lo = UnsafeReadInt32(pointer);
+ int mid = UnsafeReadInt32(pointer + 4);
+ int hi = UnsafeReadInt32(pointer + 8);
+ int flags = UnsafeReadInt32(pointer + 12);
+
+ // Check for invalid Decimal values
+ if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16)))
+ {
+ throw new ArgumentException(Environment.GetResourceString("Arg_BadDecimal")); // Throw same Exception type as Decimal(int[]) ctor for compat
+ }
+
+ bool isNegative = (flags & SignMask) != 0;
+ byte scale = (byte)(flags >> 16);
+
+ return new decimal(lo, mid, hi, isNegative, scale);
+ }
+ finally
+ {
+ if (pointer != null)
+ {
+ _buffer.ReleasePointer();
+ }
+ }
+ }
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Single ReadSingle(Int64 position) {
int sizeOfType = sizeof(Single);
EnsureSafeToRead(position, sizeOfType);
@@ -329,7 +364,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- result = *((Single*)(pointer));
+ result = BitConverter.Int32BitsToSingle(*((int*)(pointer)));
#if ALIGN_ACCESS
}
else {
@@ -348,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);
@@ -365,7 +399,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- result = *((Double*)(pointer));
+ result = BitConverter.Int64BitsToDouble(*((long*)(pointer)));
#if ALIGN_ACCESS
}
else {
@@ -388,7 +422,6 @@ namespace System.IO {
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public SByte ReadSByte(Int64 position) {
int sizeOfType = sizeof(SByte);
@@ -413,7 +446,6 @@ namespace System.IO {
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public UInt16 ReadUInt16(Int64 position) {
int sizeOfType = sizeof(UInt16);
@@ -450,7 +482,6 @@ namespace System.IO {
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public UInt32 ReadUInt32(Int64 position) {
int sizeOfType = sizeof(UInt32);
@@ -487,7 +518,6 @@ namespace System.IO {
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public UInt64 ReadUInt64(Int64 position) {
int sizeOfType = sizeof(UInt64);
@@ -540,10 +570,9 @@ 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("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -557,10 +586,10 @@ namespace System.IO {
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
if (position > _capacity - sizeOfT) {
if (position >= _capacity) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead", typeof(T).FullName), "position");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead", typeof(T).FullName), nameof(position));
}
}
@@ -573,16 +602,15 @@ 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("array", "Buffer cannot be null.");
+ throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
}
if (offset < 0) {
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (count < 0) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (array.Length - offset < count) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds"));
@@ -597,14 +625,14 @@ namespace System.IO {
}
}
if (position < 0) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
UInt32 sizeOfT = Marshal.AlignedSizeOf<T>();
// only check position and ask for fewer Ts if count is too big
if (position >= _capacity) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
int n = count;
@@ -647,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);
@@ -682,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);
@@ -716,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);
@@ -751,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);
@@ -789,28 +813,56 @@ namespace System.IO {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private unsafe void UnsafeWriteInt32(byte* pointer, Int32 value)
+ {
+ // check if pointer is aligned
+ if (((int)pointer & (sizeof(Int32) - 1)) == 0)
+ {
+ *((Int32*)pointer) = value;
+ }
+ else
+ {
+ *(pointer) = (byte)value;
+ *(pointer + 1) = (byte)(value >> 8);
+ *(pointer + 2) = (byte)(value >> 16);
+ *(pointer + 3) = (byte)(value >> 24);
+ }
+ }
+
public void Write(Int64 position, Decimal value) {
int sizeOfType = sizeof(Decimal);
EnsureSafeToWrite(position, sizeOfType);
- byte[] decimalArray = new byte[16];
- Decimal.GetBytes(value, decimalArray);
+ unsafe
+ {
+ byte* pointer = null;
+ try
+ {
+ _buffer.AcquirePointer(ref pointer);
+ pointer += (_offset + position);
- int[] bits = new int[4];
- int flags = ((int)decimalArray[12]) | ((int)decimalArray[13] << 8) | ((int)decimalArray[14] << 16) | ((int)decimalArray[15] << 24);
- int lo = ((int)decimalArray[0]) | ((int)decimalArray[1] << 8) | ((int)decimalArray[2] << 16) | ((int)decimalArray[3] << 24);
- int mid = ((int)decimalArray[4]) | ((int)decimalArray[5] << 8) | ((int)decimalArray[6] << 16) | ((int)decimalArray[7] << 24);
- int hi = ((int)decimalArray[8]) | ((int)decimalArray[9] << 8) | ((int)decimalArray[10] << 16) | ((int)decimalArray[11] << 24);
- bits[0] = lo;
- bits[1] = mid;
- bits[2] = hi;
- bits[3] = flags;
+ int* valuePtr = (int*)(&value);
+ int flags = *valuePtr;
+ int hi = *(valuePtr + 1);
+ int lo = *(valuePtr + 2);
+ int mid = *(valuePtr + 3);
- WriteArray<int>(position, bits, 0, bits.Length);
+ UnsafeWriteInt32(pointer, lo);
+ UnsafeWriteInt32(pointer + 4, mid);
+ UnsafeWriteInt32(pointer + 8, hi);
+ UnsafeWriteInt32(pointer + 12, flags);
+ }
+ finally
+ {
+ if (pointer != null)
+ {
+ _buffer.ReleasePointer();
+ }
+ }
+ }
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Write(Int64 position, Single value) {
int sizeOfType = sizeof(Single);
EnsureSafeToWrite(position, sizeOfType);
@@ -825,7 +877,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- *((Single*)pointer) = value;
+ *((int*)pointer) = BitConverter.SingleToInt32Bits(value);
#if ALIGN_ACCESS
}
else {
@@ -846,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);
@@ -861,7 +912,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- *((Double*)pointer) = value;
+ *((long*)pointer) = BitConverter.DoubleToInt64Bits(value);
#if ALIGN_ACCESS
}
else {
@@ -886,7 +937,6 @@ namespace System.IO {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public void Write(Int64 position, SByte value) {
int sizeOfType = sizeof(SByte);
@@ -908,7 +958,6 @@ namespace System.IO {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public void Write(Int64 position, UInt16 value) {
int sizeOfType = sizeof(UInt16);
@@ -942,7 +991,6 @@ namespace System.IO {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public void Write(Int64 position, UInt32 value) {
int sizeOfType = sizeof(UInt32);
@@ -979,7 +1027,6 @@ namespace System.IO {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public void Write(Int64 position, UInt64 value) {
int sizeOfType = sizeof(UInt64);
@@ -1024,10 +1071,9 @@ 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("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -1041,10 +1087,10 @@ namespace System.IO {
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
if (position > _capacity - sizeOfT) {
if (position >= _capacity) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", typeof(T).FullName), "position");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", typeof(T).FullName), nameof(position));
}
}
@@ -1054,25 +1100,24 @@ 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("array", "Buffer cannot be null.");
+ throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
}
if (offset < 0) {
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (count < 0) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (array.Length - offset < count) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds"));
}
if (position < 0) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (position >= Capacity) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
Contract.EndContractBlock();
@@ -1086,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 {
@@ -1109,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 writeable");
- 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;
@@ -1138,15 +1181,15 @@ namespace System.IO {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
}
if (position < 0) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (position > _capacity - sizeOfType) {
if (position >= _capacity) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead"), "position");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead"), nameof(position));
}
}
}
@@ -1159,15 +1202,15 @@ namespace System.IO {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing"));
}
if (position < 0) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (position > _capacity - sizeOfType) {
if (position >= _capacity) {
- throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", "Byte"), "position");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", nameof(Byte)), nameof(position));
}
}
}
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
index 6b506ea5b1..d78632639b 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
@@ -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;
@@ -43,7 +44,7 @@ namespace System.IO {
*
* It may become necessary to add in some sort of
* DeallocationMode enum, specifying whether we unmap a section of memory,
- * call free, run a user-provided delegate to free the memory, etc etc.
+ * call free, run a user-provided delegate to free the memory, etc.
* We'll suggest user write a subclass of UnmanagedMemoryStream that uses
* a SafeHandle subclass to hold onto the memory.
* Check for problems when using this in the negative parts of a
@@ -76,7 +77,7 @@ namespace System.IO {
* a. a race condition in WriteX that could have allowed a thread to
* read from unzeroed memory was fixed
* b. memory region cannot be expanded beyond _capacity; in other
- * words, a UMS creator is saying a writeable UMS is safe to
+ * words, a UMS creator is saying a writable UMS is safe to
* write to anywhere in the memory range up to _capacity, specified
* in the ctor. Even if the caller doesn't specify a capacity, then
* length is used as the capacity.
@@ -85,22 +86,19 @@ 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;
private long _position;
private long _offset;
private FileAccess _access;
- internal bool _isOpen;
+ internal bool _isOpen;
[NonSerialized]
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
// Needed for subclasses that need to map a file, etc.
- [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,32 +118,29 @@ 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("buffer");
+ throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0) {
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (length < 0) {
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (buffer.ByteLength < (ulong)(offset + length)) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen"));
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
- throw new ArgumentOutOfRangeException("access");
+ throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
@@ -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,41 +193,39 @@ 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)
- throw new ArgumentNullException("pointer");
+ throw new ArgumentNullException(nameof(pointer));
if (length < 0 || capacity < 0)
- throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (length > capacity)
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
Contract.EndContractBlock();
// Check for wraparound.
if (((byte*) ((long)pointer + capacity)) < pointer)
- throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
+ throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
- throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(access), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
if (_isOpen)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
- if (!skipSecurityCheck)
+ if (!skipSecurityCheck) {
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
+ }
_mem = pointer;
_offset = 0;
@@ -261,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;
@@ -277,7 +265,6 @@ namespace System.IO {
if (!_isOpen) __Error.StreamIsClosed();
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
@@ -316,10 +303,9 @@ namespace System.IO {
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
- [System.Security.SecuritySafeCritical] // auto-generated
set {
if (value < 0)
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (!CanSeek) __Error.StreamIsClosed();
@@ -327,7 +313,7 @@ namespace System.IO {
unsafe {
// On 32 bit machines, ensure we don't wrap around.
if (value > (long) Int32.MaxValue || _mem + value < _mem)
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
#endif
Interlocked.Exchange(ref _position, value);
@@ -336,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"));
@@ -350,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"));
@@ -368,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"));
@@ -377,14 +360,13 @@ 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("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync
@@ -404,42 +386,49 @@ namespace System.IO {
int nInt = (int) n; // Safe because n <= count, which is an Int32
if (nInt < 0)
- nInt = 0; // _position could be beyond EOF
- Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
-
- if (_buffer != null) {
- unsafe {
- byte* pointer = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- _buffer.AcquirePointer(ref pointer);
- Buffer.Memcpy(buffer, offset, pointer + pos + _offset, 0, nInt);
- }
- finally {
- if (pointer != null) {
- _buffer.ReleasePointer();
+ return 0; // _position could be beyond EOF
+ Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
+
+ unsafe
+ {
+ fixed (byte* pBuffer = buffer)
+ {
+ if (_buffer != null)
+ {
+ byte* pointer = null;
+
+ RuntimeHelpers.PrepareConstrainedRegions();
+ try
+ {
+ _buffer.AcquirePointer(ref pointer);
+ Buffer.Memcpy(pBuffer + offset, pointer + pos + _offset, nInt);
+ }
+ finally
+ {
+ if (pointer != null)
+ {
+ _buffer.ReleasePointer();
+ }
}
}
- }
- }
- else {
- unsafe {
- Buffer.Memcpy(buffer, offset, _mem + pos, 0, nInt);
+ else
+ {
+ Buffer.Memcpy(pBuffer + offset, _mem + pos, nInt);
+ }
}
}
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
@@ -455,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();
@@ -497,7 +485,7 @@ namespace System.IO {
public override long Seek(long offset, SeekOrigin loc) {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > UnmanagedMemStreamMaxLength)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
switch(loc) {
case SeekOrigin.Begin:
if (offset < 0)
@@ -524,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"));
@@ -554,14 +541,13 @@ namespace System.IO {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..)
@@ -595,46 +581,52 @@ namespace System.IO {
}
}
- if (_buffer != null) {
-
- long bytesLeft = _capacity - pos;
- if (bytesLeft < count) {
- throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
- }
+ unsafe
+ {
+ fixed (byte* pBuffer = buffer)
+ {
+ if (_buffer != null)
+ {
+ long bytesLeft = _capacity - pos;
+ if (bytesLeft < count)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
+ }
- unsafe {
- byte* pointer = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- _buffer.AcquirePointer(ref pointer);
- Buffer.Memcpy(pointer + pos + _offset, 0, buffer, offset, count);
- }
- finally {
- if (pointer != null) {
- _buffer.ReleasePointer();
+ byte* pointer = null;
+ RuntimeHelpers.PrepareConstrainedRegions();
+ try
+ {
+ _buffer.AcquirePointer(ref pointer);
+ Buffer.Memcpy(pointer + pos + _offset, pBuffer + offset, count);
+ }
+ finally
+ {
+ if (pointer != null)
+ {
+ _buffer.ReleasePointer();
+ }
}
}
- }
- }
- else {
- unsafe {
- Buffer.Memcpy(_mem + pos, 0, buffer, offset, count);
+ else
+ {
+ Buffer.Memcpy(_mem + pos, pBuffer + offset, count);
+ }
}
}
Interlocked.Exchange(ref _position, n);
return;
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
- throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(..)
@@ -649,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();
@@ -674,7 +665,7 @@ namespace System.IO {
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
- if (_buffer == null) {
+ if (_buffer == null) {
if (pos > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, pos-len);
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
index 5727eeddf5..040ddbb3d7 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
@@ -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();
@@ -127,7 +126,7 @@ namespace System.IO {
// Writes this MemoryStream to another stream.
public unsafe override void WriteTo(Stream stream) {
if (stream==null)
- throw new ArgumentNullException("stream", Environment.GetResourceString("ArgumentNull_Stream"));
+ throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
Contract.EndContractBlock();
if (!_unmanagedStream._isOpen) __Error.StreamIsClosed();
@@ -151,16 +150,16 @@ namespace System.IO {
// The parameter checks must be in sync with the base version:
if (destination == null)
- throw new ArgumentNullException("destination");
+ throw new ArgumentNullException(nameof(destination));
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
if (!CanRead && !CanWrite)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
if (!destination.CanRead && !destination.CanWrite)
- throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+ throw new ObjectDisposedException(nameof(destination), Environment.GetResourceString("ObjectDisposed_StreamClosed"));
if (!CanRead)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
diff --git a/src/mscorlib/src/System/IO/__DebugOutputTextWriter.cs b/src/mscorlib/src/System/IO/__DebugOutputTextWriter.cs
deleted file mode 100644
index 621bc41b4b..0000000000
--- a/src/mscorlib/src/System/IO/__DebugOutputTextWriter.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-#if _DEBUG
-// This class writes to wherever OutputDebugString writes to. If you don't have
-// a Windows app (ie, something hosted in IE), you can use this to redirect Console
-// output for some good old-fashioned console spew in MSDEV's debug output window.
-
-using System;
-using System.IO;
-using System.Text;
-using System.Security;
-using System.Runtime.InteropServices;
-using System.Runtime.Versioning;
-using Microsoft.Win32;
-using System.Globalization;
-
-namespace System.IO {
- internal class __DebugOutputTextWriter : TextWriter {
- private readonly String _consoleType;
-
- internal __DebugOutputTextWriter(String consoleType): base(CultureInfo.InvariantCulture)
- {
- _consoleType = consoleType;
- }
-
- public override Encoding Encoding {
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
- get {
- if (Marshal.SystemDefaultCharSize == 1)
- return Encoding.Default;
- else
- return new UnicodeEncoding(false, false);
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override void Write(char c)
- {
- OutputDebugString(c.ToString());
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override void Write(String str)
- {
- OutputDebugString(str);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override void Write(char[] array)
- {
- if (array != null)
- OutputDebugString(new String(array));
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override void WriteLine(String str)
- {
- if (str != null)
- OutputDebugString(_consoleType + str);
- else
- OutputDebugString("<null>");
- OutputDebugString(new String(CoreNewLine));
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(Win32Native.KERNEL32, CharSet=CharSet.Auto)]
- [SuppressUnmanagedCodeSecurityAttribute()]
- private static extern void OutputDebugString(String output);
- }
-}
-
-#endif // _DEBUG
diff --git a/src/mscorlib/src/System/IO/__Error.cs b/src/mscorlib/src/System/IO/__Error.cs
index a31d9657e8..ad4972de54 100644
--- a/src/mscorlib/src/System/IO/__Error.cs
+++ b/src/mscorlib/src/System/IO/__Error.cs
@@ -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)
{
@@ -85,7 +84,7 @@ namespace System.IO {
bool isFullyQualified = false;
if (path.Length < 2)
return path;
- if (Path.IsDirectorySeparator(path[0]) && Path.IsDirectorySeparator(path[1]))
+ if (PathInternal.IsDirectorySeparator(path[0]) && PathInternal.IsDirectorySeparator(path[1]))
isFullyQualified = true;
else if (path[1] == Path.VolumeSeparatorChar) {
isFullyQualified = true;
@@ -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;
}
}
@@ -116,7 +112,7 @@ namespace System.IO {
}
if (!safeToReturn) {
- if (Path.IsDirectorySeparator(path[path.Length - 1]))
+ if (PathInternal.IsDirectorySeparator(path[path.Length - 1]))
path = Environment.GetResourceString("IO.IO_NoPermissionToDirectoryName");
else
path = Path.GetFileName(path);
@@ -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) {
diff --git a/src/mscorlib/src/System/Int16.cs b/src/mscorlib/src/System/Int16.cs
index 0adc64cd13..f02a5f2cda 100644
--- a/src/mscorlib/src/System/Int16.cs
+++ b/src/mscorlib/src/System/Int16.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Int32.cs b/src/mscorlib/src/System/Int32.cs
index 778a893672..2da55bf089 100644
--- a/src/mscorlib/src/System/Int32.cs
+++ b/src/mscorlib/src/System/Int32.cs
@@ -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));
diff --git a/src/mscorlib/src/System/Int64.cs b/src/mscorlib/src/System/Int64.cs
index 0cd2558997..e5fcf86c3b 100644
--- a/src/mscorlib/src/System/Int64.cs
+++ b/src/mscorlib/src/System/Int64.cs
@@ -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));
diff --git a/src/mscorlib/src/System/IntPtr.cs b/src/mscorlib/src/System/IntPtr.cs
index c7eea36447..2d66652ab8 100644
--- a/src/mscorlib/src/System/IntPtr.cs
+++ b/src/mscorlib/src/System/IntPtr.cs
@@ -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,10 +78,9 @@ namespace System {
m_value = (void *)l;
}
- [System.Security.SecurityCritical]
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
#if BIT64
@@ -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]
diff --git a/src/mscorlib/src/System/Internal.cs b/src/mscorlib/src/System/Internal.cs
index c6be49f83f..0eb2bced72 100644
--- a/src/mscorlib/src/System/Internal.cs
+++ b/src/mscorlib/src/System/Internal.cs
@@ -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>();
diff --git a/src/mscorlib/src/System/InvalidTimeZoneException.cs b/src/mscorlib/src/System/InvalidTimeZoneException.cs
index 2c57bc8341..f33475497a 100644
--- a/src/mscorlib/src/System/InvalidTimeZoneException.cs
+++ b/src/mscorlib/src/System/InvalidTimeZoneException.cs
@@ -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) { }
diff --git a/src/mscorlib/src/System/Lazy.cs b/src/mscorlib/src/System/Lazy.cs
index 883979ef56..85cbb9816a 100644
--- a/src/mscorlib/src/System/Lazy.cs
+++ b/src/mscorlib/src/System/Lazy.cs
@@ -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);
};
@@ -207,7 +204,7 @@ namespace System
public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode)
{
if (valueFactory == null)
- throw new ArgumentNullException("valueFactory");
+ throw new ArgumentNullException(nameof(valueFactory));
m_threadSafeObj = GetObjectFromMode(mode);
m_valueFactory = valueFactory;
@@ -223,7 +220,7 @@ namespace System
else if (mode == LazyThreadSafetyMode.PublicationOnly)
return LazyHelpers.PUBLICATION_ONLY_SENTINEL;
else if (mode != LazyThreadSafetyMode.None)
- throw new ArgumentOutOfRangeException("mode", Environment.GetResourceString("Lazy_ctor_ModeInvalid"));
+ throw new ArgumentOutOfRangeException(nameof(mode), Environment.GetResourceString("Lazy_ctor_ModeInvalid"));
return null; // None mode
}
@@ -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;
}
diff --git a/src/mscorlib/src/System/LowLevelConsole.cs b/src/mscorlib/src/System/LowLevelConsole.cs
index 3aba3db4d1..316583e276 100644
--- a/src/mscorlib/src/System/LowLevelConsole.cs
+++ b/src/mscorlib/src/System/LowLevelConsole.cs
@@ -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);
diff --git a/src/mscorlib/src/System/MarshalByRefObject.cs b/src/mscorlib/src/System/MarshalByRefObject.cs
index 4948a4316d..53ebda7672 100644
--- a/src/mscorlib/src/System/MarshalByRefObject.cs
+++ b/src/mscorlib/src/System/MarshalByRefObject.cs
@@ -13,250 +13,25 @@
**
**
===========================================================*/
-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)
+ protected MarshalByRefObject() { }
+ public object GetLifetimeService()
{
- return T.IsInstanceOfType(this);
+ throw new PlatformNotSupportedException();
}
-
- // 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)
+ public virtual object InitializeLifetimeService()
{
- 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);
+ throw new PlatformNotSupportedException();
}
-
- // 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("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
-
-#endif // FEATURE_REMOTING
- }
-} // namespace
+ }
+}
diff --git a/src/mscorlib/src/System/Math.cs b/src/mscorlib/src/System/Math.cs
index 4e280d5fd9..3ac1f0694a 100644
--- a/src/mscorlib/src/System/Math.cs
+++ b/src/mscorlib/src/System/Math.cs
@@ -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,33 +83,27 @@ 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);
public static double Round(double value, int digits)
{
if ((digits < 0) || (digits > maxRoundingDigits))
- throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
+ throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
Contract.EndContractBlock();
return InternalRound(value, digits, MidpointRounding.ToEven);
}
@@ -129,9 +114,9 @@ namespace System {
public static double Round(double value, int digits, MidpointRounding mode) {
if ((digits < 0) || (digits > maxRoundingDigits))
- throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
+ throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, "MidpointRounding"), "mode");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, nameof(MidpointRounding)), nameof(mode));
}
Contract.EndContractBlock();
return InternalRound(value, digits, mode);
@@ -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
@@ -476,7 +453,151 @@ namespace System {
public static Decimal Min(Decimal val1, Decimal val2) {
return Decimal.Min(val1,val2);
}
-
+
+ /*=====================================Clamp====================================
+ **
+ ==============================================================================*/
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Byte Clamp(Byte value, Byte min, Byte max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Decimal Clamp(Decimal value, Decimal min, Decimal max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Double Clamp(Double value, Double min, Double max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Int16 Clamp(Int16 value, Int16 min, Int16 max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Int32 Clamp(Int32 value, Int32 min, Int32 max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Int64 Clamp(Int64 value, Int64 min, Int64 max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [CLSCompliant(false)]
+ public static SByte Clamp(SByte value, SByte min, SByte max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Single Clamp(Single value, Single min, Single max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [CLSCompliant(false)]
+ public static UInt16 Clamp(UInt16 value, UInt16 min, UInt16 max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [CLSCompliant(false)]
+ public static UInt32 Clamp(UInt32 value, UInt32 min, UInt32 max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [CLSCompliant(false)]
+ public static UInt64 Clamp(UInt64 value, UInt64 min, UInt64 max)
+ {
+ if (min > max)
+ ThrowMinMaxException(min, max);
+ if (value < min)
+ return min;
+ else if (value > max)
+ return max;
+ return value;
+ }
+
+ private static void ThrowMinMaxException<T>(T min, T max)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_MinMaxValue", min, max));
+ }
+
/*=====================================Log======================================
**
==============================================================================*/
@@ -582,13 +703,21 @@ namespace System {
}
public static int DivRem(int a, int b, out int result) {
- result = a%b;
- return a/b;
+ // TODO https://github.com/dotnet/coreclr/issues/3439:
+ // Restore to using % and / when the JIT is able to eliminate one of the idivs.
+ // In the meantime, a * and - is measurably faster than an extra /.
+ int div = a / b;
+ result = a - (div * b);
+ return div;
}
public static long DivRem(long a, long b, out long result) {
- result = a%b;
- return a/b;
+ // TODO https://github.com/dotnet/coreclr/issues/3439:
+ // Restore to using % and / when the JIT is able to eliminate one of the idivs.
+ // In the meantime, a * and - is measurably faster than an extra /.
+ long div = a / b;
+ result = a - (div * b);
+ return div;
}
}
}
diff --git a/src/mscorlib/src/System/MathF.cs b/src/mscorlib/src/System/MathF.cs
new file mode 100644
index 0000000000..fb800924b5
--- /dev/null
+++ b/src/mscorlib/src/System/MathF.cs
@@ -0,0 +1,253 @@
+// 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: Some single-precision floating-point math operations
+**
+===========================================================*/
+namespace System {
+
+ //This class contains only static members and doesn't require serialization.
+ using System;
+ using System.Runtime;
+ using System.Runtime.CompilerServices;
+ using System.Runtime.ConstrainedExecution;
+ using System.Runtime.Versioning;
+ using System.Diagnostics.Contracts;
+
+ public static class MathF
+ {
+ private static float singleRoundLimit = 1e8f;
+
+ private const int maxRoundingDigits = 6;
+
+ // This table is required for the Round function which can specify the number of digits to round to
+ private static float[] roundPower10Single = new float[] {
+ 1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f
+ };
+
+ public const float PI = 3.14159265f;
+
+ public const float E = 2.71828183f;
+
+ public static float Abs(float x) => Math.Abs(x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Acos(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Asin(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Atan(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Atan2(float y, float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Ceiling(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Cos(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Cosh(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Exp(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Floor(float x);
+
+ public static float IEEERemainder(float x, float y)
+ {
+ if (float.IsNaN(x))
+ {
+ return x; // IEEE 754-2008: NaN payload must be preserved
+ }
+
+ if (float.IsNaN(y))
+ {
+ return y; // IEEE 754-2008: NaN payload must be preserved
+ }
+
+ var regularMod = x % y;
+
+ if (float.IsNaN(regularMod))
+ {
+ return float.NaN;
+ }
+
+ if ((regularMod == 0) && float.IsNegative(x))
+ {
+ return float.NegativeZero;
+ }
+
+ var alternativeResult = (regularMod - (Abs(y) * Sign(x)));
+
+ if (Abs(alternativeResult) == Abs(regularMod))
+ {
+ var divisionResult = x / y;
+ var roundedResult = Round(divisionResult);
+
+ if (Abs(roundedResult) > Abs(divisionResult))
+ {
+ return alternativeResult;
+ }
+ else
+ {
+ return regularMod;
+ }
+ }
+
+ if (Abs(alternativeResult) < Abs(regularMod))
+ {
+ return alternativeResult;
+ }
+ else
+ {
+ return regularMod;
+ }
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Log(float x);
+
+ public static float Log(float x, float y)
+ {
+ if (float.IsNaN(x))
+ {
+ return x; // IEEE 754-2008: NaN payload must be preserved
+ }
+
+ if (float.IsNaN(y))
+ {
+ return y; // IEEE 754-2008: NaN payload must be preserved
+ }
+
+ if (y == 1)
+ {
+ return float.NaN;
+ }
+
+ if ((x != 1) && ((y == 0) || float.IsPositiveInfinity(y)))
+ {
+ return float.NaN;
+ }
+
+ return Log(x) / Log(y);
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Log10(float x);
+
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+ public static float Max(float x, float y) => Math.Max(x, y);
+
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+ public static float Min(float x, float y) => Math.Min(x, y);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Pow(float x, float y);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Round(float x);
+
+ public static float Round(float x, int digits)
+ {
+ if ((digits < 0) || (digits > maxRoundingDigits))
+ {
+ throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
+ }
+ Contract.EndContractBlock();
+
+ return InternalRound(x, digits, MidpointRounding.ToEven);
+ }
+
+ public static float Round(float x, int digits, MidpointRounding mode)
+ {
+ if ((digits < 0) || (digits > maxRoundingDigits))
+ {
+ throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
+ }
+
+ if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumx", mode, nameof(MidpointRounding)), nameof(mode));
+ }
+ Contract.EndContractBlock();
+
+ return InternalRound(x, digits, mode);
+ }
+
+ public static float Round(float x, MidpointRounding mode)
+ {
+ if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumx", mode, nameof(MidpointRounding)), nameof(mode));
+ }
+ Contract.EndContractBlock();
+
+ return InternalRound(x, 0, mode);
+ }
+
+ public static int Sign(float x) => Math.Sign(x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Sin(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Sinh(float x);
+
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Sqrt(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Tan(float x);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern float Tanh(float x);
+
+ public static float Truncate(float x) => InternalTruncate(x);
+
+ private static unsafe float InternalRound(float x, int digits, MidpointRounding mode)
+ {
+ if (Abs(x) < singleRoundLimit)
+ {
+ var power10 = roundPower10Single[digits];
+
+ x *= power10;
+
+ if (mode == MidpointRounding.AwayFromZero)
+ {
+ var fraction = SplitFractionSingle(&x);
+
+ if (Abs(fraction) >= 0.5f)
+ {
+ x += Sign(fraction);
+ }
+ }
+ else
+ {
+ x = Round(x);
+ }
+
+ x /= power10;
+ }
+
+ return x;
+ }
+
+ private unsafe static float InternalTruncate(float x)
+ {
+ SplitFractionSingle(&x);
+ return x;
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private static unsafe extern float SplitFractionSingle(float* x);
+ }
+}
diff --git a/src/mscorlib/src/System/MissingFieldException.cs b/src/mscorlib/src/System/MissingFieldException.cs
index 4196ea8f6b..d96d0378e3 100644
--- a/src/mscorlib/src/System/MissingFieldException.cs
+++ b/src/mscorlib/src/System/MissingFieldException.cs
@@ -39,7 +39,6 @@ namespace System {
public override String Message
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (ClassName == null) {
return base.Message;
diff --git a/src/mscorlib/src/System/MissingMemberException.cs b/src/mscorlib/src/System/MissingMemberException.cs
index 30ce5b8fd0..ab773dc467 100644
--- a/src/mscorlib/src/System/MissingMemberException.cs
+++ b/src/mscorlib/src/System/MissingMemberException.cs
@@ -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,10 +80,9 @@ namespace System {
MemberName = memberName;
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
base.GetObjectData(info, context);
diff --git a/src/mscorlib/src/System/MissingMethodException.cs b/src/mscorlib/src/System/MissingMethodException.cs
index cba33efa0f..79434900a1 100644
--- a/src/mscorlib/src/System/MissingMethodException.cs
+++ b/src/mscorlib/src/System/MissingMethodException.cs
@@ -41,7 +41,6 @@ namespace System {
public override String Message
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (ClassName == null) {
return base.Message;
diff --git a/src/mscorlib/src/System/MulticastDelegate.cs b/src/mscorlib/src/System/MulticastDelegate.cs
index f59db16850..a7b244cdae 100644
--- a/src/mscorlib/src/System/MulticastDelegate.cs
+++ b/src/mscorlib/src/System/MulticastDelegate.cs
@@ -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)
{
diff --git a/src/mscorlib/src/System/NotFiniteNumberException.cs b/src/mscorlib/src/System/NotFiniteNumberException.cs
index a3d455aac6..3a896ce548 100644
--- a/src/mscorlib/src/System/NotFiniteNumberException.cs
+++ b/src/mscorlib/src/System/NotFiniteNumberException.cs
@@ -57,10 +57,9 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
base.GetObjectData(info, context);
diff --git a/src/mscorlib/src/System/Nullable.cs b/src/mscorlib/src/System/Nullable.cs
index 2091e20af3..8a22c8e65c 100644
--- a/src/mscorlib/src/System/Nullable.cs
+++ b/src/mscorlib/src/System/Nullable.cs
@@ -130,7 +130,7 @@ namespace System
// Otherwise, returns the underlying type of the Nullable type
public static Type GetUnderlyingType(Type nullableType) {
if((object)nullableType == null) {
- throw new ArgumentNullException("nullableType");
+ throw new ArgumentNullException(nameof(nullableType));
}
Contract.EndContractBlock();
Type result = null;
diff --git a/src/mscorlib/src/System/Number.cs b/src/mscorlib/src/System/Number.cs
index 3c1215d418..3412c02c31 100644
--- a/src/mscorlib/src/System/Number.cs
+++ b/src/mscorlib/src/System/Number.cs
@@ -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,32 +590,29 @@ 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;
}
- for (; (*str != '\0'); p++, str++) {
- if (*p != *str) { //We only hurt the failure case
- if ((*str == '\u00A0') && (*p == '\u0020')) {// This fix is for French or Kazakh cultures. Since a user cannot type 0xA0 as a
- // space character we use 0x20 space character instead to mean the same.
- continue;
- }
- return null;
- }
+ // We only hurt the failure case
+ // This fix is for French or Kazakh cultures. Since a user cannot type 0xA0 as a
+ // space character we use 0x20 space character instead to mean the same.
+ while (*p == *str || (*str == '\u00a0' && *p == '\u0020'))
+ {
+ p++;
+ str++;
+ if (*str == '\0') return p;
}
- return p;
+ 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,10 +627,9 @@ 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("value");
+ throw new ArgumentNullException(nameof(value));
}
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -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;
@@ -742,26 +716,12 @@ namespace System {
string groupSep; // group separator from NumberFormatInfo.
string currSymbol = null; // currency symbol from NumberFormatInfo.
- // The alternative currency symbol used in ANSI codepage, that can not roundtrip between ANSI and Unicode.
- // Currently, only ja-JP and ko-KR has non-null values (which is U+005c, backslash)
- string ansicurrSymbol = null; // currency symbol from NumberFormatInfo.
- string altdecSep = null; // decimal separator from NumberFormatInfo as a decimal
- string altgroupSep = null; // group separator from NumberFormatInfo as a decimal
-
Boolean parsingCurrency = false;
if ((options & NumberStyles.AllowCurrencySymbol) != 0) {
currSymbol = numfmt.CurrencySymbol;
-#if !FEATURE_COREFX_GLOBALIZATION
- if (numfmt.ansiCurrencySymbol != null) {
- ansicurrSymbol = numfmt.ansiCurrencySymbol;
- }
-#endif
-
// The idea here is to match the currency separators and on failure match the number separators to keep the perf of VB's IsNumeric fast.
// The values of decSep are setup to use the correct relevant separator (currency in the if part and decimal in the else part).
- altdecSep = numfmt.NumberDecimalSeparator;
- altgroupSep = numfmt.NumberGroupSeparator;
decSep = numfmt.CurrencyDecimalSeparator;
groupSep = numfmt.CurrencyGroupSeparator;
parsingCurrency = true;
@@ -772,9 +732,7 @@ namespace System {
}
Int32 state = 0;
- Boolean signflag = false; // Cache the results of "options & PARSE_LEADINGSIGN && !(state & STATE_SIGN)" to avoid doing this twice
Boolean bigNumber = (sb != null); // When a StringBuilder is provided then we use it in place of the number.digits char[50]
- Boolean bigNumberHex = (bigNumber && ((options & NumberStyles.AllowHexSpecifier) != 0));
Int32 maxParseDigits = bigNumber ? Int32.MaxValue : NumberMaxDigits;
char* p = str;
@@ -784,32 +742,26 @@ namespace System {
while (true) {
// Eat whitespace unless we've found a sign which isn't followed by a currency symbol.
// "-Kr 1231.47" is legal but "- 1231.47" is not.
- if (IsWhite(ch) && ((options & NumberStyles.AllowLeadingWhite) != 0) && (((state & StateSign) == 0) || (((state & StateSign) != 0) && (((state & StateCurrency) != 0) || numfmt.numberNegativePattern == 2)))) {
- // Do nothing here. We will increase p at the end of the loop.
- }
- else if ((signflag = (((options & NumberStyles.AllowLeadingSign) != 0) && ((state & StateSign) == 0))) && ((next = MatchChars(p, numfmt.positiveSign)) != null)) {
- state |= StateSign;
- p = next - 1;
- } else if (signflag && (next = MatchChars(p, numfmt.negativeSign)) != null) {
- state |= StateSign;
- number.sign = true;
- p = next - 1;
- }
- else if (ch == '(' && ((options & NumberStyles.AllowParentheses) != 0) && ((state & StateSign) == 0)) {
- state |= StateSign | StateParens;
- number.sign = true;
- }
- else if ((currSymbol != null && (next = MatchChars(p, currSymbol)) != null) || (ansicurrSymbol != null && (next = MatchChars(p, ansicurrSymbol)) != null)) {
- state |= StateCurrency;
- currSymbol = null;
- ansicurrSymbol = null;
- // We already found the currency symbol. There should not be more currency symbols. Set
- // currSymbol to NULL so that we won't search it again in the later code path.
- p = next - 1;
- }
- else {
- break;
- }
+ if (!IsWhite(ch) || (options & NumberStyles.AllowLeadingWhite) == 0 || ((state & StateSign) != 0 && ((state & StateCurrency) == 0 && numfmt.NumberNegativePattern != 2))){
+ if ((((options & NumberStyles.AllowLeadingSign) != 0) && (state & StateSign) == 0) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || ((next = MatchChars(p, numfmt.NegativeSign)) != null && (number.sign = true)))){
+ state |= StateSign;
+ p = next - 1;
+ }
+ else if (ch == '(' && ((options & NumberStyles.AllowParentheses) != 0) && ((state & StateSign) == 0)) {
+ state |= StateSign | StateParens;
+ number.sign = true;
+ }
+ else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null) {
+ state |= StateCurrency;
+ currSymbol = null;
+ // We already found the currency symbol. There should not be more currency symbols. Set
+ // currSymbol to NULL so that we won't search it again in the later code path.
+ p = next - 1;
+ }
+ else {
+ break;
+ }
+ }
ch = *++p;
}
Int32 digCount = 0;
@@ -818,7 +770,7 @@ namespace System {
if ((ch >= '0' && ch <= '9') || (((options & NumberStyles.AllowHexSpecifier) != 0) && ((ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')))) {
state |= StateDigits;
- if (ch != '0' || (state & StateNonZero) != 0 || bigNumberHex) {
+ if (ch != '0' || (state & StateNonZero) != 0 || (bigNumber && ((options & NumberStyles.AllowHexSpecifier) != 0))) {
if (digCount < maxParseDigits) {
if (bigNumber)
sb.Append(ch);
@@ -837,11 +789,11 @@ namespace System {
number.scale--;
}
}
- else if (((options & NumberStyles.AllowDecimalPoint) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, decSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, altdecSep)) != null)) {
+ else if (((options & NumberStyles.AllowDecimalPoint) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, decSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberDecimalSeparator)) != null)) {
state |= StateDecimal;
p = next - 1;
}
- else if (((options & NumberStyles.AllowThousands) != 0) && ((state & StateDigits) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, groupSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, altgroupSep)) != null)) {
+ else if (((options & NumberStyles.AllowThousands) != 0) && ((state & StateDigits) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, groupSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberGroupSeparator)) != null)) {
p = next - 1;
}
else {
@@ -890,27 +842,22 @@ namespace System {
}
}
while (true) {
- if (IsWhite(ch) && ((options & NumberStyles.AllowTrailingWhite) != 0)) {
- }
- else if ((signflag = (((options & NumberStyles.AllowTrailingSign) != 0) && ((state & StateSign) == 0))) && (next = MatchChars(p, numfmt.positiveSign)) != null) {
- state |= StateSign;
- p = next - 1;
- } else if (signflag && (next = MatchChars(p, numfmt.negativeSign)) != null) {
- state |= StateSign;
- number.sign = true;
- p = next - 1;
- }
- else if (ch == ')' && ((state & StateParens) != 0)) {
- state &= ~StateParens;
- }
- else if ((currSymbol != null && (next = MatchChars(p, currSymbol)) != null) || (ansicurrSymbol != null && (next = MatchChars(p, ansicurrSymbol)) != null)) {
- currSymbol = null;
- ansicurrSymbol = null;
- p = next - 1;
- }
- else {
- break;
- }
+ if (!IsWhite(ch) || (options & NumberStyles.AllowTrailingWhite) == 0){
+ if (((options & NumberStyles.AllowTrailingSign) != 0 && ((state & StateSign) == 0)) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || (((next = MatchChars(p, numfmt.NegativeSign)) != null) && (number.sign = true)))) {
+ state |= StateSign;
+ p = next - 1;
+ }
+ else if (ch == ')' && ((state & StateParens) != 0)) {
+ state &= ~StateParens;
+ }
+ else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null) {
+ currSymbol = null;
+ p = next - 1;
+ }
+ else {
+ break;
+ }
+ }
ch = *++p;
}
if ((state & StateParens) == 0) {
@@ -930,10 +877,9 @@ 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("value");
+ throw new ArgumentNullException(nameof(value));
}
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
@@ -967,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];
@@ -990,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);
@@ -1010,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("String");
+ 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)
@@ -1037,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];
@@ -1054,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);
@@ -1070,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];
@@ -1094,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];
@@ -1118,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);
@@ -1140,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];
@@ -1164,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];
@@ -1192,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;
diff --git a/src/mscorlib/src/System/Numerics/Hashing/HashHelpers.cs b/src/mscorlib/src/System/Numerics/Hashing/HashHelpers.cs
new file mode 100644
index 0000000000..0314d1af3c
--- /dev/null
+++ b/src/mscorlib/src/System/Numerics/Hashing/HashHelpers.cs
@@ -0,0 +1,19 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Numerics.Hashing
+{
+ // Please change the corresponding file in corefx if this is changed.
+
+ internal static class HashHelpers
+ {
+ public static int Combine(int h1, int h2)
+ {
+ // The jit optimizes this to use the ROL instruction on x86
+ // Related GitHub pull request: dotnet/coreclr#1830
+ uint shift5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
+ return ((int)shift5 + h1) ^ h2;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Object.cs b/src/mscorlib/src/System/Object.cs
index 769c5a6bd6..d8d9a0e36c 100644
--- a/src/mscorlib/src/System/Object.cs
+++ b/src/mscorlib/src/System/Object.cs
@@ -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;
}
}
diff --git a/src/mscorlib/src/System/ObjectDisposedException.cs b/src/mscorlib/src/System/ObjectDisposedException.cs
index cf92cef5ee..d2eca37325 100644
--- a/src/mscorlib/src/System/ObjectDisposedException.cs
+++ b/src/mscorlib/src/System/ObjectDisposedException.cs
@@ -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));
diff --git a/src/mscorlib/src/System/OleAutBinder.cs b/src/mscorlib/src/System/OleAutBinder.cs
index 1ed1e32ca9..acae95a214 100644
--- a/src/mscorlib/src/System/OleAutBinder.cs
+++ b/src/mscorlib/src/System/OleAutBinder.cs
@@ -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));
}
}
-
-
}
}
diff --git a/src/mscorlib/src/System/OperatingSystem.cs b/src/mscorlib/src/System/OperatingSystem.cs
index 6955310acf..a11d4bcce8 100644
--- a/src/mscorlib/src/System/OperatingSystem.cs
+++ b/src/mscorlib/src/System/OperatingSystem.cs
@@ -38,11 +38,11 @@ namespace System {
if( platform < PlatformID.Win32S || platform > PlatformID.MacOSX) {
throw new ArgumentException(
Environment.GetResourceString("Arg_EnumIllegalVal", (int)platform),
- "platform");
+ nameof(platform));
}
if ((Object) version == null)
- throw new ArgumentNullException("version");
+ throw new ArgumentNullException(nameof(version));
Contract.EndContractBlock();
_platform = platform;
@@ -71,10 +71,9 @@ namespace System {
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context) {
if( info == null ) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/ParseNumbers.cs b/src/mscorlib/src/System/ParseNumbers.cs
index 01c2ae3019..2a375f7584 100644
--- a/src/mscorlib/src/System/ParseNumbers.cs
+++ b/src/mscorlib/src/System/ParseNumbers.cs
@@ -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);
}
diff --git a/src/mscorlib/src/System/Progress.cs b/src/mscorlib/src/System/Progress.cs
index 8800c0322a..72c43c304d 100644
--- a/src/mscorlib/src/System/Progress.cs
+++ b/src/mscorlib/src/System/Progress.cs
@@ -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);
}
@@ -63,7 +63,7 @@ namespace System
/// <exception cref="System.ArgumentNullException">The <paramref name="handler"/> is null (Nothing in Visual Basic).</exception>
public Progress(Action<T> handler) : this()
{
- if (handler == null) throw new ArgumentNullException("handler");
+ if (handler == null) throw new ArgumentNullException(nameof(handler));
m_handler = handler;
}
diff --git a/src/mscorlib/src/System/Random.cs b/src/mscorlib/src/System/Random.cs
index adede6a101..f5941d6718 100644
--- a/src/mscorlib/src/System/Random.cs
+++ b/src/mscorlib/src/System/Random.cs
@@ -11,13 +11,14 @@
**
===========================================================*/
namespace System {
-
+
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Diagnostics.Contracts;
-[System.Runtime.InteropServices.ComVisible(true)]
+
+ [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class Random {
//
@@ -46,13 +47,19 @@ namespace System {
//
// Constructors
//
-
+
+ /*=========================================================================================
+ **Action: Initializes a new instance of the Random class, using a default seed value
+ ===========================================================================================*/
public Random()
- : this(Environment.TickCount) {
+ : this(GenerateSeed()) {
}
-
+
+ /*=========================================================================================
+ **Action: Initializes a new instance of the Random class, using a specified seed value
+ ===========================================================================================*/
public Random(int Seed) {
- int ii;
+ int ii = 0;
int mj, mk;
//Initialize our Seed array.
@@ -61,7 +68,7 @@ namespace System {
SeedArray[55]=mj;
mk=1;
for (int i=1; i<55; i++) { //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
- ii = (21*i)%55;
+ if ((ii += 21) >= 55) ii -= 55;
SeedArray[ii]=mk;
mk = mj - mk;
if (mk<0) mk+=MBIG;
@@ -69,19 +76,21 @@ namespace System {
}
for (int k=1; k<5; k++) {
for (int i=1; i<56; i++) {
- SeedArray[i] -= SeedArray[1+(i+30)%55];
- if (SeedArray[i]<0) SeedArray[i]+=MBIG;
+ int n = i + 30;
+ if (n >= 55) n -= 55;
+ SeedArray[i] -= SeedArray[1 + n];
+ if (SeedArray[i]<0) SeedArray[i]+=MBIG;
}
}
inext=0;
inextp = 21;
Seed = 1;
}
-
+
//
// Package Private Methods
//
-
+
/*====================================Sample====================================
**Action: Return a new random number [0..1) and reSeed the Seed array.
**Returns: A double [0..1)
@@ -115,11 +124,41 @@ namespace System {
return retVal;
}
+
+ [ThreadStatic]
+ private static Random t_threadRandom;
+ private static readonly Random s_globalRandom = new Random(GenerateGlobalSeed());
+
+ /*=====================================GenerateSeed=====================================
+ **Returns: An integer that can be used as seed values for consecutively
+ creating lots of instances on the same thread within a short period of time.
+ ========================================================================================*/
+ private static int GenerateSeed() {
+ Random rnd = t_threadRandom;
+ if (rnd == null) {
+ int seed;
+ lock (s_globalRandom) {
+ seed = s_globalRandom.Next();
+ }
+ rnd = new Random(seed);
+ t_threadRandom = rnd;
+ }
+ return rnd.Next();
+ }
+
+ /*==================================GenerateGlobalSeed====================================
+ **Action: Creates a number to use as global seed.
+ **Returns: An integer that is safe to use as seed values for thread-local seed generators.
+ ==========================================================================================*/
+ private static int GenerateGlobalSeed() {
+ return Guid.NewGuid().GetHashCode();
+ }
+
//
// Public Instance Methods
//
-
-
+
+
/*=====================================Next=====================================
**Returns: An int [0..Int32.MaxValue)
**Arguments: None
@@ -156,7 +195,7 @@ namespace System {
==============================================================================*/
public virtual int Next(int minValue, int maxValue) {
if (minValue>maxValue) {
- throw new ArgumentOutOfRangeException("minValue",Environment.GetResourceString("Argument_MinMaxValue", "minValue", "maxValue"));
+ throw new ArgumentOutOfRangeException(nameof(minValue),Environment.GetResourceString("Argument_MinMaxValue", nameof(minValue), nameof(maxValue)));
}
Contract.EndContractBlock();
@@ -177,7 +216,7 @@ namespace System {
==============================================================================*/
public virtual int Next(int maxValue) {
if (maxValue<0) {
- throw new ArgumentOutOfRangeException("maxValue", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "maxValue"));
+ throw new ArgumentOutOfRangeException(nameof(maxValue), Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(maxValue)));
}
Contract.EndContractBlock();
return (int)(Sample()*maxValue);
@@ -201,14 +240,11 @@ namespace System {
**Exceptions: None
==============================================================================*/
public virtual void NextBytes(byte [] buffer){
- if (buffer==null) throw new ArgumentNullException("buffer");
+ if (buffer==null) throw new ArgumentNullException(nameof(buffer));
Contract.EndContractBlock();
for (int i=0; i<buffer.Length; i++) {
buffer[i]=(byte)(InternalSample()%(Byte.MaxValue+1));
}
}
}
-
-
-
}
diff --git a/src/mscorlib/src/System/ReadOnlySpan.cs b/src/mscorlib/src/System/ReadOnlySpan.cs
new file mode 100644
index 0000000000..b0919d3208
--- /dev/null
+++ b/src/mscorlib/src/System/ReadOnlySpan.cs
@@ -0,0 +1,397 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+
+#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
+
+namespace System
+{
+ /// <summary>
+ /// ReadOnlySpan represents contiguous read-only region of arbitrary memory, with performance
+ /// characteristics on par with T[]. Unlike arrays, it can point to either managed
+ /// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
+ /// </summary>
+ public struct ReadOnlySpan<T>
+ {
+ /// <summary>A byref or a native ptr.</summary>
+ private readonly ByReference<T> _pointer;
+ /// <summary>The number of elements this ReadOnlySpan contains.</summary>
+ private readonly int _length;
+
+ /// <summary>
+ /// Creates a new span over the entirety of the target array.
+ /// </summary>
+ /// <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>
+ public ReadOnlySpan(T[] array)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+
+ _pointer = new ByReference<T>(ref JitHelpers.GetArrayData(array));
+ _length = array.Length;
+ }
+
+ /// <summary>
+ /// Creates a new span over the portion of the target array beginning
+ /// at 'start' index and covering the remainder of the array.
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <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.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> is not in the range (&lt;0 or &gt;&eq;Length).
+ /// </exception>
+ public ReadOnlySpan(T[] array, int start)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if ((uint)start > (uint)array.Length)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _pointer = new ByReference<T>(ref Unsafe.Add(ref JitHelpers.GetArrayData(array), start));
+ _length = array.Length - start;
+ }
+
+ /// <summary>
+ /// Creates a new span over the portion of the target array beginning
+ /// at 'start' index and ending at 'end' index (exclusive).
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <param name="start">The index at which to begin the span.</param>
+ /// <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.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;&eq;Length).
+ /// </exception>
+ public ReadOnlySpan(T[] array, int start, int length)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _pointer = new ByReference<T>(ref Unsafe.Add(ref JitHelpers.GetArrayData(array), start));
+ _length = length;
+ }
+
+ /// <summary>
+ /// Creates a new span over the target unmanaged buffer. Clearly this
+ /// is quite dangerous, because we are creating arbitrarily typed T's
+ /// 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="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.
+ /// </exception>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="length"/> is negative.
+ /// </exception>
+ [CLSCompliant(false)]
+ public unsafe ReadOnlySpan(void* pointer, int length)
+ {
+ if (JitHelpers.ContainsReferences<T>())
+ ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
+ if (length < 0)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
+ _length = length;
+ }
+
+ /// <summary>
+ /// An internal helper for creating spans.
+ /// </summary>
+ internal ReadOnlySpan(ref T ptr, int length)
+ {
+ _pointer = new ByReference<T>(ref ptr);
+ _length = length;
+ }
+
+ /// <summary>
+ /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
+ /// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
+ /// </summary>
+ public ref T DangerousGetPinnableReference()
+ {
+ return ref _pointer.Value;
+ }
+
+ /// <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>
+ /// Create a new read-only span over a portion of a regular managed object. This can be useful
+ /// if part of a managed object represents a "fixed array." This is dangerous because
+ /// "length" is not checked, nor is the fact that "rawPointer" actually lies within the object.
+ /// </summary>
+ /// <param name="obj">The managed object that contains the data to span over.</param>
+ /// <param name="objectData">A reference to data within that object.</param>
+ /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
+ /// <exception cref="System.ArgumentNullException">
+ /// Thrown when the specified object is null.
+ /// </exception>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="length"/> is negative.
+ /// </exception>
+ public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length)
+ {
+ if (obj == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
+ if (length < 0)
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
+
+ return new ReadOnlySpan<T>(ref objectData, length);
+ }
+
+ /// <summary>
+ /// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
+ /// </summary>
+ public static implicit operator ReadOnlySpan<T>(Span<T> slice)
+ {
+ return new ReadOnlySpan<T>(ref slice.DangerousGetPinnableReference(), slice.Length);
+ }
+
+ /// <summary>
+ /// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/>
+ /// </summary>
+ public static implicit operator ReadOnlySpan<T>(T[] array)
+ {
+ return new ReadOnlySpan<T>(array);
+ }
+
+ /// <summary>
+ /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlySpan{T}"/>
+ /// </summary>
+ public static implicit operator ReadOnlySpan<T>(ArraySegment<T> arraySegment)
+ {
+ return new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+ }
+
+ /// <summary>
+ /// Gets the number of elements contained in the <see cref="ReadOnlySpan{T}"/>
+ /// </summary>
+ public int Length
+ {
+ get { return _length; }
+ }
+
+ /// <summary>
+ /// Returns an empty <see cref="ReadOnlySpan{T}"/>
+ /// </summary>
+ public static ReadOnlySpan<T> Empty
+ {
+ get { return default(ReadOnlySpan<T>); }
+ }
+
+ /// <summary>
+ /// Returns whether the <see cref="ReadOnlySpan{T}"/> is empty.
+ /// </summary>
+ public bool IsEmpty
+ {
+ get { return _length == 0; }
+ }
+
+ /// <summary>
+ /// Fetches the element at the specified index.
+ /// </summary>
+ /// <exception cref="System.IndexOutOfRangeException">
+ /// Thrown when the specified <paramref name="index"/> is not in range (&lt;0 or &gt;&eq;Length).
+ /// </exception>
+ public T this[int index]
+ {
+ get
+ {
+ if ((uint)index >= (uint)_length)
+ ThrowHelper.ThrowIndexOutOfRangeException();
+
+ return Unsafe.Add(ref DangerousGetPinnableReference(), index);
+ }
+ }
+
+ /// <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.
+ /// </summary>
+ public T[] ToArray()
+ {
+ if (_length == 0)
+ return Array.Empty<T>();
+
+ var destination = new T[_length];
+ SpanHelper.CopyTo<T>(ref JitHelpers.GetArrayData(destination), ref DangerousGetPinnableReference(), _length);
+ return destination;
+ }
+
+ /// <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>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.NoOptimization)] // TODO-SPAN: Workaround for https://github.com/dotnet/coreclr/issues/7894
+ public ReadOnlySpan<T> Slice(int start)
+ {
+ if ((uint)start > (uint)_length)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ return new ReadOnlySpan<T>(ref Unsafe.Add(ref DangerousGetPinnableReference(), start), _length - start);
+ }
+
+ /// <summary>
+ /// 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>
+ /// <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>
+ [MethodImpl(MethodImplOptions.NoOptimization)] // TODO-SPAN: Workaround for https://github.com/dotnet/coreclr/issues/7894
+ public ReadOnlySpan<T> Slice(int start, int length)
+ {
+ if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ return new ReadOnlySpan<T>(ref Unsafe.Add(ref DangerousGetPinnableReference(), start), length);
+ }
+
+ /// <summary>
+ /// Copies the contents of this read-only 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.
+ ///
+ /// <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>
+ /// </summary>
+ public void CopyTo(Span<T> destination)
+ {
+ if (!TryCopyTo(destination))
+ ThrowHelper.ThrowArgumentException_DestinationTooShort();
+ }
+
+ /// <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.
+ /// </summary>
+ /// <param name="destination">The span to copy items into.</param>
+ 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 ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
+ {
+ return left._length == right._length && Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
+ }
+
+ /// <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 !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) => !(left == right);
+ }
+
+ public static class ReadOnlySpanExtensions
+ {
+ /// <summary>
+ /// Creates a new readonly span over the portion of the target string.
+ /// </summary>
+ /// <param name="text">The target string.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ public static ReadOnlySpan<char> Slice(this string text)
+ {
+ if (text == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
+
+ return new ReadOnlySpan<char>(ref text.GetFirstCharRef(), text.Length);
+ }
+
+ /// <summary>
+ /// Creates a new readonly span over the portion of the target string, beginning at 'start'.
+ /// </summary>
+ /// <param name="text">The target string.</param>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;Length).
+ /// </exception>
+ public static ReadOnlySpan<char> Slice(this string text, int start)
+ {
+ if (text == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
+ if ((uint)start > (uint)text.Length)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetFirstCharRef(), start), text.Length - start);
+ }
+
+ /// <summary>
+ /// Creates a new readonly span over the portion of the target string, beginning at <paramref name="start"/>, of given <paramref name="length"/>.
+ /// </summary>
+ /// <param name="text">The target string.</param>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <param name="length">The number of items in the span.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <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>
+ public static ReadOnlySpan<char> Slice(this string text, int start, int length)
+ {
+ if (text == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
+ if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetFirstCharRef(), start), length);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/Assembly.cs b/src/mscorlib/src/System/Reflection/Assembly.cs
index 479d6ca3a6..677e4aa964 100644
--- a/src/mscorlib/src/System/Reflection/Assembly.cs
+++ b/src/mscorlib/src/System/Reflection/Assembly.cs
@@ -37,7 +37,7 @@ namespace System.Reflection
using __HResults = System.__HResults;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
-
+ using System.Runtime.Loader;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
@@ -48,14 +48,9 @@ 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
{
-#region constructors
protected Assembly() {}
-#endregion
#region public static methods
@@ -67,7 +62,7 @@ namespace System.Reflection
public static Assembly GetAssembly(Type type)
{
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
Module m = type.Module;
@@ -105,36 +100,15 @@ namespace System.Reflection
return base.GetHashCode();
}
- // Locate an assembly by the name of the file containing the manifest.
-#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 static Assembly LoadFrom(String assemblyFile)
{
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
-#if FEATURE_WINDOWSPHONE
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_WindowsPhone", "Assembly.LoadFrom"));
-#else
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- return RuntimeAssembly.InternalLoadFrom(
- assemblyFile,
- null, // securityEvidence
- null, // hashValue
- AssemblyHashAlgorithm.None,
- false,// forIntrospection
- false,// suppressSecurityChecks
- ref stackMark);
-#endif // FEATURE_WINDOWSPHONE
+ if(assemblyFile == null)
+ throw new ArgumentNullException(nameof(assemblyFile));
+ string fullPath = Path.GetFullPath(assemblyFile);
+ return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
}
// 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)
{
@@ -153,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,
@@ -174,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,
@@ -196,49 +168,21 @@ 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,
AssemblyHashAlgorithm hashAlgorithm)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- return RuntimeAssembly.InternalLoadFrom(
- assemblyFile,
- null,
- hashValue,
- hashAlgorithm,
- false,
- false,
- ref stackMark);
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_AssemblyLoadFromHash"));
}
-#if FEATURE_CAS_POLICY
- // Load an assembly into the LoadFrom context bypassing some security checks
- [SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly UnsafeLoadFrom(string assemblyFile)
{
-
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- return RuntimeAssembly.InternalLoadFrom(assemblyFile,
- null, // securityEvidence
- null, // hashValue
- AssemblyHashAlgorithm.None,
- false, // forIntrospection
- true, // suppressSecurityChecks
- ref stackMark);
+ return LoadFrom(assemblyFile);
}
-#endif // FEATURE_CAS_POLICY
// 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)
{
@@ -253,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)
{
@@ -283,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)
{
@@ -293,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)
@@ -307,11 +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.
-#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 static Assembly Load(AssemblyName assemblyRef)
{
@@ -331,11 +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.
-#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
internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBinder)
{
@@ -353,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)
@@ -365,34 +295,17 @@ namespace System.Reflection
return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/);
}
-#if FEATURE_FUSION
- [System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly LoadWithPartialName(String partialName)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.LoadWithPartialNameInternal(partialName, null, ref stackMark);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly LoadWithPartialName(String partialName, Evidence securityEvidence)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.LoadWithPartialNameInternal(partialName, securityEvidence, ref stackMark);
+ if(partialName == null)
+ throw new ArgumentNullException(nameof(partialName));
+ return Load(partialName);
}
-#endif // FEATURE_FUSION
// Loads the assembly with a COFF based IMAGE containing
// an emitted assembly. The assembly is loaded into the domain
// of the caller.
-#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 static Assembly Load(byte[] rawAssembly)
{
@@ -401,20 +314,12 @@ namespace System.Reflection
AppDomain.CheckLoadByteArraySupported();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.nLoadImage(
- rawAssembly,
- null, // symbol store
- null, // evidence
- ref stackMark,
- false, // fIntrospection
- SecurityContextSource.CurrentAssembly);
+ return Load(rawAssembly, null);
}
// 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)
{
@@ -436,40 +341,30 @@ 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.
-#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 static Assembly Load(byte[] rawAssembly,
byte[] rawSymbolStore)
{
-
Contract.Ensures(Contract.Result<Assembly>() != null);
Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
AppDomain.CheckLoadByteArraySupported();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.nLoadImage(
- rawAssembly,
- rawSymbolStore,
- null, // evidence
- ref stackMark,
- false, // fIntrospection
- SecurityContextSource.CurrentAssembly);
+ if(rawAssembly == null)
+ throw new ArgumentNullException(nameof(rawAssembly));
+ AssemblyLoadContext alc = new IndividualAssemblyLoadContext();
+ MemoryStream assemblyStream = new MemoryStream(rawAssembly);
+ MemoryStream symbolStream = (rawSymbolStore!=null)?new MemoryStream(rawSymbolStore):null;
+ return alc.LoadFromStream(assemblyStream, symbolStream);
}
// 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,
SecurityContextSource securityContextSource)
{
-
Contract.Ensures(Contract.Result<Assembly>() != null);
Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
@@ -478,7 +373,7 @@ namespace System.Reflection
if (securityContextSource < SecurityContextSource.CurrentAppDomain ||
securityContextSource > SecurityContextSource.CurrentAssembly)
{
- throw new ArgumentOutOfRangeException("securityContextSource");
+ throw new ArgumentOutOfRangeException(nameof(securityContextSource));
}
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -490,79 +385,37 @@ namespace System.Reflection
securityContextSource);
}
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlEvidence)]
- [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(byte[] rawAssembly,
- byte[] rawSymbolStore,
- Evidence securityEvidence)
- {
-
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- AppDomain.CheckLoadByteArraySupported();
+ private static Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>();
- if (securityEvidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- // A zone of MyComputer could not have been used to sandbox, so for compatibility we do not
- // throw an exception when we see it.
- Zone zone = securityEvidence.GetHostEvidence<Zone>();
- if (zone == null || zone.SecurityZone != SecurityZone.MyComputer)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
- }
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.nLoadImage(
- rawAssembly,
- rawSymbolStore,
- securityEvidence,
- ref stackMark,
- false, // fIntrospection
- SecurityContextSource.CurrentAssembly);
- }
-#endif // FEATURE_CAS_POLICY
-
- [System.Security.SecuritySafeCritical] // auto-generated
public static Assembly LoadFile(String path)
{
-
Contract.Ensures(Contract.Result<Assembly>() != null);
Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
AppDomain.CheckLoadFileSupported();
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, path).Demand();
- return RuntimeAssembly.nLoadFile(path, null);
- }
-
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlEvidence)]
- [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFile which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public static Assembly LoadFile(String path,
- Evidence securityEvidence)
- {
-
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
+ Assembly result = null;
+ if(path == null)
+ throw new ArgumentNullException(nameof(path));
- AppDomain.CheckLoadFileSupported();
+ if (PathInternal.IsPartiallyQualified(path))
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(path));
+ }
- if (securityEvidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
+ string normalizedPath = Path.GetFullPath(path);
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, path).Demand();
- return RuntimeAssembly.nLoadFile(path, securityEvidence);
+ lock(s_loadfile)
+ {
+ if(s_loadfile.TryGetValue(normalizedPath, out result))
+ return result;
+ AssemblyLoadContext alc = new IndividualAssemblyLoadContext();
+ result = alc.LoadFromAssemblyPath(normalizedPath);
+ s_loadfile.Add(normalizedPath, result);
+ }
+ return result;
}
-#endif // FEATURE_CAS_POLICY
-#if FEATURE_CORECLR
- [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)
{
@@ -572,8 +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)
{
@@ -583,12 +434,10 @@ namespace System.Reflection
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.InternalLoadFromStream(assemblyStream, null, ref stackMark);
}
-#endif //FEATURE_CORECLR
/*
* 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()
{
@@ -596,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()
{
@@ -607,25 +455,22 @@ 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)
domainManager = new AppDomainManager();
return domainManager.EntryAssembly;
}
-
+
#endregion // public static methods
#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();
@@ -634,9 +479,6 @@ namespace System.Reflection
public virtual String CodeBase
{
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
get
{
throw new NotImplementedException();
@@ -645,24 +487,17 @@ namespace System.Reflection
public virtual String EscapedCodeBase
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return AssemblyName.EscapeCodeBase(CodeBase);
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public virtual AssemblyName GetName()
{
return GetName(false);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public virtual AssemblyName GetName(bool copiedName)
{
throw new NotImplementedException();
@@ -684,13 +519,6 @@ namespace System.Reflection
}
}
-#if !FEATURE_CORECLR
- Type _Assembly.GetType()
- {
- return base.GetType();
- }
-#endif
-
public virtual Type GetType(String name)
{
return GetType(name, false, false);
@@ -789,31 +617,11 @@ namespace System.Reflection
throw new NotImplementedException();
}
-#if FEATURE_CAS_POLICY
- public virtual Evidence Evidence
- {
- get
- {
- throw new NotImplementedException();
- }
- }
-
- public virtual PermissionSet PermissionSet
- {
- // SecurityCritical because permissions can contain sensitive information such as paths
- [SecurityCritical]
- get
- {
- throw new NotImplementedException();
- }
- }
-
public bool IsFullyTrusted
{
- [SecuritySafeCritical]
get
{
- return PermissionSet.IsUnrestricted();
+ return true;
}
}
@@ -821,14 +629,11 @@ namespace System.Reflection
{
get
{
- throw new NotImplementedException();
+ return SecurityRuleSet.None;
}
}
-#endif // FEATURE_CAS_POLICY
-
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
@@ -890,8 +695,6 @@ namespace System.Reflection
}
}
-#if FEATURE_MULTIMODULE_ASSEMBLIES
-
public Module LoadModule(String moduleName,
byte[] rawModule)
{
@@ -904,7 +707,6 @@ namespace System.Reflection
{
throw new NotImplementedException();
}
-#endif //FEATURE_MULTIMODULE_ASSEMBLIES
//
// Locates a type from this assembly and creates an instance of it using
@@ -986,9 +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.)
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public virtual FileStream GetFile(String name)
{
throw new NotImplementedException();
@@ -999,9 +798,6 @@ namespace System.Reflection
return GetFiles(false);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public virtual FileStream[] GetFiles(bool getResourceModules)
{
throw new NotImplementedException();
@@ -1034,9 +830,6 @@ namespace System.Reflection
public virtual String Location
{
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
get
{
throw new NotImplementedException();
@@ -1103,27 +896,7 @@ namespace System.Reflection
[Serializable]
internal class RuntimeAssembly : Assembly
-#if !FEATURE_CORECLR
- , ICustomQueryInterface
-#endif
{
-#if !FEATURE_CORECLR
-#region ICustomQueryInterface
- [System.Security.SecurityCritical]
- CustomQueryInterfaceResult ICustomQueryInterface.GetInterface([In]ref Guid iid, out IntPtr ppv)
- {
- if (iid == typeof(NativeMethods.IDispatch).GUID)
- {
- ppv = Marshal.GetComInterfaceForObject(this, typeof(_Assembly));
- return CustomQueryInterfaceResult.Handled;
- }
-
- ppv = IntPtr.Zero;
- return CustomQueryInterfaceResult.NotHandled;
- }
-#endregion
-#endif // !FEATURE_CORECLR
-
#if FEATURE_APPX
// The highest byte is the flags and the lowest 3 bytes are
// the cached ctor token of [DynamicallyInvocableAttribute].
@@ -1166,54 +939,12 @@ namespace System.Reflection
private ASSEMBLY_FLAGS Flags
{
- [SecuritySafeCritical]
get
{
if ((m_flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED) == 0)
{
- ASSEMBLY_FLAGS flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_UNKNOWN;
-
-#if FEATURE_CORECLR
- flags |= ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION;
-#else
- if (RuntimeAssembly.IsFrameworkAssembly(GetName()))
- {
- flags |= ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION;
-
- foreach (string name in s_unsafeFrameworkAssemblyNames)
- {
- if (String.Compare(GetSimpleName(), name, StringComparison.OrdinalIgnoreCase) == 0)
- {
- flags &= ~ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION;
- break;
- }
- }
-
- // Each blessed API will be annotated with a "__DynamicallyInvokableAttribute".
- // This "__DynamicallyInvokableAttribute" is a type defined in its own assembly.
- // So the ctor is always a MethodDef and the type a TypeDef.
- // We cache this ctor MethodDef token for faster custom attribute lookup.
- // If this attribute type doesn't exist in the assembly, it means the assembly
- // doesn't contain any blessed APIs.
- Type invocableAttribute = GetType("__DynamicallyInvokableAttribute", false);
- if (invocableAttribute != null)
- {
- Contract.Assert(((MetadataToken)invocableAttribute.MetadataToken).IsTypeDef);
-
- ConstructorInfo ctor = invocableAttribute.GetConstructor(Type.EmptyTypes);
- Contract.Assert(ctor != null);
-
- int token = ctor.MetadataToken;
- Contract.Assert(((MetadataToken)token).IsMethodDef);
-
- flags |= (ASSEMBLY_FLAGS)token & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_TOKEN_MASK;
- }
- }
- else if (IsDesignerBindingContext())
- {
- flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION;
- }
-#endif
+ ASSEMBLY_FLAGS flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_UNKNOWN
+ | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION;
m_flags = flags | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED;
}
@@ -1221,7 +952,7 @@ namespace System.Reflection
return m_flags;
}
}
-#endif // FEATURE_CORECLR
+#endif // FEATURE_APPX
internal object SyncRoot
{
@@ -1237,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;
@@ -1251,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;
@@ -1268,11 +995,6 @@ namespace System.Reflection
public override String CodeBase
{
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
get {
String codeBase = GetCodeBase(false);
VerifyCodeBaseDiscovery(codeBase);
@@ -1288,11 +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.
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public override AssemblyName GetName(bool copiedName)
{
AssemblyName an = new AssemblyName();
@@ -1326,27 +1043,12 @@ namespace System.Reflection
return an;
}
-#if FEATURE_APTCA
- // This method is called from the VM when creating conditional APTCA exceptions, in order to include
- // the text which must be added to the partial trust visible assembly list
- [SecurityCritical]
- [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
- private string GetNameForConditionalAptca()
- {
- AssemblyName assemblyName = GetName();
- return assemblyName.GetNameWithPublicKey();
-
- }
-#endif // FEATURE_APTCA
-
- [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)
@@ -1360,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));
@@ -1379,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,
@@ -1389,12 +1088,11 @@ 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"
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
RuntimeType type = null;
Object keepAlive = null;
@@ -1404,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;
@@ -1424,7 +1119,6 @@ namespace System.Reflection
public override IEnumerable<TypeInfo> DefinedTypes
{
- [System.Security.SecuritySafeCritical]
get
{
List<RuntimeType> rtTypes = new List<RuntimeType>();
@@ -1441,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)
{
@@ -1449,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)
{
@@ -1457,76 +1149,11 @@ namespace System.Reflection
return GetManifestResourceStream(name, ref stackMark, false);
}
-#if FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void GetEvidence(RuntimeAssembly assembly, ObjectHandleOnStack retEvidence);
-
- [SecurityCritical]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static SecurityRuleSet GetSecurityRuleSet(RuntimeAssembly assembly);
-
- public override Evidence Evidence
- {
- [SecuritySafeCritical]
- [SecurityPermissionAttribute( SecurityAction.Demand, ControlEvidence = true )]
- get
- {
- Evidence evidence = EvidenceNoDemand;
- return evidence.Clone();
- }
- }
-
- internal Evidence EvidenceNoDemand
- {
- [SecurityCritical]
- get
- {
- Evidence evidence = null;
- GetEvidence(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref evidence));
- return evidence;
- }
- }
-
- public override PermissionSet PermissionSet
- {
- [SecurityCritical]
- get
- {
- PermissionSet grantSet = null;
- PermissionSet deniedSet = null;
-
- GetGrantSet(out grantSet, out deniedSet);
-
- if (grantSet != null)
- {
- return grantSet.Copy();
- }
- else
- {
- return new PermissionSet(PermissionState.Unrestricted);
- }
- }
- }
-
- public override SecurityRuleSet SecurityRuleSet
- {
- [SecuritySafeCritical]
- get
- {
- return GetSecurityRuleSet(GetNativeHandle());
- }
- }
-#endif // FEATURE_CAS_POLICY
-
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
@@ -1550,17 +1177,17 @@ namespace System.Reflection
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
-
+
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -1568,13 +1195,13 @@ namespace System.Reflection
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"caType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -1583,8 +1210,7 @@ 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,
@@ -1595,16 +1221,10 @@ namespace System.Reflection
ref StackCrawlMark stackMark)
{
if (assemblyFile == null)
- throw new ArgumentNullException("assemblyFile");
+ throw new ArgumentNullException(nameof(assemblyFile));
Contract.EndContractBlock();
-#if FEATURE_CAS_POLICY
- if (securityEvidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
AssemblyName an = new AssemblyName();
an.CodeBase = assemblyFile;
an.SetHashControl(hashValue, hashAlgorithm);
@@ -1613,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,
@@ -1622,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,
@@ -1644,14 +1262,13 @@ 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,
out RuntimeAssembly assemblyFromResolveEvent)
{
if (assemblyString == null)
- throw new ArgumentNullException("assemblyString");
+ throw new ArgumentNullException(nameof(assemblyString));
Contract.EndContractBlock();
if ((assemblyString.Length == 0) ||
@@ -1670,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,
@@ -1684,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,
@@ -1698,7 +1313,7 @@ namespace System.Reflection
{
if (assemblyRef == null)
- throw new ArgumentNullException("assemblyRef");
+ throw new ArgumentNullException(nameof(assemblyRef));
Contract.EndContractBlock();
if (assemblyRef.CodeBase != null)
@@ -1717,13 +1332,6 @@ namespace System.Reflection
if (assemblySecurity != null)
{
-#if FEATURE_CAS_POLICY
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
if (!suppressSecurityChecks)
{
#pragma warning disable 618
@@ -1732,22 +1340,19 @@ namespace System.Reflection
}
}
-
String codeBase = VerifyCodeBase(assemblyRef.CodeBase);
- if (codeBase != null && !suppressSecurityChecks) {
-
- if (String.Compare( codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase) != 0) {
-#if FEATURE_FUSION // Of all the binders, Fusion is the only one that understands Web locations
- IPermission perm = CreateWebPermission( assemblyRef.EscapedCodeBase );
- perm.Demand();
-#else
+ if (codeBase != null && !suppressSecurityChecks)
+ {
+ if (String.Compare( codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase) != 0)
+ {
+ // Of all the binders, Fusion is the only one that understands Web locations
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "assemblyRef.CodeBase");
-#endif
}
- else {
+ else
+ {
System.Security.Util.URLString urlString = new System.Security.Util.URLString( codeBase, true );
new FileIOPermission( FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read , urlString.GetFileName() ).Demand();
- }
+ }
}
return nLoad(assemblyRef, codeBase, assemblySecurity, reqAssembly, ref stackMark,
@@ -1765,7 +1370,6 @@ namespace System.Reflection
};
#if FEATURE_APPX
- [System.Security.SecuritySafeCritical]
internal bool IsFrameworkAssembly()
{
ASSEMBLY_FLAGS flags = Flags;
@@ -1780,43 +1384,28 @@ 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,
Evidence assemblySecurity,
RuntimeAssembly locationHint,
- ref StackCrawlMark stackMark,
+ ref StackCrawlMark stackMark,
IntPtr pPrivHostBinder,
- bool throwOnFileNotFound,
+ bool throwOnFileNotFound,
bool forIntrospection,
bool suppressSecurityChecks,
IntPtr ptrLoadContextBinder);
-#if !FEATURE_CORECLR
- // The NGEN task uses this method, so please do not modify its signature
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern bool IsFrameworkAssembly(AssemblyName assemblyName);
-
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool IsNewPortableAssembly(AssemblyName assemblyName);
-#endif
-
- [System.Security.SecurityCritical] // auto-generated
private static RuntimeAssembly nLoad(AssemblyName fileName,
String codeBase,
Evidence assemblySecurity,
@@ -1832,177 +1421,6 @@ namespace System.Reflection
throwOnFileNotFound, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder);
}
-#if FEATURE_FUSION
- // used by vm
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- private static unsafe RuntimeAssembly LoadWithPartialNameHack(String partialName, bool cropPublicKey)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- AssemblyName an = new AssemblyName(partialName);
-
- if (!IsSimplyNamed(an))
- {
- if (cropPublicKey)
- {
- an.SetPublicKey(null);
- an.SetPublicKeyToken(null);
- }
-
- if(IsFrameworkAssembly(an) || !AppDomain.IsAppXModel())
- {
- AssemblyName GACAssembly = EnumerateCache(an);
- if(GACAssembly != null)
- return InternalLoadAssemblyName(GACAssembly, null, null,ref stackMark, true /*thrownOnFileNotFound*/, false, false);
- else
- return null;
- }
- }
-
- if (AppDomain.IsAppXModel())
- {
- // also try versionless bind from the package
- an.Version = null;
- return nLoad(an, null, null, null, ref stackMark,
- IntPtr.Zero,
- false, false, false);
- }
- return null;
-
- }
-
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- internal static RuntimeAssembly LoadWithPartialNameInternal(String partialName, Evidence securityEvidence, ref StackCrawlMark stackMark)
- {
- AssemblyName an = new AssemblyName(partialName);
- return LoadWithPartialNameInternal(an, securityEvidence, ref stackMark);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal static RuntimeAssembly LoadWithPartialNameInternal(AssemblyName an, Evidence securityEvidence, ref StackCrawlMark stackMark)
- {
- if (securityEvidence != null)
- {
-#if FEATURE_CAS_POLICY
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
- }
-
- AppDomain.CheckLoadWithPartialNameSupported(stackMark);
-
- RuntimeAssembly result = null;
- try {
- result = nLoad(an, null, securityEvidence, null, ref stackMark,
- IntPtr.Zero,
- true, false, false);
- }
- catch(Exception e) {
- if (e.IsTransient)
- throw e;
-
- if (IsUserError(e))
- throw;
-
-
- if(IsFrameworkAssembly(an) || !AppDomain.IsAppXModel())
- {
- if (IsSimplyNamed(an))
- return null;
-
- AssemblyName GACAssembly = EnumerateCache(an);
- if(GACAssembly != null)
- result = InternalLoadAssemblyName(GACAssembly, securityEvidence, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
- }
- else
- {
- an.Version = null;
- result = nLoad(an, null, securityEvidence, null, ref stackMark,
- IntPtr.Zero,
- false, false, false);
- }
- }
-
-
- return result;
- }
-#endif // !FEATURE_CORECLR
-
- [SecuritySafeCritical]
- private static bool IsUserError(Exception e)
- {
- return (uint)e.HResult == COR_E_LOADING_REFERENCE_ASSEMBLY;
- }
-
- private static bool IsSimplyNamed(AssemblyName partialName)
- {
- byte[] pk = partialName.GetPublicKeyToken();
- if ((pk != null) &&
- (pk.Length == 0))
- return true;
-
- pk = partialName.GetPublicKey();
- if ((pk != null) &&
- (pk.Length == 0))
- return true;
-
- return false;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private static AssemblyName EnumerateCache(AssemblyName partialName)
- {
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
-
- partialName.Version = null;
-
- ArrayList a = new ArrayList();
- Fusion.ReadCache(a, partialName.FullName, ASM_CACHE.GAC);
-
- IEnumerator myEnum = a.GetEnumerator();
- AssemblyName ainfoBest = null;
- CultureInfo refCI = partialName.CultureInfo;
-
- while (myEnum.MoveNext()) {
- AssemblyName ainfo = new AssemblyName((String)myEnum.Current);
-
- if (CulturesEqual(refCI, ainfo.CultureInfo)) {
- if (ainfoBest == null)
- ainfoBest = ainfo;
- else {
- // Choose highest version
- if (ainfo.Version > ainfoBest.Version)
- ainfoBest = ainfo;
- }
- }
- }
-
- return ainfoBest;
- }
-
- private static bool CulturesEqual(CultureInfo refCI, CultureInfo defCI)
- {
- bool defNoCulture = defCI.Equals(CultureInfo.InvariantCulture);
-
- // cultured asms aren't allowed to be bound to if
- // the ref doesn't ask for them specifically
- if ((refCI == null) || refCI.Equals(CultureInfo.InvariantCulture))
- return defNoCulture;
-
- if (defNoCulture ||
- ( !defCI.Equals(refCI) ))
- return false;
-
- return true;
- }
-#endif // FEATURE_FUSION
-
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsReflectionOnly(RuntimeAssembly assembly);
@@ -2011,23 +1429,20 @@ namespace System.Reflection
[ComVisible(false)]
public override bool ReflectionOnly
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return IsReflectionOnly(GetNativeHandle());
}
}
-#if FEATURE_CORECLR
// Loads the assembly with a COFF based IMAGE containing
// 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)
- throw new ArgumentNullException("assemblyStream");
+ throw new ArgumentNullException(nameof(assemblyStream));
if (assemblyStream.GetType()!=typeof(UnmanagedMemoryStream))
throw new NotSupportedException();
@@ -2070,44 +1485,13 @@ namespace System.Reflection
return assembly;
}
}
-#endif //FEATURE_CORECLR
-
-#if FEATURE_MULTIMODULE_ASSEMBLIES
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void LoadModule(RuntimeAssembly assembly,
- String moduleName,
- byte[] rawModule, int cbModule,
- byte[] rawSymbolStore, int cbSymbolStore,
- ObjectHandleOnStack retModule);
-
- [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
- [System.Security.SecuritySafeCritical] // auto-generated
- public override Module LoadModule(String moduleName, byte[] rawModule, byte[] rawSymbolStore)
- {
- RuntimeModule retModule = null;
- LoadModule(
- GetNativeHandle(),
- moduleName,
- rawModule,
- (rawModule != null) ? rawModule.Length : 0,
- rawSymbolStore,
- (rawSymbolStore != null) ? rawSymbolStore.Length : 0,
- JitHelpers.GetObjectHandleOnStack(ref retModule));
-
- return retModule;
- }
-#endif //FEATURE_MULTIMODULE_ASSEMBLIES
// 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;
@@ -2117,11 +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.)
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public override FileStream GetFile(String name)
{
RuntimeModule m = (RuntimeModule)GetModule(name);
@@ -2133,11 +1512,6 @@ namespace System.Reflection
FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public override FileStream[] GetFiles(bool getResourceModules)
{
Module[] m = GetModules(getResourceModules);
@@ -2152,26 +1526,20 @@ namespace System.Reflection
return fs;
}
-
// 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;
@@ -2180,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,
@@ -2199,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)
{
@@ -2218,18 +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
{
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
get {
String location = null;
@@ -2242,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);
@@ -2252,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));
@@ -2261,30 +1617,26 @@ 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 IsGlobalAssemblyCache(GetNativeHandle());
+ 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 GetHostContext(GetNativeHandle());
+ return 0;
}
}
@@ -2309,14 +1661,13 @@ namespace System.Reflection
else if ((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\'))
return "file://" + codebase;
else
- return "file:///" + Path.GetFullPathInternal( codebase );
+ return "file:///" + Path.GetFullPath(codebase);
#else
else
- return "file://" + Path.GetFullPathInternal( codebase );
+ return "file://" + Path.GetFullPath(codebase);
#endif // !PLATFORM_UNIX
}
- [System.Security.SecurityCritical] // auto-generated
internal Stream GetManifestResourceStream(
Type type,
String name,
@@ -2326,7 +1677,7 @@ namespace System.Reflection
StringBuilder sb = new StringBuilder();
if(type == null) {
if (name == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
}
else {
String nameSpace = type.Namespace;
@@ -2339,25 +1690,11 @@ namespace System.Reflection
if(name != null)
sb.Append(name);
-
- return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck);
- }
-#if FEATURE_CAS_POLICY
- internal bool IsStrongNameVerified
- {
- [System.Security.SecurityCritical] // auto-generated
- get { return GetIsStrongNameVerified(GetNativeHandle()); }
+ return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck);
}
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern bool GetIsStrongNameVerified(RuntimeAssembly assembly);
-#endif // FEATURE_CAS_POLICY
-
// 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,
@@ -2366,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;
@@ -2384,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,
@@ -2393,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;
@@ -2401,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;
@@ -2419,27 +1751,18 @@ 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 FEATURE_CAS_POLICY
- if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) {
- return;
- }
-#endif // FEATURE_CAS_POLICY
-
if ((codeBase != null) &&
(String.Compare( codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase) == 0)) {
System.Security.Util.URLString urlString = new System.Security.Util.URLString( codeBase, true );
@@ -2447,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;
@@ -2460,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;
@@ -2497,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;
@@ -2510,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;
@@ -2523,134 +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());
}
-#if FEATURE_FUSION
- // demandFlag:
- // 0 demand PathDiscovery permission only
- // 1 demand Read permission only
- // 2 demand both Read and PathDiscovery
- // 3 demand Web permission only
- [System.Security.SecurityCritical] // auto-generated
- private static void DemandPermission(String codeBase, bool havePath,
- int demandFlag)
- {
- FileIOPermissionAccess access = FileIOPermissionAccess.PathDiscovery;
- switch(demandFlag) {
-
- case 0: // default
- break;
- case 1:
- access = FileIOPermissionAccess.Read;
- break;
- case 2:
- access = FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read;
- break;
-
- case 3:
- IPermission perm = CreateWebPermission(AssemblyName.EscapeCodeBase(codeBase));
- perm.Demand();
- return;
- }
-
- if (!havePath) {
- System.Security.Util.URLString urlString = new System.Security.Util.URLString( codeBase, true );
- codeBase = urlString.GetFileName();
- }
-
- codeBase = Path.GetFullPathInternal(codeBase); // canonicalize
-
- new FileIOPermission(access, codeBase).Demand();
- }
-#endif
-
-#if FEATURE_FUSION
- private static IPermission CreateWebPermission( String codeBase )
- {
- Contract.Assert( codeBase != null, "Must pass in a valid CodeBase" );
- Assembly sys = Assembly.Load("System, Version=" + ThisAssembly.Version + ", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken);
-
- Type type = sys.GetType("System.Net.NetworkAccess", true);
-
- IPermission retval = null;
- if (!type.IsEnum || !type.IsVisible)
- goto Exit;
-
- Object[] webArgs = new Object[2];
- webArgs[0] = (Enum) Enum.Parse(type, "Connect", true);
- if (webArgs[0] == null)
- goto Exit;
-
- webArgs[1] = codeBase;
-
- type = sys.GetType("System.Net.WebPermission", true);
-
- if (!type.IsVisible)
- goto Exit;
-
- retval = (IPermission) Activator.CreateInstance(type, webArgs);
-
- Exit:
- if (retval == null) {
- Contract.Assert( false, "Unable to create WebPermission" );
- throw new InvalidOperationException();
- }
-
- return retval;
- }
-#endif
// This method is called by the VM.
- [System.Security.SecurityCritical]
private RuntimeModule OnModuleResolveEvent(String moduleName)
{
ModuleResolveEventHandler moduleResolve = _ModuleResolve;
@@ -2683,14 +1911,13 @@ 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,
ref StackCrawlMark stackMark)
{
if (culture == null)
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
Contract.EndContractBlock();
@@ -2698,15 +1925,6 @@ namespace System.Reflection
return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark);
}
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool UseRelativeBindForSatellites();
-#endif
-
- [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,
@@ -2728,104 +1946,9 @@ namespace System.Reflection
an.CultureInfo = culture;
an.Name = name;
- RuntimeAssembly retAssembly = null;
-
-#if !FEATURE_CORECLR
- bool bIsAppXDevMode = AppDomain.IsAppXDesignMode();
-
- bool useRelativeBind = false;
- if (CodeAccessSecurityEngine.QuickCheckForAllDemands())
- {
- if (IsFrameworkAssembly())
- useRelativeBind = true;
- else
- useRelativeBind = UseRelativeBindForSatellites();
- }
-
-
- if (bIsAppXDevMode || useRelativeBind)
- {
- if (GlobalAssemblyCache)
- {
- // lookup in GAC
- ArrayList a = new ArrayList();
- bool bTryLoadAnyway = false;
- try
- {
- Fusion.ReadCache(a, an.FullName, ASM_CACHE.GAC);
- }
- catch(Exception e)
- {
- if (e.IsTransient)
- throw;
-
- // We also catch any other exception types we haven't come across yet,
- // not just UnauthorizedAccessException.
-
- // We do not want this by itself to cause us to fail to load resources.
-
- // On Classic, try the old unoptimized way, for full compatibility with 4.0.
- // i.e. fall back to using nLoad.
- if (!AppDomain.IsAppXModel())
- bTryLoadAnyway = true;
-
- // On AppX:
- // Do not try nLoad since that would effectively allow Framework
- // resource satellite assemblies to be placed in AppX packages.
- // Instead, leave retAssembly == null. If we were called by the
- // ResourceManager, this will usually result in falling back to
- // the next culture in the resource fallback chain, possibly the
- // neutral culture.
-
- // Note: if throwOnFileNotFound is true, arbitrary
- // exceptions will be absorbed here and
- // FileNotFoundException will be thrown in their place.
- // (See below: "throw new FileNotFoundException").
- }
- if (a.Count > 0 || bTryLoadAnyway)
- {
- // present in the GAC, load it from there
- retAssembly = nLoad(an, null, null, this, ref stackMark,
- IntPtr.Zero,
- throwOnFileNotFound, false, false);
- }
- }
- else
- {
- String codeBase = CodeBase;
-
- if ((codeBase != null) &&
- (String.Compare(codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase) == 0))
- {
- retAssembly = InternalProbeForSatelliteAssemblyNextToParentAssembly(an,
- name,
- codeBase,
- culture,
- throwOnFileNotFound,
- bIsAppXDevMode /* useLoadFile */, // if bIsAppXDevMode is false, then useRelativeBind is true.
- ref stackMark);
- if (retAssembly != null && !IsSimplyNamed(an))
- {
- AssemblyName defName = retAssembly.GetName();
- if (!AssemblyName.ReferenceMatchesDefinitionInternal(an,defName,false))
- retAssembly = null;
- }
- }
- else if (!bIsAppXDevMode)
- {
- retAssembly = nLoad(an, null, null, this, ref stackMark,
- IntPtr.Zero,
- throwOnFileNotFound, false, false);
- }
- }
- }
- else
-#endif // !FEATURE_CORECLR
- {
- retAssembly = nLoad(an, null, null, this, ref stackMark,
- IntPtr.Zero,
- throwOnFileNotFound, false, false);
- }
+ RuntimeAssembly retAssembly = nLoad(an, null, null, this, ref stackMark,
+ IntPtr.Zero,
+ throwOnFileNotFound, false, false);
if (retAssembly == this || (retAssembly == null && throwOnFileNotFound))
{
@@ -2836,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,
@@ -2930,7 +2052,7 @@ namespace System.Reflection
// the .DLL and .EXE load attempts if the user is interested in digging deeper.
if (retAssembly == null && throwOnFileNotFound)
- throw dllNotFoundException;
+ throw dllNotFoundException;
}
}
catch (DirectoryNotFoundException)
@@ -2944,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,
@@ -2956,8 +2076,7 @@ namespace System.Reflection
ref StackCrawlMark stackMark,
bool fIntrospection,
SecurityContextSource securityContextSource);
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static internal extern unsafe void nLoadFromUnmanagedArray(bool fIntrospection,
@@ -2967,9 +2086,7 @@ namespace System.Reflection
ulong pdbSize,
StackCrawlMarkHandle stackMark,
ObjectHandleOnStack retAssembly);
-#endif
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetModules(RuntimeAssembly assembly,
@@ -2977,7 +2094,6 @@ namespace System.Reflection
bool getResourceModules,
ObjectHandleOnStack retModuleHandles);
- [System.Security.SecuritySafeCritical] // auto-generated
private RuntimeModule[] GetModulesInternal(bool loadIfNotFound,
bool getResourceModules)
{
@@ -2996,17 +2112,9 @@ namespace System.Reflection
return GetModulesInternal(false, getResourceModules);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly);
-#if FEATURE_APTCA
- [System.Security.SecuritySafeCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool AptcaCheck(RuntimeAssembly targetAssembly, RuntimeAssembly sourceAssembly);
-#endif // FEATURE_APTCA
-
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeAssembly assembly);
}
diff --git a/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs b/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
index 955255572b..b2e44b0034 100644
--- a/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
@@ -190,7 +190,7 @@ namespace System.Reflection {
public AssemblyFileVersionAttribute(String version)
{
if (version == null)
- throw new ArgumentNullException("version");
+ throw new ArgumentNullException(nameof(version));
Contract.EndContractBlock();
_version = version;
}
diff --git a/src/mscorlib/src/System/Reflection/AssemblyName.cs b/src/mscorlib/src/System/Reflection/AssemblyName.cs
index 051f3b5f0e..48eab33ee5 100644
--- a/src/mscorlib/src/System/Reflection/AssemblyName.cs
+++ b/src/mscorlib/src/System/Reflection/AssemblyName.cs
@@ -24,6 +24,7 @@ namespace System.Reflection {
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
+ using System.Text;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
@@ -103,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)
@@ -189,16 +183,15 @@ 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)
- throw new ArgumentNullException("assemblyFile");
+ throw new ArgumentNullException(nameof(assemblyFile));
Contract.EndContractBlock();
// Assembly.GetNameInternal() will not demand path discovery
// permission, so do that first.
- String fullPath = Path.GetFullPathInternal(assemblyFile);
+ string fullPath = Path.GetFullPath(assemblyFile);
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullPath ).Demand();
return nGetFileInformation(fullPath);
}
@@ -230,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)
@@ -279,7 +271,6 @@ namespace System.Reflection {
public String FullName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return nToString();
}
@@ -295,11 +286,10 @@ namespace System.Reflection {
return s;
}
- [System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
//Allocate the serialization info and serialize our static data.
@@ -360,11 +350,10 @@ namespace System.Reflection {
m_siInfo = info;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public AssemblyName(String assemblyName)
{
if (assemblyName == null)
- throw new ArgumentNullException("assemblyName");
+ throw new ArgumentNullException(nameof(assemblyName));
Contract.EndContractBlock();
if ((assemblyName.Length == 0) ||
(assemblyName[0] == '\0'))
@@ -374,7 +363,6 @@ namespace System.Reflection {
nInit();
}
- [System.Security.SecuritySafeCritical] // auto-generated
static public bool ReferenceMatchesDefinition(AssemblyName reference,
AssemblyName definition)
{
@@ -389,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,
@@ -397,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;
@@ -486,54 +471,239 @@ namespace System.Reflection {
_StrongNameKeyPair = keyPair;
}
-#if !FEATURE_CORECLR
- void _AssemblyName.GetTypeInfoCount(out uint pcTInfo)
+ // This call opens and closes the file, but does not add the
+ // assembly to the domain.
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ static internal extern AssemblyName nGetFileInformation(String s);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private extern String nToString();
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private extern byte[] nGetPublicKeyToken();
+
+ static internal String EscapeCodeBase(String codebase)
{
- throw new NotImplementedException();
+ if (codebase == null)
+ return string.Empty;
+
+ int position = 0;
+ char[] dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar);
+ if (dest == null)
+ return codebase;
+
+ return new string(dest, 0, position);
}
- void _AssemblyName.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
+ // This implementation of EscapeString has been copied from System.Private.Uri from corefx repo
+ // - forceX characters are always escaped if found
+ // - rsvd character will remain unescaped
+ //
+ // start - starting offset from input
+ // end - the exclusive ending offset in input
+ // destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output.
+ //
+ // In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos
+ //
+ // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos
+ //
+ internal unsafe static char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos,
+ bool isUriString, char force1, char force2, char rsvd)
{
- throw new NotImplementedException();
+ int i = start;
+ int prevInputPos = start;
+ byte* bytes = stackalloc byte[c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar]; // 40*4=160
+
+ fixed (char* pStr = input)
+ {
+ for (; i < end; ++i)
+ {
+ char ch = pStr[i];
+
+ // a Unicode ?
+ if (ch > '\x7F')
+ {
+ short maxSize = (short)Math.Min(end - i, (int)c_MaxUnicodeCharsReallocate - 1);
+
+ short count = 1;
+ for (; count < maxSize && pStr[i + count] > '\x7f'; ++count)
+ ;
+
+ // Is the last a high surrogate?
+ if (pStr[i + count - 1] >= 0xD800 && pStr[i + count - 1] <= 0xDBFF)
+ {
+ // Should be a rare case where the app tries to feed an invalid Unicode surrogates pair
+ if (count == 1 || count == end - i)
+ throw new FormatException(Environment.GetResourceString("Arg_FormatException"));
+ // need to grab one more char as a Surrogate except when it's a bogus input
+ ++count;
+ }
+
+ dest = EnsureDestinationSize(pStr, dest, i,
+ (short)(count * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte),
+ c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte,
+ ref destPos, prevInputPos);
+
+ short numberOfBytes = (short)Encoding.UTF8.GetBytes(pStr + i, count, bytes,
+ c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar);
+
+ // This is the only exception that built in UriParser can throw after a Uri ctor.
+ // Should not happen unless the app tries to feed an invalid Unicode String
+ if (numberOfBytes == 0)
+ throw new FormatException(Environment.GetResourceString("Arg_FormatException"));
+
+ i += (count - 1);
+
+ for (count = 0; count < numberOfBytes; ++count)
+ EscapeAsciiChar((char)bytes[count], dest, ref destPos);
+
+ prevInputPos = i + 1;
+ }
+ else if (ch == '%' && rsvd == '%')
+ {
+ // Means we don't reEncode '%' but check for the possible escaped sequence
+ dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte,
+ c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos);
+ if (i + 2 < end && EscapedAscii(pStr[i + 1], pStr[i + 2]) != c_DummyChar)
+ {
+ // leave it escaped
+ dest[destPos++] = '%';
+ dest[destPos++] = pStr[i + 1];
+ dest[destPos++] = pStr[i + 2];
+ i += 2;
+ }
+ else
+ {
+ EscapeAsciiChar('%', dest, ref destPos);
+ }
+ prevInputPos = i + 1;
+ }
+ else if (ch == force1 || ch == force2)
+ {
+ dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte,
+ c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos);
+ EscapeAsciiChar(ch, dest, ref destPos);
+ prevInputPos = i + 1;
+ }
+ else if (ch != rsvd && (isUriString ? !IsReservedUnreservedOrHash(ch) : !IsUnreserved(ch)))
+ {
+ dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte,
+ c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos);
+ EscapeAsciiChar(ch, dest, ref destPos);
+ prevInputPos = i + 1;
+ }
+ }
+
+ if (prevInputPos != i)
+ {
+ // need to fill up the dest array ?
+ if (prevInputPos != start || dest != null)
+ dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos);
+ }
+ }
+
+ return dest;
}
- void _AssemblyName.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
+ //
+ // ensure destination array has enough space and contains all the needed input stuff
+ //
+ private unsafe static char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos,
+ short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos)
{
- throw new NotImplementedException();
- }
+ if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd)
+ {
+ // allocating or reallocating array by ensuring enough space based on maxCharsToAdd.
+ char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars];
+
+ if ((object)dest != null && destPos != 0)
+ Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1);
+ dest = newresult;
+ }
- void _AssemblyName.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
+ // ensuring we copied everything form the input string left before last escaping
+ while (prevInputPos != currentInputPos)
+ dest[destPos++] = pStr[prevInputPos++];
+ return dest;
+ }
+
+ internal static void EscapeAsciiChar(char ch, char[] to, ref int pos)
{
- throw new NotImplementedException();
+ to[pos++] = '%';
+ to[pos++] = s_hexUpperChars[(ch & 0xf0) >> 4];
+ to[pos++] = s_hexUpperChars[ch & 0xf];
}
-#endif
-#if FEATURE_APTCA
- internal string GetNameWithPublicKey()
+ internal static char EscapedAscii(char digit, char next)
{
- byte[] key = GetPublicKey();
+ if (!(((digit >= '0') && (digit <= '9'))
+ || ((digit >= 'A') && (digit <= 'F'))
+ || ((digit >= 'a') && (digit <= 'f'))))
+ {
+ return c_DummyChar;
+ }
+
+ int res = (digit <= '9')
+ ? ((int)digit - (int)'0')
+ : (((digit <= 'F')
+ ? ((int)digit - (int)'A')
+ : ((int)digit - (int)'a'))
+ + 10);
+
+ if (!(((next >= '0') && (next <= '9'))
+ || ((next >= 'A') && (next <= 'F'))
+ || ((next >= 'a') && (next <= 'f'))))
+ {
+ return c_DummyChar;
+ }
+
+ return (char)((res << 4) + ((next <= '9')
+ ? ((int)next - (int)'0')
+ : (((next <= 'F')
+ ? ((int)next - (int)'A')
+ : ((int)next - (int)'a'))
+ + 10)));
+ }
- // The following string should not be localized because it is used in security decisions.
- return Name + ", PublicKey=" + System.Security.Util.Hex.EncodeHexString(key);
+ private static unsafe bool IsReservedUnreservedOrHash(char c)
+ {
+ if (IsUnreserved(c))
+ {
+ return true;
+ }
+ return (RFC3986ReservedMarks.IndexOf(c) >= 0);
}
-#endif
- // 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);
+ internal static unsafe bool IsUnreserved(char c)
+ {
+ if (IsAsciiLetterOrDigit(c))
+ {
+ return true;
+ }
+ return (RFC3986UnreservedMarks.IndexOf(c) >= 0);
+ }
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern String nToString();
+ //Only consider ASCII characters
+ internal static bool IsAsciiLetter(char character)
+ {
+ return (character >= 'a' && character <= 'z') ||
+ (character >= 'A' && character <= 'Z');
+ }
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern byte[] nGetPublicKeyToken();
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static internal extern String EscapeCodeBase(String codeBase);
+ internal static bool IsAsciiLetterOrDigit(char character)
+ {
+ return IsAsciiLetter(character) || (character >= '0' && character <= '9');
+ }
+
+ private static readonly char[] s_hexUpperChars = {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+ internal const char c_DummyChar = (char)0xFFFF; //An Invalid Unicode character used as a dummy char passed into the parameter
+ private const short c_MaxAsciiCharsReallocate = 40;
+ private const short c_MaxUnicodeCharsReallocate = 40;
+ private const short c_MaxUTF_8BytesPerUnicodeChar = 4;
+ private const short c_EncodedCharsPerByte = 3;
+ private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;=";
+ private const string RFC3986UnreservedMarks = @"-._~";
}
}
diff --git a/src/mscorlib/src/System/Reflection/Associates.cs b/src/mscorlib/src/System/Reflection/Associates.cs
index 8b34e77b63..9eaf74a6e9 100644
--- a/src/mscorlib/src/System/Reflection/Associates.cs
+++ b/src/mscorlib/src/System/Reflection/Associates.cs
@@ -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,
diff --git a/src/mscorlib/src/System/Reflection/ComInterfaces.cs b/src/mscorlib/src/System/Reflection/ComInterfaces.cs
index 63438115fc..6e4b0cc19a 100644
--- a/src/mscorlib/src/System/Reflection/ComInterfaces.cs
+++ b/src/mscorlib/src/System/Reflection/ComInterfaces.cs
@@ -2,248 +2,26 @@
// 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")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Assembly))]
[CLSCompliant(false)]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _Assembly
{
-#if !FEATURE_CORECLR
- #region Object Members
- String ToString();
- bool Equals(Object other);
- int GetHashCode();
- Type GetType();
- #endregion
-
- #region Assembly Members
- String CodeBase {
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#endif
-get; }
- String EscapedCodeBase { get; }
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- AssemblyName GetName();
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- AssemblyName GetName(bool copiedName);
- String FullName { get; }
- MethodInfo EntryPoint { get; }
- Type GetType(String name);
- Type GetType(String name, bool throwOnError);
- Type[] GetExportedTypes();
- Type[] GetTypes();
- Stream GetManifestResourceStream(Type type, String name);
- Stream GetManifestResourceStream(String name);
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- FileStream GetFile(String name);
- FileStream[] GetFiles();
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- FileStream[] GetFiles(bool getResourceModules);
- String[] GetManifestResourceNames();
- ManifestResourceInfo GetManifestResourceInfo(String resourceName);
- String Location {
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#endif
-get; }
-#if FEATURE_CAS_POLICY
- Evidence Evidence { get; }
-#endif // FEATURE_CAS_POLICY
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
- Object[] GetCustomAttributes(bool inherit);
- bool IsDefined(Type attributeType, bool inherit);
-#if FEATURE_SERIALIZATION
- [System.Security.SecurityCritical] // auto-generated_required
- void GetObjectData(SerializationInfo info, StreamingContext context);
-#endif
- [method: System.Security.SecurityCritical]
- event ModuleResolveEventHandler ModuleResolve;
- Type GetType(String name, bool throwOnError, bool ignoreCase);
- Assembly GetSatelliteAssembly(CultureInfo culture);
- Assembly GetSatelliteAssembly(CultureInfo culture, Version version);
-#if FEATURE_MULTIMODULE_ASSEMBLIES
- Module LoadModule(String moduleName, byte[] rawModule);
- Module LoadModule(String moduleName, byte[] rawModule, byte[] rawSymbolStore);
-#endif
- Object CreateInstance(String typeName);
- Object CreateInstance(String typeName, bool ignoreCase);
- Object CreateInstance(String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes);
- Module[] GetLoadedModules();
- Module[] GetLoadedModules(bool getResourceModules);
- Module[] GetModules();
- Module[] GetModules(bool getResourceModules);
- Module GetModule(String name);
- AssemblyName[] GetReferencedAssemblies();
- bool GlobalAssemblyCache { get; }
- #endregion
-#endif
}
-
[GuidAttribute("f7102fa9-cabb-3a74-a6da-b4567ef1b079")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[TypeLibImportClassAttribute(typeof(System.Reflection.MemberInfo))]
@@ -251,34 +29,8 @@ get; }
[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)]
@@ -286,57 +38,8 @@ get; }
[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)]
@@ -344,62 +47,7 @@ get; }
[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)]
@@ -408,174 +56,26 @@ get; }
[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)]
@@ -583,91 +83,33 @@ get; }
[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
}
}
diff --git a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs b/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
index d5b5cc36eb..3d927fc85c 100644
--- a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
+++ b/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
@@ -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);
@@ -397,28 +307,27 @@ namespace System.Reflection
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -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)
@@ -532,7 +438,7 @@ namespace System.Reflection
internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg)
{
if (declaringType == null)
- throw new ArgumentNullException("declaringType");
+ throw new ArgumentNullException(nameof(declaringType));
Contract.EndContractBlock();
// ctor is ReflectOnly
@@ -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,26 +512,10 @@ 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;
@@ -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,17 +552,17 @@ namespace System.Reflection
public override bool IsSecurityCritical
{
- get { return RuntimeMethodHandle.IsSecurityCritical(this); }
+ get { return true; }
}
public override bool IsSecuritySafeCritical
{
- get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
+ get { return false; }
}
public override bool IsSecurityTransparent
{
- get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
+ get { return false; }
}
public override bool ContainsGenericParameters
@@ -687,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
@@ -711,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;
@@ -749,11 +624,10 @@ namespace System.Reflection
#endregion
#region ISerializable Implementation
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
@@ -777,5 +651,4 @@ namespace System.Reflection
}
#endregion
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
index 463c976357..e568a1702f 100644
--- a/src/mscorlib/src/System/Reflection/CustomAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
@@ -29,7 +29,7 @@ namespace System.Reflection
public static IList<CustomAttributeData> GetCustomAttributes(MemberInfo target)
{
if (target == null)
- throw new ArgumentNullException("target");
+ throw new ArgumentNullException(nameof(target));
return target.GetCustomAttributesData();
}
@@ -37,7 +37,7 @@ namespace System.Reflection
public static IList<CustomAttributeData> GetCustomAttributes(Module target)
{
if (target == null)
- throw new ArgumentNullException("target");
+ throw new ArgumentNullException(nameof(target));
Contract.EndContractBlock();
return target.GetCustomAttributesData();
@@ -46,7 +46,7 @@ namespace System.Reflection
public static IList<CustomAttributeData> GetCustomAttributes(Assembly target)
{
if (target == null)
- throw new ArgumentNullException("target");
+ throw new ArgumentNullException(nameof(target));
Contract.EndContractBlock();
return target.GetCustomAttributesData();
@@ -55,7 +55,7 @@ namespace System.Reflection
public static IList<CustomAttributeData> GetCustomAttributes(ParameterInfo target)
{
if (target == null)
- throw new ArgumentNullException("target");
+ throw new ArgumentNullException(nameof(target));
Contract.EndContractBlock();
return target.GetCustomAttributesData();
@@ -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);
@@ -279,7 +270,7 @@ namespace System.Reflection
if (type.IsValueType)
return CustomAttributeEncoding.Undefined;
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKindOfTypeForCA"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKindOfTypeForCA"), nameof(type));
}
private static CustomAttributeType InitCustomAttributeType(RuntimeType parameterType)
{
@@ -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;
@@ -611,7 +599,7 @@ namespace System.Reflection
public CustomAttributeNamedArgument(MemberInfo memberInfo, object value)
{
if (memberInfo == null)
- throw new ArgumentNullException("memberInfo");
+ throw new ArgumentNullException(nameof(memberInfo));
Type type = null;
FieldInfo field = memberInfo as FieldInfo;
@@ -631,7 +619,7 @@ namespace System.Reflection
public CustomAttributeNamedArgument(MemberInfo memberInfo, CustomAttributeTypedArgument typedArgument)
{
if (memberInfo == null)
- throw new ArgumentNullException("memberInfo");
+ throw new ArgumentNullException(nameof(memberInfo));
m_memberInfo = memberInfo;
m_value = typedArgument;
@@ -749,11 +737,10 @@ namespace System.Reflection
return typeof(object);
default :
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)encodedType), "encodedType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)encodedType), nameof(encodedType));
}
}
- [SecuritySafeCritical]
private static object EncodedValueToRawValue(long val, CustomAttributeEncoding encodedType)
{
switch (encodedType)
@@ -795,7 +782,7 @@ namespace System.Reflection
unsafe { return *(double*)&val; }
default:
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)val), "val");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)val), nameof(val));
}
}
private static RuntimeType ResolveType(RuntimeModule scope, string typeName)
@@ -820,7 +807,7 @@ namespace System.Reflection
{
// value can be null.
if (argumentType == null)
- throw new ArgumentNullException("argumentType");
+ throw new ArgumentNullException(nameof(argumentType));
m_value = (value == null) ? null : CanonicalizeValue(value);
m_argumentType = argumentType;
@@ -830,7 +817,7 @@ namespace System.Reflection
{
// value cannot be null.
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
m_value = CanonicalizeValue(value);
m_argumentType = value.GetType();
@@ -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)
{
@@ -852,7 +839,7 @@ namespace System.Reflection
CustomAttributeEncoding encodedType = encodedArg.CustomAttributeType.EncodedType;
if (encodedType == CustomAttributeEncoding.Undefined)
- throw new ArgumentException("encodedArg");
+ throw new ArgumentException(null, nameof(encodedArg));
else if (encodedType == CustomAttributeEncoding.Enum)
{
@@ -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,18 +1010,17 @@ 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,
RuntimeModule customAttributeModule)
{
if (customAttributeModule == null)
- throw new ArgumentNullException("customAttributeModule");
+ 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)
{
@@ -1083,7 +1068,7 @@ namespace System.Reflection
public CustomAttributeNamedParameter(string argumentName, CustomAttributeEncoding fieldOrProperty, CustomAttributeType type)
{
if (argumentName == null)
- throw new ArgumentNullException("argumentName");
+ throw new ArgumentNullException(nameof(argumentName));
Contract.EndContractBlock();
m_argumentName = argumentName;
@@ -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,
@@ -1885,19 +1835,6 @@ namespace System.Reflection
return false;
}
-#if FEATURE_APTCA
- // APTCA checks
- RuntimeAssembly attributeAssembly = (RuntimeAssembly)attributeType.Assembly;
- RuntimeAssembly decoratedModuleAssembly = (RuntimeAssembly)decoratedModule.Assembly;
-
- if (attributeAssembly != lastAptcaOkAssembly &&
- !RuntimeAssembly.AptcaCheck(attributeAssembly, decoratedModuleAssembly))
- return false;
-
- // Cache last successful APTCA check (optimization)
- lastAptcaOkAssembly = decoratedModuleAssembly;
-#endif // FEATURE_APTCA
-
// Resolve the attribute ctor
ConstArray ctorSig = scope.GetMethodSignature(caRecord.tkCtor);
isVarArg = (ctorSig[0] & 0x05) != 0;
@@ -1944,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.");
}
@@ -1959,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)
{
@@ -1992,7 +1928,6 @@ namespace System.Reflection
return true;
}
- [System.Security.SecurityCritical] // auto-generated
internal static AttributeUsageAttribute GetAttributeUsage(RuntimeType decoratedAttribute)
{
RuntimeModule decoratedModule = decoratedAttribute.GetRuntimeModule();
@@ -2027,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)
{
@@ -2040,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;
@@ -2055,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)
{
@@ -2069,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);
@@ -2089,18 +2017,13 @@ namespace System.Reflection
#endregion
#region FCalls
- [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)
+ internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes)
{
- _GetSecurityAttributes(module.GetNativeHandle(), token, assembly, out securityAttributes);
+ securityAttributes = null;
}
#endregion
#region Static Constructor
- [System.Security.SecurityCritical] // auto-generated
static PseudoCustomAttribute()
{
RuntimeType[] pcas = new RuntimeType[]
@@ -2130,21 +2053,20 @@ 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
+#endregion
- #region Internal Static
+#region Internal Static
internal static bool IsSecurityAttribute(RuntimeType type)
{
#pragma warning disable 618
@@ -2152,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);
@@ -2196,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);
@@ -2221,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);
@@ -2260,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);
@@ -2286,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);
@@ -2323,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);
@@ -2351,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;
@@ -2386,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;
@@ -2403,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);
@@ -2435,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);
@@ -2458,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;
@@ -2484,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);
@@ -2522,6 +2432,6 @@ namespace System.Reflection
{
return false;
}
- #endregion
+#endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs
index 6484677c62..fb9324902a 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs
@@ -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
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
index 5e7f83f2df..9331ae193c 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
@@ -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,27 +188,15 @@ 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;
- throw new ArgumentException("module");
+ throw new ArgumentException(null, nameof(module));
}
}
@@ -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,
@@ -303,13 +251,9 @@ namespace System.Reflection.Emit
SecurityContextSource securityContextSource)
{
if (name == null)
- throw new ArgumentNullException("name");
+ 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
@@ -318,25 +262,17 @@ namespace System.Reflection.Emit
#endif // FEATURE_COLLECTIBLE_TYPES
)
{
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), "access");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), nameof(access));
}
if (securityContextSource < SecurityContextSource.CurrentAppDomain ||
securityContextSource > SecurityContextSource.CurrentAssembly)
{
- throw new ArgumentOutOfRangeException("securityContextSource");
+ throw new ArgumentOutOfRangeException(nameof(securityContextSource));
}
// 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.
@@ -379,41 +308,10 @@ namespace System.Reflection.Emit
}
else if (attribute.m_con.DeclaringType == typeof(SecurityCriticalAttribute))
{
-#if !FEATURE_CORECLR
- SecurityCriticalScope scope = SecurityCriticalScope.Everything;
- if (attribute.m_constructorArgs != null &&
- attribute.m_constructorArgs.Length == 1 &&
- attribute.m_constructorArgs[0] is SecurityCriticalScope)
- {
- scope = (SecurityCriticalScope)attribute.m_constructorArgs[0];
- }
-
- assemblyFlags |= DynamicAssemblyFlags.Critical;
- if (scope == SecurityCriticalScope.Everything)
-#endif // !FEATURE_CORECLR
{
assemblyFlags |= DynamicAssemblyFlags.AllCritical;
}
}
-#if !FEATURE_CORECLR
- else if (attribute.m_con.DeclaringType == typeof(SecurityRulesAttribute))
- {
- securityRulesBlob = new byte[attribute.m_blob.Length];
- Buffer.BlockCopy(attribute.m_blob, 0, securityRulesBlob, 0, securityRulesBlob.Length);
- }
- else if (attribute.m_con.DeclaringType == typeof(SecurityTreatAsSafeAttribute))
- {
- assemblyFlags |= DynamicAssemblyFlags.TreatAsSafe;
- }
-#endif // !FEATURE_CORECLR
-#if FEATURE_APTCA
- else if (attribute.m_con.DeclaringType == typeof(AllowPartiallyTrustedCallersAttribute))
- {
- assemblyFlags |= DynamicAssemblyFlags.Aptca;
- aptcaBlob = new byte[attribute.m_blob.Length];
- Buffer.BlockCopy(attribute.m_blob, 0, aptcaBlob, 0, aptcaBlob.Length);
- }
-#endif // FEATURE_APTCA
}
#pragma warning restore 618
}
@@ -458,7 +356,6 @@ namespace System.Reflection.Emit
}
}
- [System.Security.SecurityCritical] // auto-generated
private void InitManifestModule()
{
InternalModuleBuilder modBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule();
@@ -487,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,
@@ -500,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,
@@ -518,7 +413,6 @@ namespace System.Reflection.Emit
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Assembly nCreateDynamicAssembly(AppDomain domain,
AssemblyName name,
@@ -535,7 +429,6 @@ namespace System.Reflection.Emit
private class AssemblyBuilderLock { }
- [System.Security.SecurityCritical] // auto-generated
internal static AssemblyBuilder InternalDefineDynamicAssembly(
AssemblyName name,
AssemblyBuilderAccess access,
@@ -548,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
@@ -581,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)
@@ -592,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,
@@ -604,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
@@ -616,115 +499,38 @@ namespace System.Reflection.Emit
}
}
- [System.Security.SecurityCritical] // auto-generated
private ModuleBuilder DefineDynamicModuleInternalNoLock(
String name,
bool emitSymbolInfo, // specify if emit symbol info or not
ref StackCrawlMark stackMark)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
if (name[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), nameof(name));
Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
Contract.EndContractBlock();
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;
IntPtr pInternalSymWriter = new IntPtr();
- // create the dynamic module
-
-#if FEATURE_MULTIMODULE_ASSEMBLIES
-
-#if FEATURE_CORECLR
-#error FEATURE_MULTIMODULE_ASSEMBLIES should always go with !FEATURE_CORECLR
-#endif //FEATURE_CORECLR
-
- m_assemblyData.CheckNameConflict(name);
-
- if (m_fManifestModuleUsedAsDefinedModule == true)
- { // We need to define a new module
- int tkFile;
- InternalModuleBuilder internalDynModule = (InternalModuleBuilder)DefineDynamicModule(
- InternalAssembly,
- emitSymbolInfo,
- name,
- name,
- ref stackMark,
- ref pInternalSymWriter,
- true /*fIsTransient*/,
- out tkFile);
- dynModule = new ModuleBuilder(this, internalDynModule);
-
- // initialize the dynamic module's managed side information
- dynModule.Init(name, null, tkFile);
- }
- else
- { // We will reuse the manifest module
- m_manifestModuleBuilder.ModifyModuleName(name);
- dynModule = m_manifestModuleBuilder;
-
- if (emitSymbolInfo)
- {
- pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, name);
- }
- }
-
-#else // FEATURE_MULTIMODULE_ASSEMBLIES
- // Without FEATURE_MULTIMODULE_ASSEMBLIES only one ModuleBuilder per AssemblyBuilder can be created
+ // create the dynamic module- only one ModuleBuilder per AssemblyBuilder can be created
if (m_fManifestModuleUsedAsDefinedModule == true)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoMultiModuleAssembly"));
// Init(...) has already been called on m_manifestModuleBuilder in InitManifestModule()
dynModule = m_manifestModuleBuilder;
-#endif // FEATURE_MULTIMODULE_ASSEMBLIES
// Create the symbol writer
if (emitSymbolInfo)
{
-#if FEATURE_MULTIMODULE_ASSEMBLIES && !FEATURE_CORECLR
- // this is the code path for the desktop runtime
-
- // create the default SymWriter
- Assembly assem = LoadISymWrapper();
- Type symWriter = assem.GetType("System.Diagnostics.SymbolStore.SymWriter", true, false);
- if (symWriter != null && !symWriter.IsVisible)
- symWriter = null;
-
- if (symWriter == null)
- {
- // cannot find SymWriter - throw TypeLoadException since we couldnt find the type.
- throw new TypeLoadException(Environment.GetResourceString(ResId.MissingType, "SymWriter"));
- }
-
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-
- try
- {
- (new PermissionSet(PermissionState.Unrestricted)).Assert();
- writer = (ISymbolWriter)Activator.CreateInstance(symWriter);
-
- // Set the underlying writer for the managed writer
- // that we're using. Note that this function requires
- // unmanaged code access.
- writer.SetUnderlyingWriter(pInternalSymWriter);
- }
- finally
- {
- CodeAccessPermission.RevertAssert();
- }
-#endif // FEATURE_MULTIMODULE_ASSEMBLIES && !FEATURE_CORECLR
-
-#if !FEATURE_MULTIMODULE_ASSEMBLIES && FEATURE_CORECLR
- // this is the code path for CoreCLR
-
writer = SymWrapperCore.SymWriter.CreateSymWriter();
// Set the underlying writer for the managed writer
// that we're using. Note that this function requires
@@ -741,7 +547,6 @@ namespace System.Reflection.Emit
// In Telesto, we took the SetUnderlyingWriter method private as it's a very rickety method.
// This might someday be a good move for the desktop CLR too.
((SymWrapperCore.SymWriter)writer).InternalSetUnderlyingWriter(pInternalSymWriter);
-#endif // !FEATURE_MULTIMODULE_ASSEMBLIES && FEATURE_CORECLR
} // Creating the symbol writer
dynModule.SetSymWriter(writer);
@@ -754,174 +559,6 @@ namespace System.Reflection.Emit
return dynModule;
} // DefineDynamicModuleInternalNoLock
-
-#if !FEATURE_CORECLR
- // All dynamic modules in SilverLight are transient so we removed this overload of DefineDynamicModule
- // Note that it is assumed that !FEATURE_CORECLR always goes with FEATURE_MULTIMODULE_ASSEMBLIES
- // If we ever will build a non coreclr version of the runtime without FEATURE_MULTIMODULE_ASSEMBLIES
- // we will need to make the same changes here as the ones we made in the transient overload
-
- /**********************************************
- *
- * Defines a named dynamic module. It is an error to define multiple
- * modules within an Assembly with the same name. No symbol information
- * will be emitted.
- *
- **********************************************/
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public ModuleBuilder DefineDynamicModule(
- String name,
- String fileName)
- {
- Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- // delegate to the next DefineDynamicModule
- return DefineDynamicModuleInternal(name, fileName, false, ref stackMark);
- }
-
- /**********************************************
- *
- * Emit symbol information if emitSymbolInfo is true using the
- * default symbol writer interface.
- * An exception will be thrown if the assembly is transient.
- *
- **********************************************/
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public ModuleBuilder DefineDynamicModule(
- String name, // module name
- String fileName, // module file name
- bool emitSymbolInfo) // specify if emit symbol info or not
- {
- Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return DefineDynamicModuleInternal(name, fileName, emitSymbolInfo, ref stackMark);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private ModuleBuilder DefineDynamicModuleInternal(
- String name, // module name
- String fileName, // module file name
- bool emitSymbolInfo, // specify if emit symbol info or not
- ref StackCrawlMark stackMark) // stack crawl mark used to find caller
- {
- lock(SyncRoot)
- {
- return DefineDynamicModuleInternalNoLock(name, fileName, emitSymbolInfo, ref stackMark);
- }
- }
-
- // "name" will be used for:
- // 1. The Name field in the Module table.
- // 2. ModuleBuilder.GetModule(string).
- // "fileName" will be used for:
- // 1. The name field in the ModuleRef table when this module is being referenced by
- // another module in the same assembly.
- // 2. .file record in the in memory assembly manifest when the module is created in memory
- // 3. .file record in the on disk assembly manifest when the assembly is saved to disk
- // 4. The file name of the saved module.
- [System.Security.SecurityCritical] // auto-generated
- private ModuleBuilder DefineDynamicModuleInternalNoLock(
- String name, // module name
- String fileName, // module file name
- bool emitSymbolInfo, // specify if emit symbol info or not
- ref StackCrawlMark stackMark) // stack crawl mark used to find caller
- {
- if (name == null)
- throw new ArgumentNullException("name");
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
- if (name[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name");
-
- if (fileName == null)
- throw new ArgumentNullException("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"), "fileName");
- Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
- Contract.EndContractBlock();
-
- BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + ", " + fileName + ", " + emitSymbolInfo + " )");
- if (m_assemblyData.m_access == AssemblyBuilderAccess.Run)
- {
- // Error! You cannot define a persistable module within a transient data.
- throw new NotSupportedException(Environment.GetResourceString("Argument_BadPersistableModuleInTransientAssembly"));
- }
-
- if (m_assemblyData.m_isSaved == true)
- {
- // assembly has been saved before!
- throw new InvalidOperationException(Environment.GetResourceString(
- "InvalidOperation_CannotAlterAssembly"));
- }
-
- ModuleBuilder dynModule;
- ISymbolWriter writer = null;
- IntPtr pInternalSymWriter = new IntPtr();
-
- // create the dynamic module
-
- m_assemblyData.CheckNameConflict(name);
- m_assemblyData.CheckFileNameConflict(fileName);
-
- int tkFile;
- InternalModuleBuilder internalDynModule = (InternalModuleBuilder)DefineDynamicModule(
- InternalAssembly,
- emitSymbolInfo,
- name,
- fileName,
- ref stackMark,
- ref pInternalSymWriter,
- false /*fIsTransient*/,
- out tkFile);
- dynModule = new ModuleBuilder(this, internalDynModule);
-
- // initialize the dynamic module's managed side information
- dynModule.Init(name, fileName, tkFile);
-
- // Create the symbol writer
- if (emitSymbolInfo)
- {
- // create the default SymWriter
- Assembly assem = LoadISymWrapper();
- Type symWriter = assem.GetType("System.Diagnostics.SymbolStore.SymWriter", true, false);
- if (symWriter != null && !symWriter.IsVisible)
- symWriter = null;
-
- if (symWriter == null)
- {
- // cannot find SymWriter - throw TypeLoadException since we couldnt find the type.
- throw new TypeLoadException(Environment.GetResourceString("MissingType", "SymWriter"));
- }
- try
- {
- (new PermissionSet(PermissionState.Unrestricted)).Assert();
- writer = (ISymbolWriter)Activator.CreateInstance(symWriter);
-
- // Set the underlying writer for the managed writer
- // that we're using. Note that this function requires
- // unmanaged code access.
- writer.SetUnderlyingWriter(pInternalSymWriter);
- }
- finally
- {
- CodeAccessPermission.RevertAssert();
- }
- }
-
- dynModule.SetSymWriter(writer);
-
- m_assemblyData.AddModule(dynModule);
-
- return dynModule;
- } // DefineDynamicModuleInternalNoLock
-#endif // !FEATURE_CORECLR
#endregion
private Assembly LoadISymWrapper()
@@ -970,170 +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("name");
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
- if (fileName == null)
- throw new ArgumentNullException("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"), "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;
- }
-
-#endif // !FEATURE_CORECLR
-
- /**********************************************
- *
- * Add an existing resource file to the Assembly
- *
- **********************************************/
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- public void AddResourceFile(
- String name,
- String fileName)
- {
- AddResourceFile(name, fileName, ResourceAttributes.Public);
- }
-
- /**********************************************
- *
- * Add an existing resource file to the Assembly
- *
- **********************************************/
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- 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("name");
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
- if (fileName == null)
- throw new ArgumentNullException("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"), "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) );
- }
-
#region object overrides
public override bool Equals(object obj)
{
@@ -1172,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);
@@ -1205,9 +672,6 @@ namespace System.Reflection.Emit
public override String Location
{
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
get
{
return InternalAssembly.Location;
@@ -1224,9 +688,6 @@ namespace System.Reflection.Emit
public override String CodeBase
{
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
get
{
return InternalAssembly.CodeBase;
@@ -1249,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);
@@ -1270,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
@@ -1371,143 +802,8 @@ namespace System.Reflection.Emit
}
}
#endregion
-
-
- /**********************************************
- *
- * 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("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("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;
- }
-
-
-
/**********************************************
*
* return a dynamic module with the specified name.
@@ -1526,9 +822,9 @@ namespace System.Reflection.Emit
String name) // the name of module for the look up
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
Contract.EndContractBlock();
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.GetDynamicModule( " + name + " )");
@@ -1550,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.
@@ -1577,7 +867,7 @@ namespace System.Reflection.Emit
{
if (entryMethod == null)
- throw new ArgumentNullException("entryMethod");
+ throw new ArgumentNullException(nameof(entryMethod));
Contract.EndContractBlock();
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint");
@@ -1588,36 +878,19 @@ 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)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
- throw new ArgumentNullException("binaryAttribute");
+ throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
lock(SyncRoot)
@@ -1626,7 +899,6 @@ namespace System.Reflection.Emit
}
}
- [System.Security.SecurityCritical] // auto-generated
private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute)
{
TypeBuilder.DefineCustomAttribute(
@@ -1648,12 +920,11 @@ 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)
{
- throw new ArgumentNullException("customBuilder");
+ throw new ArgumentNullException(nameof(customBuilder));
}
Contract.EndContractBlock();
@@ -1663,7 +934,6 @@ namespace System.Reflection.Emit
}
}
- [System.Security.SecurityCritical] // auto-generated
private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)
{
customBuilder.CreateCustomAttribute(
@@ -1693,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)
{
@@ -1703,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("assemblyFileName");
- if (assemblyFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "assemblyFileName");
- if (!String.Equals(assemblyFileName, Path.GetFileName(assemblyFileName)))
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "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;
}
@@ -2065,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;
@@ -2080,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;
@@ -2107,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,
@@ -2145,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,
@@ -2171,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,
@@ -2186,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,
@@ -2207,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,
@@ -2217,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,
@@ -2226,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
@@ -2234,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,
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
index 00a961dd89..5c86d8ec87 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
@@ -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
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
index f1a38c611b..f0f83e7d2a 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
@@ -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
@@ -242,7 +236,7 @@ namespace System.Reflection.Emit {
}
// CultureInfo attribute overrides the lcid from AssemblyName.
CultureInfo culture = new CultureInfo(m_CABuilders[i].m_constructorArgs[0].ToString());
-#if FEATURE_USE_LCID
+#if FEATURE_USE_LCID
m_nativeVersion.m_lcid = culture.LCID;
#endif
}
@@ -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;
diff --git a/src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs b/src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs
index 0d8ce5a8d4..8dba934bde 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs
@@ -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
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
index e5062d3365..ef76adcf80 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
@@ -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("pset");
-
-#pragma warning disable 618
- if (!Enum.IsDefined(typeof(SecurityAction), action) ||
- action == SecurityAction.RequestMinimum ||
- action == SecurityAction.RequestOptional ||
- action == SecurityAction.RequestRefuse)
- {
- throw new ArgumentOutOfRangeException("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
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
index 2a29a5c190..545657a053 100644
--- a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
@@ -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)]
@@ -70,8 +70,14 @@ namespace System.Reflection.Emit {
// Check that a type is suitable for use in a custom attribute.
private bool ValidateType(Type t)
{
- if (t.IsPrimitive || t == typeof(String) || t == typeof(Type))
+ if (t.IsPrimitive)
+ {
+ return t != typeof(IntPtr) && t != typeof(UIntPtr);
+ }
+ if (t == typeof(String) || t == typeof(Type))
+ {
return true;
+ }
if (t.IsEnum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(t)))
@@ -103,17 +109,17 @@ namespace System.Reflection.Emit {
FieldInfo[] namedFields, Object[] fieldValues)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (constructorArgs == null)
- throw new ArgumentNullException("constructorArgs");
+ throw new ArgumentNullException(nameof(constructorArgs));
if (namedProperties == null)
- throw new ArgumentNullException("namedProperties");
+ throw new ArgumentNullException(nameof(namedProperties));
if (propertyValues == null)
- throw new ArgumentNullException("propertyValues");
+ throw new ArgumentNullException(nameof(propertyValues));
if (namedFields == null)
- throw new ArgumentNullException("namedFields");
+ throw new ArgumentNullException(nameof(namedFields));
if (fieldValues == null)
- throw new ArgumentNullException("fieldValues");
+ throw new ArgumentNullException(nameof(fieldValues));
if (namedProperties.Length != propertyValues.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedProperties, propertyValues");
if (namedFields.Length != fieldValues.Length)
@@ -123,7 +129,7 @@ namespace System.Reflection.Emit {
if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
(con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructor"));
-
+
if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard)
throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructorCallConv"));
@@ -150,12 +156,16 @@ namespace System.Reflection.Emit {
// Now verify that the types of the actual parameters are compatible with the types of the formal parameters.
for (i = 0; i < paramTypes.Length; i++)
{
- if (constructorArgs[i] == null)
+ object constructorArg = constructorArgs[i];
+ if (constructorArg == null)
+ {
+ if (paramTypes[i].IsValueType)
+ {
+ throw new ArgumentNullException($"{nameof(constructorArgs)}[{i}]");
+ }
continue;
- TypeCode paramTC = Type.GetTypeCode(paramTypes[i]);
- if (paramTC != Type.GetTypeCode(constructorArgs[i].GetType()))
- if (paramTC != TypeCode.Object || !ValidateType(constructorArgs[i].GetType()))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForConstructor", i));
+ }
+ VerifyTypeAndPassedObjectType(paramTypes[i], constructorArg.GetType(), $"{nameof(constructorArgs)}[{i}]");
}
// Allocate a memory stream to represent the CA blob in the metadata and a binary writer to help format it.
@@ -176,12 +186,14 @@ namespace System.Reflection.Emit {
for (i = 0; i < namedProperties.Length; i++)
{
// Validate the property.
- if (namedProperties[i] == null)
+ PropertyInfo property = namedProperties[i];
+ if (property == null)
throw new ArgumentNullException("namedProperties[" + i + "]");
// Allow null for non-primitive types only.
- Type propType = namedProperties[i].PropertyType;
- if (propertyValues[i] == null && propType.IsPrimitive)
+ Type propType = property.PropertyType;
+ object propertyValue = propertyValues[i];
+ if (propertyValue == null && propType.IsValueType)
throw new ArgumentNullException("propertyValues[" + i + "]");
// Validate property type.
@@ -189,55 +201,57 @@ namespace System.Reflection.Emit {
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Property has to be writable.
- if (!namedProperties[i].CanWrite)
+ if (!property.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_NotAWritableProperty"));
-
+
// Property has to be from the same class or base class as ConstructorInfo.
- if (namedProperties[i].DeclaringType != con.DeclaringType
+ if (property.DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
- && !con.DeclaringType.IsSubclassOf(namedProperties[i].DeclaringType))
+ && !con.DeclaringType.IsSubclassOf(property.DeclaringType))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// separately.
- if (!TypeBuilder.IsTypeEqual(namedProperties[i].DeclaringType, con.DeclaringType))
+ if (!TypeBuilder.IsTypeEqual(property.DeclaringType, con.DeclaringType))
{
// IsSubclassOf is overloaded to do the right thing if
// the constructor is a TypeBuilder, but we still need
// to deal with the case where the property's declaring
// type is one.
- if (!(namedProperties[i].DeclaringType is TypeBuilder) ||
- !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedProperties[i].DeclaringType).BakedRuntimeType))
+ if (!(property.DeclaringType is TypeBuilder) ||
+ !con.DeclaringType.IsSubclassOf(((TypeBuilder)property.DeclaringType).BakedRuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadPropertyForConstructorBuilder"));
}
}
// Make sure the property's type can take the given value.
// Note that there will be no coersion.
- if (propertyValues[i] != null &&
- propType != typeof(Object) &&
- Type.GetTypeCode(propertyValues[i].GetType()) != Type.GetTypeCode(propType))
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
-
+ if (propertyValue != null)
+ {
+ VerifyTypeAndPassedObjectType(propType, propertyValue.GetType(), $"{nameof(propertyValues)}[{i}]");
+ }
+
// First a byte indicating that this is a property.
writer.Write((byte)CustomAttributeEncoding.Property);
// Emit the property type, name and value.
EmitType(writer, propType);
EmitString(writer, namedProperties[i].Name);
- EmitValue(writer, propType, propertyValues[i]);
+ EmitValue(writer, propType, propertyValue);
}
// Emit all the field sets.
for (i = 0; i < namedFields.Length; i++)
{
// Validate the field.
- if (namedFields[i] == null)
+ FieldInfo namedField = namedFields[i];
+ if (namedField == null)
throw new ArgumentNullException("namedFields[" + i + "]");
// Allow null for non-primitive types only.
- Type fldType = namedFields[i].FieldType;
- if (fieldValues[i] == null && fldType.IsPrimitive)
+ Type fldType = namedField.FieldType;
+ object fieldValue = fieldValues[i];
+ if (fieldValue == null && fldType.IsValueType)
throw new ArgumentNullException("fieldValues[" + i + "]");
// Validate field type.
@@ -245,20 +259,20 @@ namespace System.Reflection.Emit {
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Field has to be from the same class or base class as ConstructorInfo.
- if (namedFields[i].DeclaringType != con.DeclaringType
+ if (namedField.DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
- && !con.DeclaringType.IsSubclassOf(namedFields[i].DeclaringType))
+ && !con.DeclaringType.IsSubclassOf(namedField.DeclaringType))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// separately.
- if (!TypeBuilder.IsTypeEqual(namedFields[i].DeclaringType, con.DeclaringType))
+ if (!TypeBuilder.IsTypeEqual(namedField.DeclaringType, con.DeclaringType))
{
// IsSubclassOf is overloaded to do the right thing if
// the constructor is a TypeBuilder, but we still need
// to deal with the case where the field's declaring
// type is one.
- if (!(namedFields[i].DeclaringType is TypeBuilder) ||
+ if (!(namedField.DeclaringType is TypeBuilder) ||
!con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldForConstructorBuilder"));
}
@@ -266,24 +280,36 @@ namespace System.Reflection.Emit {
// Make sure the field's type can take the given value.
// Note that there will be no coersion.
- if (fieldValues[i] != null &&
- fldType != typeof(Object) &&
- Type.GetTypeCode(fieldValues[i].GetType()) != Type.GetTypeCode(fldType))
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
+ if (fieldValue != null)
+ {
+ VerifyTypeAndPassedObjectType(fldType, fieldValue.GetType(), $"{nameof(fieldValues)}[{i}]");
+ }
// First a byte indicating that this is a field.
writer.Write((byte)CustomAttributeEncoding.Field);
// Emit the field type, name and value.
EmitType(writer, fldType);
- EmitString(writer, namedFields[i].Name);
- EmitValue(writer, fldType, fieldValues[i]);
+ EmitString(writer, namedField.Name);
+ EmitValue(writer, fldType, fieldValue);
}
// Create the blob array.
m_blob = ((MemoryStream)writer.BaseStream).ToArray();
}
+ private static void VerifyTypeAndPassedObjectType(Type type, Type passedType, string paramName)
+ {
+ if (type != typeof(object) && Type.GetTypeCode(passedType) != Type.GetTypeCode(type))
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
+ }
+ if (passedType == typeof(IntPtr) || passedType == typeof(UIntPtr))
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB"), paramName);
+ }
+ }
+
private void EmitType(BinaryWriter writer, Type type)
{
if (type.IsPrimitive)
@@ -327,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;
}
}
@@ -411,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;
}
}
@@ -489,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;
}
}
@@ -524,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);
@@ -537,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;
@@ -546,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;
diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
index b66fdad1e2..9e1d82986a 100644
--- a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
@@ -9,7 +9,6 @@ namespace System.Reflection.Emit
using System;
using System.Globalization;
- using TextWriter = System.IO.TextWriter;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices;
using System.Reflection;
@@ -17,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;
@@ -36,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,
@@ -62,7 +61,7 @@ namespace System.Reflection.Emit
{
LocalBuilder localBuilder;
if (localType == null)
- throw new ArgumentNullException("localType");
+ throw new ArgumentNullException(nameof(localType));
Contract.EndContractBlock();
RuntimeType rtType = localType as RuntimeType;
@@ -87,11 +86,10 @@ namespace System.Reflection.Emit
// Token resolution calls
//
//
- [System.Security.SecuritySafeCritical] // auto-generated
public override void Emit(OpCode opcode, MethodInfo meth)
{
if (meth == null)
- throw new ArgumentNullException("meth");
+ throw new ArgumentNullException(nameof(meth));
Contract.EndContractBlock();
int stackchange = 0;
@@ -101,7 +99,7 @@ namespace System.Reflection.Emit
{
RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo;
if (rtMeth == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "meth");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(meth));
RuntimeType declaringType = rtMeth.GetRuntimeType();
if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
@@ -148,12 +146,12 @@ namespace System.Reflection.Emit
public override void Emit(OpCode opcode, ConstructorInfo con)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
Contract.EndContractBlock();
RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo;
if (rtConstructor == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "con");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(con));
RuntimeType declaringType = rtConstructor.GetRuntimeType();
int token;
@@ -176,7 +174,7 @@ namespace System.Reflection.Emit
public override void Emit(OpCode opcode, Type type)
{
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
@@ -193,12 +191,12 @@ namespace System.Reflection.Emit
public override void Emit(OpCode opcode, FieldInfo field)
{
if (field == null)
- throw new ArgumentNullException("field");
+ throw new ArgumentNullException(nameof(field));
Contract.EndContractBlock();
RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo;
if (runtimeField == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), "field");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(field));
int token;
if (field.DeclaringType == null)
@@ -214,7 +212,7 @@ namespace System.Reflection.Emit
public override void Emit(OpCode opcode, String str)
{
if (str == null)
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
Contract.EndContractBlock();
int tempVal = GetTokenForString(str);
@@ -228,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,
@@ -307,20 +304,19 @@ namespace System.Reflection.Emit
PutInteger4(token);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
{
if (methodInfo == null)
- throw new ArgumentNullException("methodInfo");
+ throw new ArgumentNullException(nameof(methodInfo));
if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
- throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode));
if (methodInfo.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo");
+ throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo");
+ throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
Contract.EndContractBlock();
int tk;
@@ -351,7 +347,7 @@ namespace System.Reflection.Emit
public override void Emit(OpCode opcode, SignatureHelper signature)
{
if (signature == null)
- throw new ArgumentNullException("signature");
+ throw new ArgumentNullException(nameof(signature));
Contract.EndContractBlock();
int stackchange = 0;
@@ -365,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;
@@ -421,7 +417,7 @@ namespace System.Reflection.Emit
{
// execute this branch if previous clause is Catch or Fault
if (exceptionType == null)
- throw new ArgumentNullException("exceptionType");
+ throw new ArgumentNullException(nameof(exceptionType));
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
@@ -482,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;
@@ -494,7 +489,7 @@ namespace System.Reflection.Emit
DynamicMethod dm = methodInfo as DynamicMethod;
if (rtMeth == null && dm == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "methodInfo");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(methodInfo));
ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy();
if (paramInfo != null && paramInfo.Length != 0)
@@ -519,7 +514,6 @@ namespace System.Reflection.Emit
return GetTokenForVarArgMethod(dm, sig);
}
- [System.Security.SecurityCritical] // auto-generated
internal override SignatureHelper GetMemberRefSignature(
CallingConventions call,
Type returnType,
@@ -704,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;
@@ -774,7 +765,6 @@ namespace System.Reflection.Emit
{
internal RuntimeMethodHandleInternal m_methodHandle;
- [System.Security.SecuritySafeCritical] // auto-generated
~DestroyScout()
{
if (m_methodHandle.IsNullHandle())
@@ -887,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;
@@ -922,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();
@@ -1003,9 +991,6 @@ namespace System.Reflection.Emit
}
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public class DynamicILInfo
{
@@ -1032,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,
@@ -1064,15 +1048,14 @@ namespace System.Reflection.Emit
m_maxStackSize = maxStackSize;
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe void SetCode(byte* code, int codeSize, int maxStackSize)
{
if (codeSize < 0)
- throw new ArgumentOutOfRangeException("codeSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(codeSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (codeSize > 0 && code == null)
- throw new ArgumentNullException("code");
+ throw new ArgumentNullException(nameof(code));
Contract.EndContractBlock();
m_code = new byte[codeSize];
@@ -1090,15 +1073,14 @@ 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)
{
if (exceptionsSize < 0)
- throw new ArgumentOutOfRangeException("exceptionsSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(exceptionsSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (exceptionsSize > 0 && exceptions == null)
- throw new ArgumentNullException("exceptions");
+ throw new ArgumentNullException(nameof(exceptions));
Contract.EndContractBlock();
m_exceptions = new byte[exceptionsSize];
@@ -1115,15 +1097,14 @@ 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)
{
if (signatureSize < 0)
- throw new ArgumentOutOfRangeException("signatureSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(signatureSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (signatureSize > 0 && localSignature == null)
- throw new ArgumentNullException("localSignature");
+ throw new ArgumentNullException(nameof(localSignature));
Contract.EndContractBlock();
m_localSignature = new byte[signatureSize];
@@ -1136,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);
@@ -1222,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();
diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
index 6f6b436706..1b8c97de65 100644
--- a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
@@ -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.
@@ -419,7 +368,7 @@ namespace System.Reflection.Emit
m_methodHandle = null;
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck)
@@ -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("m");
+ 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"), "m");
- }
-
- // The user cannot explicitly use this assembly
- if (rtModule == s_anonymouslyHostedDynamicMethodsModule)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"), "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("owner");
-#if !FEATURE_CORECLR
-
- RuntimeType rtOwner = owner as RuntimeType;
- if (rtOwner == null)
- rtOwner = owner.UnderlyingSystemType as RuntimeType;
-
- if (rtOwner == null)
- throw new ArgumentNullException("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
+ throw new ArgumentNullException(nameof(owner));
}
//
// 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,83 +505,19 @@ namespace System.Reflection.Emit
public override bool IsSecurityCritical
{
- [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();
- }
- }
+ get { return true; }
}
public override bool IsSecuritySafeCritical
{
- [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();
- }
- }
+ get { return false; }
}
public override bool IsSecurityTransparent
{
- [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();
- }
- }
+ get { return false; }
}
- [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"));
@@ -789,7 +594,6 @@ namespace System.Reflection.Emit
return null;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public DynamicILInfo GetDynamicILInfo()
{
#pragma warning disable 618
@@ -802,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)
@@ -819,7 +622,6 @@ namespace System.Reflection.Emit
return GetILGenerator(64);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public ILGenerator GetILGenerator(int streamSize)
{
if (m_ilGenerator == null)
@@ -935,7 +737,7 @@ namespace System.Reflection.Emit
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) {
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
@@ -951,7 +753,7 @@ namespace System.Reflection.Emit
public override bool IsDefined(Type attributeType, bool inherit) {
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
diff --git a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
index f8e3ab2991..82dc2828ca 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
@@ -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
@@ -407,36 +402,13 @@ namespace System.Reflection.Emit {
{
// Client should not set any bits other than the visibility bits.
if ((visibility & ~TypeAttributes.VisibilityMask) != 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_ShouldOnlySetVisibilityFlags"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ShouldOnlySetVisibilityFlags"), nameof(name));
m_typeBuilder = new TypeBuilder(name, visibility | TypeAttributes.Sealed, typeof(System.Enum), null, module, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize, null);
// Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
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
diff --git a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
index 42a5252102..449b20824c 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
@@ -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,12 +57,11 @@ namespace System.Reflection.Emit {
return m_evToken;
}
- [System.Security.SecurityCritical] // auto-generated
private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics)
{
if (mdBuilder == null)
{
- throw new ArgumentNullException("mdBuilder");
+ throw new ArgumentNullException(nameof(mdBuilder));
}
Contract.EndContractBlock();
@@ -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,18 +95,13 @@ 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)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
- throw new ArgumentNullException("binaryAttribute");
+ throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
m_type.ThrowIfCreated();
@@ -125,41 +114,17 @@ 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)
{
- throw new ArgumentNullException("customBuilder");
+ throw new ArgumentNullException(nameof(customBuilder));
}
Contract.EndContractBlock();
m_type.ThrowIfCreated();
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;
}
-
-
-
-
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
index 0f2de5be43..595d60ada0 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
@@ -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,21 +28,20 @@ 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)
{
if (fieldName == null)
- throw new ArgumentNullException("fieldName");
+ throw new ArgumentNullException(nameof(fieldName));
if (fieldName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "fieldName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(fieldName));
if (fieldName[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "fieldName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(fieldName));
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
if (type == typeof(void))
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldType"));
@@ -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,12 +185,11 @@ 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)
{
if (unmanagedMarshal == null)
- throw new ArgumentNullException("unmanagedMarshal");
+ throw new ArgumentNullException(nameof(unmanagedMarshal));
Contract.EndContractBlock();
m_typeBuilder.ThrowIfCreated();
@@ -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,19 +207,14 @@ 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)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
- throw new ArgumentNullException("binaryAttribute");
+ throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder;
@@ -240,11 +225,10 @@ 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)
- throw new ArgumentNullException("customBuilder");
+ throw new ArgumentNullException(nameof(customBuilder));
Contract.EndContractBlock();
m_typeBuilder.ThrowIfCreated();
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
index 5bfe5bb7bb..31bb564cf4 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
@@ -26,11 +26,8 @@ public enum FlowControl
Cond_Branch = 3,
Meta = 4,
Next = 5,
-#if !FEATURE_CORECLR
- /// <internalonly/>
[Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
Phi = 6,
-#endif
Return = 7,
Throw = 8,
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
index bcf70dbe46..6987ea139d 100644
--- a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
index 15dece9fcb..ed0763bfda 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
@@ -7,12 +7,12 @@
namespace System.Reflection.Emit
{
using System;
- using TextWriter = System.IO.TextWriter;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Security.Permissions;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[ClassInterface(ClassInterfaceType.None)]
@@ -210,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)
{
@@ -414,7 +411,7 @@ namespace System.Reflection.Emit
{
if (m_RelocFixupCount == 0)
{
- Contract.Assert(m_RelocFixupList == null);
+ Debug.Assert(m_RelocFixupList == null);
return null;
}
@@ -472,11 +469,10 @@ namespace System.Reflection.Emit
PutInteger4(arg);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public virtual void Emit(OpCode opcode, MethodInfo meth)
{
if (meth == null)
- throw new ArgumentNullException("meth");
+ throw new ArgumentNullException(nameof(meth));
Contract.EndContractBlock();
if (opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))
@@ -504,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)
{
@@ -593,14 +588,13 @@ 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)
- throw new ArgumentNullException("methodInfo");
+ throw new ArgumentNullException(nameof(methodInfo));
if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
- throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode));
Contract.EndContractBlock();
@@ -634,7 +628,7 @@ namespace System.Reflection.Emit
public virtual void Emit(OpCode opcode, SignatureHelper signature)
{
if (signature == null)
- throw new ArgumentNullException("signature");
+ throw new ArgumentNullException(nameof(signature));
Contract.EndContractBlock();
int stackchange = 0;
@@ -653,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;
@@ -666,12 +660,11 @@ namespace System.Reflection.Emit
PutInteger4(tempVal);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public virtual void Emit(OpCode opcode, ConstructorInfo con)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
Contract.EndContractBlock();
int stackchange = 0;
@@ -687,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++;
@@ -695,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.");
@@ -710,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
@@ -750,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);
@@ -761,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);
@@ -805,7 +795,7 @@ namespace System.Reflection.Emit
public virtual void Emit(OpCode opcode, Label[] labels)
{
if (labels == null)
- throw new ArgumentNullException("labels");
+ throw new ArgumentNullException(nameof(labels));
Contract.EndContractBlock();
// Emitting a switch table
@@ -854,13 +844,13 @@ namespace System.Reflection.Emit
if (local == null)
{
- throw new ArgumentNullException("local");
+ throw new ArgumentNullException(nameof(local));
}
Contract.EndContractBlock();
int tempVal = local.GetLocalIndex();
if (local.GetMethodBuilder() != m_methodBuilder)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_UnmatchedMethodForLocal"), "local");
+ throw new ArgumentException(Environment.GetResourceString("Argument_UnmatchedMethodForLocal"), nameof(local));
}
// If the instruction is a ldloc, ldloca a stloc, morph it to the optimal form.
if (opcode.Equals(OpCodes.Ldloc))
@@ -1020,7 +1010,7 @@ namespace System.Reflection.Emit
public virtual void BeginExceptFilterBlock()
{
- // Begins a eception filter block. Emits a branch instruction to the end of the current exception block.
+ // Begins an exception filter block. Emits a branch instruction to the end of the current exception block.
if (m_currExcStackCount == 0)
throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
@@ -1051,7 +1041,7 @@ namespace System.Reflection.Emit
} else {
// execute this branch if previous clause is Catch or Fault
if (exceptionType==null) {
- throw new ArgumentNullException("exceptionType");
+ throw new ArgumentNullException(nameof(exceptionType));
}
Label endLabel = current.GetEndLabel();
@@ -1153,7 +1143,7 @@ namespace System.Reflection.Emit
// Emits the il to throw an exception
if (excType==null) {
- throw new ArgumentNullException("excType");
+ throw new ArgumentNullException(nameof(excType));
}
if (!excType.IsSubclassOf(typeof(Exception)) && excType!=typeof(Exception)) {
@@ -1212,9 +1202,9 @@ namespace System.Reflection.Emit
throw new ArgumentException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder"));
}
parameterTypes[0] = (Type)cls;
- MethodInfo mi = typeof(TextWriter).GetMethod("WriteLine", parameterTypes);
+ MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes);
if (mi==null) {
- throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), "localBuilder");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), nameof(localBuilder));
}
Emit(OpCodes.Callvirt, mi);
@@ -1231,7 +1221,7 @@ namespace System.Reflection.Emit
if (fld == null)
{
- throw new ArgumentNullException("fld");
+ throw new ArgumentNullException(nameof(fld));
}
Contract.EndContractBlock();
@@ -1250,9 +1240,9 @@ namespace System.Reflection.Emit
throw new NotSupportedException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder"));
}
parameterTypes[0] = (Type)cls;
- MethodInfo mi = typeof(TextWriter).GetMethod("WriteLine", parameterTypes);
+ MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes);
if (mi==null) {
- throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), "fld");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), nameof(fld));
}
Emit(OpCodes.Callvirt, mi);
}
@@ -1283,7 +1273,7 @@ namespace System.Reflection.Emit
}
if (localType==null) {
- throw new ArgumentNullException("localType");
+ throw new ArgumentNullException(nameof(localType));
}
if (methodBuilder.m_bIsBaked) {
@@ -1304,10 +1294,10 @@ namespace System.Reflection.Emit
// for the current active lexical scope.
if (usingNamespace == null)
- throw new ArgumentNullException("usingNamespace");
+ throw new ArgumentNullException(nameof(usingNamespace));
if (usingNamespace.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "usingNamespace");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(usingNamespace));
Contract.EndContractBlock();
int index;
@@ -1335,7 +1325,7 @@ namespace System.Reflection.Emit
{
if (startLine == 0 || startLine < 0 || endLine == 0 || endLine < 0)
{
- throw new ArgumentOutOfRangeException("startLine");
+ throw new ArgumentOutOfRangeException(nameof(startLine));
}
Contract.EndContractBlock();
m_LineNumberInfo.AddLineNumberInfo(document, m_length, startLine, startColumn, endLine, endColumn);
@@ -1362,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
@@ -1472,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;
}
}
@@ -1489,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;
}
}
@@ -1531,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;
}
@@ -1596,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;
@@ -1606,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;
@@ -1762,9 +1730,6 @@ namespace System.Reflection.Emit
}
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal void EmitScopeTree(ISymbolWriter symWriter)
{
int i;
@@ -1821,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);
}
@@ -1874,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++)
@@ -1912,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();
@@ -1968,9 +1930,6 @@ namespace System.Reflection.Emit
}
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal void EmitLineNumberInfo(ISymbolWriter symWriter)
{
int[] iOffsetsTemp;
diff --git a/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs b/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
index 00fdd00315..a737895829 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
@@ -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
-
diff --git a/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
index 4008703ca7..a34d5ebe5d 100644
--- a/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
index 015a73be09..654e166a05 100644
--- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
@@ -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
@@ -90,16 +90,16 @@ namespace System.Reflection.Emit
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
if (name[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name));
if (mod == null)
- throw new ArgumentNullException("mod");
+ throw new ArgumentNullException(nameof(mod));
Contract.EndContractBlock();
if (parameterTypes != null)
@@ -107,7 +107,7 @@ namespace System.Reflection.Emit
foreach(Type t in parameterTypes)
{
if (t == null)
- throw new ArgumentNullException("parameterTypes");
+ throw new ArgumentNullException(nameof(parameterTypes));
}
}
@@ -196,14 +196,13 @@ 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
// queries this instance to get all of the information which it needs.
if (il == null)
{
- throw new ArgumentNullException("il");
+ throw new ArgumentNullException(nameof(il));
}
Contract.EndContractBlock();
@@ -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,17 +595,17 @@ namespace System.Reflection.Emit
public override bool IsSecurityCritical
{
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
+ get { return true; }
}
public override bool IsSecuritySafeCritical
{
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
+ get { return false; }
}
public override bool IsSecurityTransparent
{
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
+ get { return false; }
}
#endregion
@@ -693,10 +689,10 @@ namespace System.Reflection.Emit
public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
{
if (names == null)
- throw new ArgumentNullException("names");
+ throw new ArgumentNullException(nameof(names));
if (names.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "names");
+ throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(names));
Contract.EndContractBlock();
if (m_inst != null)
@@ -704,7 +700,7 @@ namespace System.Reflection.Emit
for (int i = 0; i < names.Length; i ++)
if (names[i] == null)
- throw new ArgumentNullException("names");
+ throw new ArgumentNullException(nameof(names));
if (m_tkMethod.Token != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBuilderBaked"));
@@ -721,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
@@ -767,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);
@@ -841,7 +835,6 @@ namespace System.Reflection.Emit
}
- [System.Security.SecuritySafeCritical] // auto-generated
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName)
{
if (position < 0)
@@ -858,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)
{
@@ -915,55 +907,15 @@ 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("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("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)
{
- throw new ArgumentNullException("il", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(il), Environment.GetResourceString("ArgumentNull_Array"));
}
if (maxStack < 0)
{
- throw new ArgumentOutOfRangeException("maxStack", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(maxStack), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -1056,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();
@@ -1075,7 +1024,7 @@ namespace System.Reflection.Emit
if (il != null && (count < 0 || count > il.Length))
{
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (il == null)
@@ -1095,7 +1044,6 @@ namespace System.Reflection.Emit
m_bIsBaked = true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetImplementationFlags(MethodImplAttributes attributes)
{
ThrowIfGeneric ();
@@ -1158,7 +1106,6 @@ namespace System.Reflection.Emit
public String Signature
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return GetMethodSignature().ToString();
@@ -1166,18 +1113,13 @@ 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)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
- throw new ArgumentNullException("binaryAttribute");
+ throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
ThrowIfGeneric();
@@ -1191,11 +1133,10 @@ namespace System.Reflection.Emit
ParseCA(con, binaryAttribute);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
- throw new ArgumentNullException("customBuilder");
+ throw new ArgumentNullException(nameof(customBuilder));
Contract.EndContractBlock();
ThrowIfGeneric();
@@ -1239,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
@@ -1366,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;
@@ -1468,51 +1383,51 @@ namespace System.Reflection.Emit
{
if (tryOffset < 0)
{
- throw new ArgumentOutOfRangeException("tryOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(tryOffset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (tryLength < 0)
{
- throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(tryLength), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (filterOffset < 0)
{
- throw new ArgumentOutOfRangeException("filterOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(filterOffset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (handlerOffset < 0)
{
- throw new ArgumentOutOfRangeException("handlerOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(handlerOffset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (handlerLength < 0)
{
- throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(handlerLength), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if ((long)tryOffset + tryLength > Int32.MaxValue)
{
- throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - tryOffset));
+ throw new ArgumentOutOfRangeException(nameof(tryLength), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - tryOffset));
}
if ((long)handlerOffset + handlerLength > Int32.MaxValue)
{
- throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - handlerOffset));
+ throw new ArgumentOutOfRangeException(nameof(handlerLength), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - handlerOffset));
}
// Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it,
// and we can't check for valid tokens until the module is baked.
if (kind == ExceptionHandlingClauseOptions.Clause && (exceptionTypeToken & 0x00FFFFFF) == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", exceptionTypeToken), "exceptionTypeToken");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", exceptionTypeToken), nameof(exceptionTypeToken));
}
Contract.EndContractBlock();
if (!IsValidKind(kind))
{
- throw new ArgumentOutOfRangeException("kind", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(kind), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
}
m_tryStartOffset = tryOffset;
@@ -1527,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;
diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
index ce2a592ae2..6884f50b0e 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
@@ -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,13 +357,12 @@ 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
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
Contract.EndContractBlock();
int tr;
@@ -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
@@ -589,7 +462,7 @@ namespace System.Reflection.Emit
}
#endregion
-
+
#region Module Overrides
// m_internalModuleBuilder is null iff this is a "internal" ModuleBuilder
@@ -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;
@@ -962,7 +828,7 @@ namespace System.Reflection.Emit
if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null)
{
fullyQualifiedName = Path.Combine(ContainingAssemblyBuilder.m_assemblyData.m_strDir, fullyQualifiedName);
- fullyQualifiedName = Path.UnsafeGetFullPath(fullyQualifiedName);
+ fullyQualifiedName = Path.GetFullPath(fullyQualifiedName);
}
if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null && fullyQualifiedName != null)
@@ -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,178 +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("name");
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "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"));
- }
- }
-#endif // !FEATURE_CORECLR
-
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
- public void DefineManifestResource(String name, Stream stream, ResourceAttributes attribute)
- {
- if (name == null)
- throw new ArgumentNullException("name");
-
- if (stream == null)
- throw new ArgumentNullException("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 !FEATURE_CORECLR
- if (name == null)
- throw new ArgumentNullException("name");
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "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"));
- }
-#endif // !FEATURE_CORECLR
- }
-
-
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
- public void DefineUnmanagedResource(Byte[] resource)
- {
- lock(SyncRoot)
- {
- DefineUnmanagedResourceInternalNoLock(resource);
- }
- }
-
- internal void DefineUnmanagedResourceInternalNoLock(Byte[] resource)
- {
- if (resource == null)
- throw new ArgumentNullException("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);
- }
-
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
- 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("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;
- }
#endregion
#region Define Global Method
@@ -1453,10 +1119,10 @@ namespace System.Reflection.Emit
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
if ((attributes & MethodAttributes.Static) == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
@@ -1475,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)
@@ -1487,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)
@@ -1503,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)
@@ -1548,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.
@@ -1564,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.
@@ -1583,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);
@@ -1596,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.
@@ -1623,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)
@@ -1638,17 +1281,15 @@ 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)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
CheckContext(type);
@@ -1710,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))
{
@@ -1753,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)
@@ -1762,7 +1389,6 @@ namespace System.Reflection.Emit
}
}
- [System.Security.SecurityCritical] // auto-generated
internal MethodToken GetMethodTokenInternal(MethodInfo method)
{
lock(SyncRoot)
@@ -1775,13 +1401,12 @@ 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
// return the MethodDef token.
if (method == null)
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
int tr;
@@ -1885,12 +1510,11 @@ namespace System.Reflection.Emit
return new MethodToken(mr);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public MethodToken GetConstructorToken(ConstructorInfo constructor, IEnumerable<Type> optionalParameterTypes)
{
if (constructor == null)
{
- throw new ArgumentNullException("constructor");
+ throw new ArgumentNullException(nameof(constructor));
}
lock (SyncRoot)
@@ -1900,12 +1524,11 @@ namespace System.Reflection.Emit
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public MethodToken GetMethodToken(MethodInfo method, IEnumerable<Type> optionalParameterTypes)
{
if (method == null)
{
- throw new ArgumentNullException("method");
+ throw new ArgumentNullException(nameof(method));
}
// useMethodDef flag only affects the result if we pass in a generic method definition.
@@ -1922,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;
@@ -1931,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;
@@ -1989,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)
{
@@ -1999,18 +1620,17 @@ namespace System.Reflection.Emit
}
}
- [System.Security.SecurityCritical] // auto-generated
private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes)
{
if (arrayClass == null)
- throw new ArgumentNullException("arrayClass");
+ throw new ArgumentNullException(nameof(arrayClass));
if (methodName == null)
- throw new ArgumentNullException("methodName");
+ throw new ArgumentNullException(nameof(methodName));
if (methodName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "methodName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(methodName));
if (arrayClass.IsArray == false)
throw new ArgumentException(Environment.GetResourceString("Argument_HasToBeArrayClass"));
@@ -2035,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)
{
@@ -2052,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)
{
@@ -2060,7 +1678,6 @@ namespace System.Reflection.Emit
return InternalGetConstructorToken(con, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public FieldToken GetFieldToken(FieldInfo field)
{
lock(SyncRoot)
@@ -2069,7 +1686,6 @@ namespace System.Reflection.Emit
}
}
- [System.Security.SecurityCritical] // auto-generated
private FieldToken GetFieldTokenNoLock(FieldInfo field)
{
if (field == null) {
@@ -2158,12 +1774,11 @@ namespace System.Reflection.Emit
return new FieldToken(mr, field.GetType());
}
- [System.Security.SecuritySafeCritical] // auto-generated
public StringToken GetStringConstant(String str)
{
if (str == null)
{
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
@@ -2172,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
@@ -2180,7 +1794,7 @@ namespace System.Reflection.Emit
if (sigHelper == null)
{
- throw new ArgumentNullException("sigHelper");
+ throw new ArgumentNullException(nameof(sigHelper));
}
Contract.EndContractBlock();
@@ -2191,11 +1805,10 @@ 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)
- throw new ArgumentNullException("sigBytes");
+ throw new ArgumentNullException(nameof(sigBytes));
Contract.EndContractBlock();
byte[] localSigBytes = new byte[sigBytes.Length];
@@ -2208,18 +1821,13 @@ 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)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
- throw new ArgumentNullException("binaryAttribute");
+ throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
TypeBuilder.DefineCustomAttribute(
@@ -2230,12 +1838,11 @@ namespace System.Reflection.Emit
false, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
{
- throw new ArgumentNullException("customBuilder");
+ throw new ArgumentNullException(nameof(customBuilder));
}
Contract.EndContractBlock();
@@ -2276,14 +1883,11 @@ 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
if (url == null)
- throw new ArgumentNullException("url");
+ throw new ArgumentNullException(nameof(url));
Contract.EndContractBlock();
lock(SyncRoot)
@@ -2292,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)
@@ -2306,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)
@@ -2319,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.
@@ -2328,7 +1923,7 @@ namespace System.Reflection.Emit
if (entryPoint == null)
{
- throw new ArgumentNullException("entryPoint");
+ throw new ArgumentNullException(nameof(entryPoint));
}
Contract.EndContractBlock();
@@ -2396,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
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
index 2bec04abe5..96e60d9a4e 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
@@ -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*/);
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs
index cae4f0564e..d7bfacd568 100644
--- a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs
@@ -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;
}
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
index 5ef5f80b15..3636cb7377 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
@@ -21,11 +21,8 @@ using System;
public enum OpCodeType
{
-#if !FEATURE_CORECLR
- /// <internalonly/>
[Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
Annotation = 0,
-#endif
Macro = 1,
Nternal = 2,
Objmodel = 3,
diff --git a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
index fdde19a73e..808844a017 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
@@ -27,11 +27,8 @@ public enum OperandType
InlineI8 = 3,
InlineMethod = 4,
InlineNone = 5,
-#if !FEATURE_CORECLR
- /// <internalonly/>
[Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
InlinePhi = 6,
-#endif
InlineR = 7,
InlineSig = 9,
InlineString = 10,
diff --git a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
index 693e2d3660..7909562baa 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
@@ -25,13 +25,12 @@ 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)
{
if (unmanagedMarshal == null)
{
- throw new ArgumentNullException("unmanagedMarshal");
+ throw new ArgumentNullException(nameof(unmanagedMarshal));
}
Contract.EndContractBlock();
@@ -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,14 +54,13 @@ 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)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
- throw new ArgumentNullException("binaryAttribute");
+ throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
TypeBuilder.DefineCustomAttribute(
@@ -75,12 +72,11 @@ 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)
{
- throw new ArgumentNullException("customBuilder");
+ throw new ArgumentNullException(nameof(customBuilder));
}
Contract.EndContractBlock();
customBuilder.CreateCustomAttribute((ModuleBuilder) (m_methodBuilder .GetModule()), m_pdToken.Token);
@@ -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 {
diff --git a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
index 5ac69f205f..e7442b4e02 100644
--- a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
@@ -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)]
@@ -47,11 +46,11 @@ namespace System.Reflection.Emit {
TypeBuilder containingType) // the containing type
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
if (name[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name));
Contract.EndContractBlock();
m_name = name;
@@ -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,12 +101,11 @@ namespace System.Reflection.Emit {
}
}
- [System.Security.SecurityCritical] // auto-generated
private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics)
{
if (mdBuilder == null)
{
- throw new ArgumentNullException("mdBuilder");
+ throw new ArgumentNullException(nameof(mdBuilder));
}
m_containingType.ThrowIfCreated();
@@ -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,18 +135,13 @@ 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)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
- throw new ArgumentNullException("binaryAttribute");
+ throw new ArgumentNullException(nameof(binaryAttribute));
m_containingType.ThrowIfCreated();
TypeBuilder.DefineCustomAttribute(
@@ -164,12 +153,11 @@ 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)
{
- throw new ArgumentNullException("customBuilder");
+ throw new ArgumentNullException(nameof(customBuilder));
}
m_containingType.ThrowIfCreated();
customBuilder.CreateCustomAttribute(m_moduleBuilder, m_prToken.Token);
@@ -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;
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
index 35e8cc7e31..c40035bc40 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
@@ -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;
@@ -123,7 +118,7 @@ namespace System.Reflection.Emit
}
else
{
- throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), "unmanagedCallConv");
+ throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), nameof(unmanagedCallConv));
}
sigHelp = new SignatureHelper(mod, intCall, returnType, null, null);
@@ -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,14 +186,13 @@ namespace System.Reflection.Emit
return sigHelp;
}
- [System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetTypeSigToken(Module mod, Type type)
{
if (mod == null)
throw new ArgumentNullException("module");
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
return new SignatureHelper(mod, type);
}
@@ -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
@@ -315,18 +303,18 @@ namespace System.Reflection.Emit
Type t = optionalCustomModifiers[i];
if (t == null)
- throw new ArgumentNullException("optionalCustomModifiers");
+ throw new ArgumentNullException(nameof(optionalCustomModifiers));
if (t.HasElementType)
- throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "optionalCustomModifiers");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(optionalCustomModifiers));
if (t.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "optionalCustomModifiers");
+ throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(optionalCustomModifiers));
AddElementType(CorElementType.CModOpt);
int token = m_module.GetTypeToken(t).Token;
- Contract.Assert(!MetadataToken.IsNullToken(token));
+ Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
@@ -338,18 +326,18 @@ namespace System.Reflection.Emit
Type t = requiredCustomModifiers[i];
if (t == null)
- throw new ArgumentNullException("requiredCustomModifiers");
+ throw new ArgumentNullException(nameof(requiredCustomModifiers));
if (t.HasElementType)
- throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "requiredCustomModifiers");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(requiredCustomModifiers));
if (t.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "requiredCustomModifiers");
+ throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(requiredCustomModifiers));
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,11 +807,10 @@ namespace System.Reflection.Emit
AddArgument(clsArgument, null, null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddArgument(Type argument, bool pinned)
{
if (argument == null)
- throw new ArgumentNullException("argument");
+ throw new ArgumentNullException(nameof(argument));
IncrementArgCounts();
AddOneArgTypeHelper(argument, pinned);
@@ -835,10 +819,10 @@ namespace System.Reflection.Emit
public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length))
- throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "requiredCustomModifiers", "arguments"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(requiredCustomModifiers), nameof(arguments)));
if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length))
- throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "optionalCustomModifiers", "arguments"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(optionalCustomModifiers), nameof(arguments)));
if (arguments != null)
{
@@ -851,14 +835,13 @@ namespace System.Reflection.Emit
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
if (m_sigDone)
throw new ArgumentException(Environment.GetResourceString("Argument_SigIsFinalized"));
if (argument == null)
- throw new ArgumentNullException("argument");
+ throw new ArgumentNullException(nameof(argument));
IncrementArgCounts();
@@ -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
-
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs
index 62780f4e3a..6b47770608 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs
@@ -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)
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
index 633a2bffb4..84ece90982 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
@@ -234,7 +234,7 @@ namespace System.Reflection.Emit
internal void SetElementType(Type baseType)
{
if (baseType == null)
- throw new ArgumentNullException("baseType");
+ throw new ArgumentNullException(nameof(baseType));
Contract.EndContractBlock();
m_baseType = baseType;
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
index 6db04717b5..73778d5f27 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
@@ -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)]
@@ -56,10 +55,10 @@ namespace System.Reflection.Emit {
public CustAttr(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
- throw new ArgumentNullException("binaryAttribute");
+ throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
m_con = con;
@@ -69,13 +68,12 @@ namespace System.Reflection.Emit {
public CustAttr(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
- throw new ArgumentNullException("customBuilder");
+ throw new ArgumentNullException(nameof(customBuilder));
Contract.EndContractBlock();
m_customBuilder = customBuilder;
}
- [System.Security.SecurityCritical] // auto-generated
public void Bake(ModuleBuilder module, int token)
{
if (m_customBuilder == null)
@@ -105,13 +103,13 @@ namespace System.Reflection.Emit {
// if we wanted to but that just complicates things so these checks are designed to prevent that scenario.
if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedGenericMethodDefinition"), "method");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedGenericMethodDefinition"), nameof(method));
if (method.DeclaringType == null || !method.DeclaringType.IsGenericTypeDefinition)
- throw new ArgumentException(Environment.GetResourceString("Argument_MethodNeedGenericDeclaringType"), "method");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MethodNeedGenericDeclaringType"), nameof(method));
if (type.GetGenericTypeDefinition() != method.DeclaringType)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidMethodDeclaringType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidMethodDeclaringType"), nameof(type));
Contract.EndContractBlock();
// The following converts from Type or TypeBuilder of G<T> to TypeBuilderInstantiation G<T>. These types
@@ -121,7 +119,7 @@ namespace System.Reflection.Emit {
type = type.MakeGenericType(type.GetGenericArguments());
if (!(type is TypeBuilderInstantiation))
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
return MethodOnTypeBuilderInstantiation.GetMethod(method, type as TypeBuilderInstantiation);
}
@@ -131,18 +129,18 @@ namespace System.Reflection.Emit {
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder"));
if (!constructor.DeclaringType.IsGenericTypeDefinition)
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstructorNeedGenericDeclaringType"), "constructor");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ConstructorNeedGenericDeclaringType"), nameof(constructor));
Contract.EndContractBlock();
if (!(type is TypeBuilderInstantiation))
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
// TypeBuilder G<T> ==> TypeBuilderInstantiation G<T>
if (type is TypeBuilder && type.IsGenericTypeDefinition)
type = type.MakeGenericType(type.GetGenericArguments());
if (type.GetGenericTypeDefinition() != constructor.DeclaringType)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorDeclaringType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorDeclaringType"), nameof(type));
return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, type as TypeBuilderInstantiation);
}
@@ -152,18 +150,18 @@ namespace System.Reflection.Emit {
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder"));
if (!field.DeclaringType.IsGenericTypeDefinition)
- throw new ArgumentException(Environment.GetResourceString("Argument_FieldNeedGenericDeclaringType"), "field");
+ throw new ArgumentException(Environment.GetResourceString("Argument_FieldNeedGenericDeclaringType"), nameof(field));
Contract.EndContractBlock();
if (!(type is TypeBuilderInstantiation))
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
// TypeBuilder G<T> ==> TypeBuilderInstantiation G<T>
if (type is TypeBuilder && type.IsGenericTypeDefinition)
type = type.MakeGenericType(type.GetGenericArguments());
if (type.GetGenericTypeDefinition() != field.DeclaringType)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldDeclaringType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldDeclaringType"), nameof(type));
return FieldOnTypeBuilderInstantiation.GetField(field, type as TypeBuilderInstantiation);
}
@@ -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,22 +559,21 @@ 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)
{
if (fullname == null)
- throw new ArgumentNullException("fullname");
+ throw new ArgumentNullException(nameof(fullname));
if (fullname.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "fullname");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(fullname));
if (fullname[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "fullname");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(fullname));
if (fullname.Length > 1023)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeNameTooLong"), "fullname");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TypeNameTooLong"), nameof(fullname));
Contract.EndContractBlock();
int i;
@@ -621,7 +589,7 @@ namespace System.Reflection.Emit {
// Nested Type should have nested attribute set.
// If we are renumbering TypeAttributes' bit, we need to change the logic here.
if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadNestedTypeFlags"), "attr");
+ throw new ArgumentException(Environment.GetResourceString("Argument_BadNestedTypeFlags"), nameof(attr));
}
int[] interfaceTokens = null;
@@ -632,7 +600,7 @@ namespace System.Reflection.Emit {
if (interfaces[i] == null)
{
// cannot contain null in the interface list
- throw new ArgumentNullException("interfaces");
+ throw new ArgumentNullException(nameof(interfaces));
}
}
interfaceTokens = new int[interfaces.Length + 1];
@@ -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,
@@ -741,22 +688,22 @@ namespace System.Reflection.Emit {
CallingConvention nativeCallConv, CharSet nativeCharSet)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
if (dllName == null)
- throw new ArgumentNullException("dllName");
+ throw new ArgumentNullException(nameof(dllName));
if (dllName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "dllName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(dllName));
if (importName == null)
- throw new ArgumentNullException("importName");
+ throw new ArgumentNullException(nameof(importName));
if (importName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "importName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(importName));
if ((attributes & MethodAttributes.Abstract) != 0)
throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeMethod"));
@@ -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;
@@ -840,10 +786,10 @@ namespace System.Reflection.Emit {
TypeAttributes typeAttributes;
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
if (size <= 0 || size >= 0x003f0000)
throw new ArgumentException(Environment.GetResourceString("Argument_BadSizeForData"));
@@ -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,38 +1306,17 @@ namespace System.Reflection.Emit {
public override bool IsSecurityCritical
{
- get
- {
- if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
- Contract.EndContractBlock();
-
- return m_bakedRuntimeType.IsSecurityCritical;
- }
+ get { return true; }
}
public override bool IsSecuritySafeCritical
{
- get
- {
- if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
- Contract.EndContractBlock();
-
- return m_bakedRuntimeType.IsSecuritySafeCritical;
- }
+ get { return false; }
}
public override bool IsSecurityTransparent
{
- get
- {
- if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
- Contract.EndContractBlock();
-
- return m_bakedRuntimeType.IsSecurityTransparent;
- }
+ get { return false; }
}
[System.Runtime.InteropServices.ComVisible(true)]
@@ -1479,7 +1401,6 @@ namespace System.Reflection.Emit {
#endregion
#region ICustomAttributeProvider Implementation
- [System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(bool inherit)
{
if (!IsCreated())
@@ -1489,38 +1410,36 @@ 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())
throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, attributeRuntimeType, inherit);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (!IsCreated())
throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"caType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(m_bakedRuntimeType, attributeRuntimeType, inherit);
}
@@ -1547,7 +1466,7 @@ namespace System.Reflection.Emit {
public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
{
if (names == null)
- throw new ArgumentNullException("names");
+ throw new ArgumentNullException(nameof(names));
if (names.Length == 0)
throw new ArgumentException();
@@ -1555,7 +1474,7 @@ namespace System.Reflection.Emit {
for (int i = 0; i < names.Length; i ++)
if (names[i] == null)
- throw new ArgumentNullException("names");
+ throw new ArgumentNullException(nameof(names));
if (m_inst != null)
throw new InvalidOperationException();
@@ -1589,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)
@@ -1598,14 +1516,13 @@ namespace System.Reflection.Emit {
}
}
- [System.Security.SecurityCritical] // auto-generated
private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
{
if (methodInfoBody == null)
- throw new ArgumentNullException("methodInfoBody");
+ throw new ArgumentNullException(nameof(methodInfoBody));
if (methodInfoDeclaration == null)
- throw new ArgumentNullException("methodInfoDeclaration");
+ throw new ArgumentNullException(nameof(methodInfoDeclaration));
Contract.EndContractBlock();
ThrowIfCreated();
@@ -1671,10 +1588,10 @@ namespace System.Reflection.Emit {
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
Contract.Ensures(Contract.Result<MethodBuilder>() != null);
Contract.EndContractBlock();
@@ -1686,10 +1603,10 @@ namespace System.Reflection.Emit {
if (parameterTypes != null)
{
if (parameterTypeOptionalCustomModifiers != null && parameterTypeOptionalCustomModifiers.Length != parameterTypes.Length)
- throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "parameterTypeOptionalCustomModifiers", "parameterTypes"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(parameterTypeOptionalCustomModifiers), nameof(parameterTypes)));
if (parameterTypeRequiredCustomModifiers != null && parameterTypeRequiredCustomModifiers.Length != parameterTypes.Length)
- throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "parameterTypeRequiredCustomModifiers", "parameterTypes"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(parameterTypeRequiredCustomModifiers), nameof(parameterTypes)));
}
ThrowIfCreated();
@@ -1725,7 +1642,6 @@ namespace System.Reflection.Emit {
#endregion
#region Define Constructor
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public ConstructorBuilder DefineTypeInitializer()
{
@@ -1735,7 +1651,6 @@ namespace System.Reflection.Emit {
}
}
- [System.Security.SecurityCritical] // auto-generated
private ConstructorBuilder DefineTypeInitializerNoLock()
{
ThrowIfCreated();
@@ -1823,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)
@@ -1839,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)
{
@@ -1874,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)
@@ -1889,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)
@@ -1904,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,
@@ -1924,7 +1822,6 @@ namespace System.Reflection.Emit {
#endregion
#region Define Nested Type
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeBuilder DefineNestedType(String name)
{
lock(SyncRoot)
@@ -1933,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)
{
@@ -1947,7 +1843,6 @@ namespace System.Reflection.Emit {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent)
{
lock(SyncRoot)
@@ -1956,7 +1851,6 @@ namespace System.Reflection.Emit {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeBuilder DefineNestedType(String name, TypeAttributes attr)
{
lock(SyncRoot)
@@ -1965,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)
@@ -1978,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)
@@ -1991,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)
@@ -2004,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);
@@ -2018,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)
{
@@ -2028,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)
{
@@ -2048,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)
@@ -2061,11 +1932,10 @@ namespace System.Reflection.Emit {
}
}
- [System.Security.SecurityCritical] // auto-generated
private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes)
{
if (data == null)
- throw new ArgumentNullException("data");
+ throw new ArgumentNullException(nameof(data));
Contract.EndContractBlock();
// This method will define an initialized Data in .sdata.
@@ -2075,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)
@@ -2088,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.
@@ -2121,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)
@@ -2133,15 +1996,14 @@ 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)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
Contract.EndContractBlock();
CheckContext(returnType);
@@ -2183,7 +2045,6 @@ namespace System.Reflection.Emit {
this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public EventBuilder DefineEvent(String name, EventAttributes attributes, Type eventtype)
{
lock(SyncRoot)
@@ -2192,15 +2053,14 @@ namespace System.Reflection.Emit {
}
}
- [System.Security.SecurityCritical] // auto-generated
private EventBuilder DefineEventNoLock(String name, EventAttributes attributes, Type eventtype)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
if (name[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name));
Contract.EndContractBlock();
int tkType;
@@ -2234,7 +2094,6 @@ namespace System.Reflection.Emit {
#region Create Type
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeInfo CreateTypeInfo()
{
lock (SyncRoot)
@@ -2243,7 +2102,6 @@ namespace System.Reflection.Emit {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Type CreateType()
{
lock (SyncRoot)
@@ -2261,7 +2119,6 @@ namespace System.Reflection.Emit {
m_module.CheckContext(types);
}
- [System.Security.SecurityCritical] // auto-generated
private TypeInfo CreateTypeNoLock()
{
if (IsCreated())
@@ -2486,13 +2343,12 @@ namespace System.Reflection.Emit {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public void AddInterfaceImplementation(Type interfaceType)
{
if (interfaceType == null)
{
- throw new ArgumentNullException("interfaceType");
+ throw new ArgumentNullException(nameof(interfaceType));
}
Contract.EndContractBlock();
@@ -2506,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("pset");
-
-#pragma warning disable 618
- if (!Enum.IsDefined(typeof(SecurityAction), action) ||
- action == SecurityAction.RequestMinimum ||
- action == SecurityAction.RequestOptional ||
- action == SecurityAction.RequestRefuse)
- {
- throw new ArgumentOutOfRangeException("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
@@ -2562,30 +2374,24 @@ 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)
{
if (con == null)
- throw new ArgumentNullException("con");
+ throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
- throw new ArgumentNullException("binaryAttribute");
+ throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
TypeBuilder.DefineCustomAttribute(m_module, m_tdType.Token, ((ModuleBuilder)m_module).GetConstructorToken(con).Token,
binaryAttribute, false, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
- throw new ArgumentNullException("customBuilder");
+ throw new ArgumentNullException(nameof(customBuilder));
Contract.EndContractBlock();
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, m_tdType.Token);
@@ -2594,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
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
index 13b98b6543..3bae585953 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
@@ -28,13 +28,13 @@ namespace System.Reflection.Emit
throw new InvalidOperationException();
if (typeArguments == null)
- throw new ArgumentNullException("typeArguments");
+ throw new ArgumentNullException(nameof(typeArguments));
Contract.EndContractBlock();
foreach (Type t in typeArguments)
{
if (t == null)
- throw new ArgumentNullException("typeArguments");
+ throw new ArgumentNullException(nameof(typeArguments));
}
return new TypeBuilderInstantiation(type, typeArguments);
diff --git a/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs b/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs
index 09eac3a272..28e95e2456 100644
--- a/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs
@@ -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
diff --git a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
index 5b36e0e372..aaaffc0df6 100644
--- a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
@@ -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;
}
}
diff --git a/src/mscorlib/src/System/Reflection/EventInfo.cs b/src/mscorlib/src/System/Reflection/EventInfo.cs
index 3fd1951b6c..0eabb9d03a 100644
--- a/src/mscorlib/src/System/Reflection/EventInfo.cs
+++ b/src/mscorlib/src/System/Reflection/EventInfo.cs
@@ -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;
@@ -305,28 +271,27 @@ namespace System.Reflection
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -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,11 +337,10 @@ namespace System.Reflection
#endregion
#region ISerializable
- [System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
diff --git a/src/mscorlib/src/System/Reflection/FieldInfo.cs b/src/mscorlib/src/System/Reflection/FieldInfo.cs
index c6a44d412b..e61207a686 100644
--- a/src/mscorlib/src/System/Reflection/FieldInfo.cs
+++ b/src/mscorlib/src/System/Reflection/FieldInfo.cs
@@ -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
{
@@ -36,7 +30,7 @@ namespace System.Reflection
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle)
{
if (handle.IsNullHandle())
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), "handle");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), nameof(handle));
FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo());
@@ -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
@@ -325,28 +260,27 @@ namespace System.Reflection
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -362,11 +296,10 @@ namespace System.Reflection
#endregion
#region ISerializable Implementation
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
@@ -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)
diff --git a/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs b/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs
index ce2630a908..49819a942f 100644
--- a/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs
+++ b/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs
@@ -8,28 +8,21 @@
**
**
**
-** Purpose: go from type to type info
+** Purpose: Get the underlying TypeInfo from a Type
**
**
=============================================================================*/
-
namespace System.Reflection
{
- using System.Reflection;
-
public static class IntrospectionExtensions
{
- public static TypeInfo GetTypeInfo(this Type type){
- if(type == null){
- throw new ArgumentNullException("type");
- }
+ public static TypeInfo GetTypeInfo(this Type type)
+ {
+ if (type == null)
+ throw new ArgumentNullException(nameof(type));
+
var rcType=(IReflectableType)type;
- if(rcType==null){
- return null;
- }else{
- return rcType.GetTypeInfo();
- }
- }
+ return rcType.GetTypeInfo();
+ }
}
}
-
diff --git a/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs b/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
index 7c980da379..fa95e37ad5 100644
--- a/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
+++ b/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
@@ -19,11 +19,7 @@ namespace System.Reflection {
using ApplicationException = System.ApplicationException;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
- public class InvalidFilterCriteriaException : Exception {
-#else
public class InvalidFilterCriteriaException : ApplicationException {
-#endif // FEATURE_CORECLR
public InvalidFilterCriteriaException()
: base(Environment.GetResourceString("Arg_InvalidFilterCriteriaException")) {
SetErrorCode(__HResults.COR_E_INVALIDFILTERCRITERIA);
diff --git a/src/mscorlib/src/System/Reflection/LoaderAllocator.cs b/src/mscorlib/src/System/Reflection/LoaderAllocator.cs
index a8b4b0c3a0..7c6c6bd0e8 100644
--- a/src/mscorlib/src/System/Reflection/LoaderAllocator.cs
+++ b/src/mscorlib/src/System/Reflection/LoaderAllocator.cs
@@ -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())
diff --git a/src/mscorlib/src/System/Reflection/MdConstant.cs b/src/mscorlib/src/System/Reflection/MdConstant.cs
index 1941736787..e59244f109 100644
--- a/src/mscorlib/src/System/Reflection/MdConstant.cs
+++ b/src/mscorlib/src/System/Reflection/MdConstant.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Reflection/MdImport.cs b/src/mscorlib/src/System/Reflection/MdImport.cs
index 3bf8eddbcc..bbdf948f99 100644
--- a/src/mscorlib/src/System/Reflection/MdImport.cs
+++ b/src/mscorlib/src/System/Reflection/MdImport.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Reflection/MemberInfo.cs b/src/mscorlib/src/System/Reflection/MemberInfo.cs
index 248c78bf70..96a89ad37b 100644
--- a/src/mscorlib/src/System/Reflection/MemberInfo.cs
+++ b/src/mscorlib/src/System/Reflection/MemberInfo.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs b/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs
index c1b4ee5fe1..20ff37650c 100644
--- a/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs
+++ b/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs
@@ -31,7 +31,7 @@ namespace System.Reflection
Type[] genericArguments)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
String assemblyName = reflectedClass.Module.Assembly.FullName;
@@ -65,7 +65,7 @@ namespace System.Reflection
internal MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
String assemblyName = info.GetString("AssemblyName");
@@ -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)
diff --git a/src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs b/src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs
index dd5d69b1fb..388e4f475f 100644
--- a/src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs
+++ b/src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs
@@ -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,12 +23,11 @@ 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)
{
- throw new ArgumentNullException("assembly");
+ throw new ArgumentNullException(nameof(assembly));
}
blob = null;
diff --git a/src/mscorlib/src/System/Reflection/MethodBase.cs b/src/mscorlib/src/System/Reflection/MethodBase.cs
index 68363bf1e0..644a1ac0b0 100644
--- a/src/mscorlib/src/System/Reflection/MethodBase.cs
+++ b/src/mscorlib/src/System/Reflection/MethodBase.cs
@@ -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)
{
@@ -347,7 +341,7 @@ namespace System.Reflection
if (p == null)
p = GetParametersNoCopy();
if (p[i].DefaultValue == System.DBNull.Value)
- throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),"parameters");
+ throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),nameof(parameters));
arg = p[i].DefaultValue;
}
copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr);
@@ -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
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/MethodBody.cs b/src/mscorlib/src/System/Reflection/MethodBody.cs
index 81d7a9ea0e..4634623e26 100644
--- a/src/mscorlib/src/System/Reflection/MethodBody.cs
+++ b/src/mscorlib/src/System/Reflection/MethodBody.cs
@@ -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
diff --git a/src/mscorlib/src/System/Reflection/MethodInfo.cs b/src/mscorlib/src/System/Reflection/MethodInfo.cs
index eeb5a815a4..39387b1f8f 100644
--- a/src/mscorlib/src/System/Reflection/MethodInfo.cs
+++ b/src/mscorlib/src/System/Reflection/MethodInfo.cs
@@ -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,23 +397,21 @@ 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)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
@@ -493,13 +419,13 @@ namespace System.Reflection
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
@@ -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,20 +482,19 @@ namespace System.Reflection
public override bool IsSecurityCritical
{
- get { return RuntimeMethodHandle.IsSecurityCritical(this); }
+ get { return true; }
}
public override bool IsSecuritySafeCritical
{
- get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
+ get { return false; }
}
public override bool IsSecurityTransparent
{
- get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
+ get { return false; }
}
- #endregion
+#endregion
- #region MethodBase Overrides
- [System.Security.SecuritySafeCritical] // auto-generated
+#region MethodBase Overrides
internal override ParameterInfo[] GetParametersNoCopy()
{
FetchNonReturnParameters();
@@ -579,7 +502,6 @@ namespace System.Reflection
return m_parameters;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Diagnostics.Contracts.Pure]
public override ParameterInfo[] GetParameters()
{
@@ -629,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);
@@ -642,9 +558,9 @@ namespace System.Reflection
mb.m_methodBase = this;
return mb;
}
- #endregion
+#endregion
- #region Invocation Logic(On MemberBase)
+#region Invocation Logic(On MemberBase)
private void CheckConsistency(Object target)
{
// only test instance methods
@@ -660,7 +576,6 @@ namespace System.Reflection
}
}
- [System.Security.SecuritySafeCritical]
private void ThrowNoInvokeException()
{
// method is ReflectionOnly
@@ -698,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
@@ -706,7 +620,7 @@ namespace System.Reflection
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
- #region Security Check
+#region Security Check
INVOCATION_FLAGS invocationFlags = InvocationFlags;
#if FEATURE_APPX
@@ -718,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
+#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)
@@ -744,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)
@@ -793,9 +694,9 @@ namespace System.Reflection
return null;
}
- #endregion
+#endregion
- #region MethodInfo Overrides
+#region MethodInfo Overrides
public override Type ReturnType
{
get { return Signature.ReturnType; }
@@ -808,7 +709,6 @@ namespace System.Reflection
public override ParameterInfo ReturnParameter
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
Contract.Ensures(m_returnParameter != null);
@@ -818,7 +718,6 @@ namespace System.Reflection
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override MethodInfo GetBaseDefinition()
{
if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
@@ -844,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;
@@ -864,7 +762,6 @@ namespace System.Reflection
ref stackMark);
}
- [System.Security.SecuritySafeCritical]
public override Delegate CreateDelegate(Type delegateType, Object target)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -881,20 +778,19 @@ namespace System.Reflection
ref stackMark);
}
- [System.Security.SecurityCritical]
private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark)
{
// Validate the parameters.
if (delegateType == null)
- throw new ArgumentNullException("delegateType");
+ throw new ArgumentNullException(nameof(delegateType));
Contract.EndContractBlock();
RuntimeType rtType = delegateType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "delegateType");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(delegateType));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "delegateType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(delegateType));
Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark);
if (d == null)
@@ -905,14 +801,13 @@ namespace System.Reflection
return d;
}
- #endregion
+#endregion
- #region Generics
- [System.Security.SecuritySafeCritical] // auto-generated
+#region Generics
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
{
if (methodInstantiation == null)
- throw new ArgumentNullException("methodInstantiation");
+ throw new ArgumentNullException(nameof(methodInstantiation));
Contract.EndContractBlock();
RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];
@@ -1017,14 +912,13 @@ namespace System.Reflection
return false;
}
}
- #endregion
+#endregion
- #region ISerializable Implementation
- [System.Security.SecurityCritical] // auto-generated
+#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_reflectedTypeCache.IsGlobal)
@@ -1044,9 +938,9 @@ namespace System.Reflection
{
return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true);
}
- #endregion
+#endregion
- #region Legacy Internal
+#region Legacy Internal
internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark)
{
IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);
@@ -1056,6 +950,6 @@ namespace System.Reflection
return RuntimeType.GetMethodBase(method);
}
- #endregion
+#endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/Missing.cs b/src/mscorlib/src/System/Reflection/Missing.cs
index 8289193191..24bf77bd4e 100644
--- a/src/mscorlib/src/System/Reflection/Missing.cs
+++ b/src/mscorlib/src/System/Reflection/Missing.cs
@@ -24,11 +24,10 @@ namespace System.Reflection
#endregion
#region ISerializable
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
UnitySerializationHolder.GetUnitySerializationInfo(info, this);
diff --git a/src/mscorlib/src/System/Reflection/Module.cs b/src/mscorlib/src/System/Reflection/Module.cs
index 34705a4211..b6be38e434 100644
--- a/src/mscorlib/src/System/Reflection/Module.cs
+++ b/src/mscorlib/src/System/Reflection/Module.cs
@@ -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();
@@ -432,16 +425,16 @@ namespace System.Reflection
String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
}
return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
@@ -450,16 +443,16 @@ namespace System.Reflection
public MethodInfo GetMethod(String name, Type[] types)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
}
return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, types, null);
@@ -468,7 +461,7 @@ namespace System.Reflection
public MethodInfo GetMethod(String name)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any,
@@ -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,18 +596,17 @@ namespace System.Reflection
return typeHandleArgs;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override byte[] ResolveSignature(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this),
- "metadataToken");
+ nameof(metadataToken));
ConstArray signature;
if (tk.IsMemberRef)
@@ -673,13 +622,12 @@ 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);
if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
@@ -690,16 +638,16 @@ namespace System.Reflection
if (!tk.IsMethodDef && !tk.IsMethodSpec)
{
if (!tk.IsMemberRef)
- throw new ArgumentException("metadataToken",
- Environment.GetResourceString("Argument_ResolveMethod", tk, this));
+ throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this),
+ nameof(metadataToken));
unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
- throw new ArgumentException("metadataToken",
- Environment.GetResourceString("Argument_ResolveMethod", tk, this));
+ throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this),
+ nameof(metadataToken));
}
}
@@ -724,13 +672,12 @@ namespace System.Reflection
}
}
- [System.Security.SecurityCritical] // auto-generated
private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef)
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
int tkDeclaringType;
@@ -752,17 +699,16 @@ namespace System.Reflection
}
catch
{
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), "metadataToken");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), nameof(metadataToken));
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
@@ -775,16 +721,16 @@ namespace System.Reflection
if (!tk.IsFieldDef)
{
if (!tk.IsMemberRef)
- throw new ArgumentException("metadataToken",
- Environment.GetResourceString("Argument_ResolveField", tk, this));
+ throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
+ nameof(metadataToken));
unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
- throw new ArgumentException("metadataToken",
- Environment.GetResourceString("Argument_ResolveField", tk, this));
+ throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
+ nameof(metadataToken));
}
fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
@@ -811,20 +757,19 @@ namespace System.Reflection
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (tk.IsGlobalTypeDefToken)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), "metadataToken");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), nameof(metadataToken));
if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken));
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
@@ -834,7 +779,7 @@ namespace System.Reflection
Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType();
if (t == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken));
return t;
}
@@ -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);
@@ -867,7 +811,7 @@ namespace System.Reflection
if (tk.IsMemberRef)
{
if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
@@ -885,11 +829,10 @@ namespace System.Reflection
}
}
- throw new ArgumentException("metadataToken",
- Environment.GetResourceString("Argument_ResolveMember", tk, this));
+ throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMember", tk, this),
+ nameof(metadataToken));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override string ResolveString(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
@@ -898,7 +841,7 @@ namespace System.Reflection
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException("metadataToken",
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
string str = MetadataImport.GetUserString(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
@@ -1001,28 +941,27 @@ namespace System.Reflection
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -1034,24 +973,22 @@ namespace System.Reflection
#endregion
#region Public Virtuals
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
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)
{
// throw on null strings regardless of the value of "throwOnError"
if (className == null)
- throw new ArgumentNullException("className");
+ throw new ArgumentNullException(nameof(className));
RuntimeType retType = null;
Object keepAlive = null;
@@ -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();
@@ -1082,7 +1013,7 @@ namespace System.Reflection
if (fullyQualifiedName != null) {
bool checkPermission = true;
try {
- Path.GetFullPathInternal(fullyQualifiedName);
+ Path.GetFullPath(fullyQualifiedName);
}
catch(ArgumentException) {
checkPermission = false;
@@ -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());
@@ -1145,7 +1073,7 @@ namespace System.Reflection
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (RuntimeType == null)
return null;
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Reflection/ParameterInfo.cs b/src/mscorlib/src/System/Reflection/ParameterInfo.cs
index 63c6330b0a..6592e5aa20 100644
--- a/src/mscorlib/src/System/Reflection/ParameterInfo.cs
+++ b/src/mscorlib/src/System/Reflection/ParameterInfo.cs
@@ -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;
@@ -157,7 +155,7 @@ namespace System.Reflection
public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
return EmptyArray<Object>.Value;
@@ -166,7 +164,7 @@ namespace System.Reflection
public virtual bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
return false;
@@ -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,18 +364,17 @@ 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)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// We could be serializing for consumption by a pre-Whidbey
@@ -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;
@@ -728,7 +697,7 @@ namespace System.Reflection
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
if (MdToken.IsNullToken(m_tkParamDef))
@@ -737,16 +706,15 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
if (MdToken.IsNullToken(m_tkParamDef))
@@ -755,7 +723,7 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Reflection/Pointer.cs b/src/mscorlib/src/System/Reflection/Pointer.cs
index 8105208288..95025b20ed 100644
--- a/src/mscorlib/src/System/Reflection/Pointer.cs
+++ b/src/mscorlib/src/System/Reflection/Pointer.cs
@@ -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,17 +36,16 @@ 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("type");
+ throw new ArgumentNullException(nameof(type));
if (!type.IsPointer)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),"ptr");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(ptr));
Contract.EndContractBlock();
RuntimeType rt = type as RuntimeType;
if (rt == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"), "ptr");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"), nameof(ptr));
Pointer x = new Pointer();
x._ptr = ptr;
@@ -57,10 +54,9 @@ 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"),"ptr");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(ptr));
return ((Pointer)ptr)._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);
diff --git a/src/mscorlib/src/System/Reflection/PropertyInfo.cs b/src/mscorlib/src/System/Reflection/PropertyInfo.cs
index 3e451b15b6..e31b378924 100644
--- a/src/mscorlib/src/System/Reflection/PropertyInfo.cs
+++ b/src/mscorlib/src/System/Reflection/PropertyInfo.cs
@@ -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)
@@ -332,28 +297,27 @@ namespace System.Reflection
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -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,11 +592,10 @@ namespace System.Reflection
#endregion
#region ISerializable Implementation
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
diff --git a/src/mscorlib/src/System/Reflection/ReflectionContext.cs b/src/mscorlib/src/System/Reflection/ReflectionContext.cs
index f9bfa87d76..34f692166c 100644
--- a/src/mscorlib/src/System/Reflection/ReflectionContext.cs
+++ b/src/mscorlib/src/System/Reflection/ReflectionContext.cs
@@ -28,7 +28,7 @@ namespace System.Reflection
public virtual TypeInfo GetTypeForObject(object value)
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
return MapType(value.GetType().GetTypeInfo());
}
diff --git a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs b/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
index 9b55c260cf..70681138c5 100644
--- a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
+++ b/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
@@ -65,10 +65,9 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
base.GetObjectData(info, context);
diff --git a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs b/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
index b4ef9b9902..00ab975842 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
@@ -72,7 +72,7 @@ namespace System.Reflection
public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo, Type interfaceType)
{
- if (typeInfo == null) throw new ArgumentNullException("typeInfo");
+ if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo));
if (!(typeInfo is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
return typeInfo.GetInterfaceMap(interfaceType);
@@ -80,7 +80,7 @@ namespace System.Reflection
public static MethodInfo GetMethodInfo(this Delegate del)
{
- if (del == null) throw new ArgumentNullException("del");
+ if (del == null) throw new ArgumentNullException(nameof(del));
return del.Method;
}
diff --git a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs b/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
index e8a441ca8f..8107cf4159 100644
--- a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
+++ b/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
@@ -26,20 +26,7 @@ namespace System.Reflection
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics.Contracts;
-#if !FEATURE_CORECLR
- using Microsoft.Runtime.Hosting;
-#endif
-#if FEATURE_CORECLR
- // Dummy type to avoid ifdefs in signature definitions
- public class StrongNameKeyPair
- {
- private StrongNameKeyPair()
- {
- throw new NotSupportedException();
- }
- }
-#else
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StrongNameKeyPair : IDeserializationCallback, ISerializable
@@ -50,14 +37,10 @@ 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)
- throw new ArgumentNullException("keyPairFile");
+ throw new ArgumentNullException(nameof(keyPairFile));
Contract.EndContractBlock();
int length = (int)keyPairFile.Length;
@@ -68,14 +51,10 @@ 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)
- throw new ArgumentNullException("keyPairArray");
+ throw new ArgumentNullException(nameof(keyPairArray));
Contract.EndContractBlock();
_keyPairArray = new byte[keyPairArray.Length];
@@ -83,27 +62,7 @@ namespace System.Reflection
_keyPairExported = true;
}
-
- // 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("keyPairContainer");
- Contract.EndContractBlock();
-
- _keyPairContainer = keyPairContainer;
-
- _keyPairExported = false;
- }
-
- [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[]));
@@ -111,68 +70,20 @@ namespace System.Reflection
_publicKey = (byte[]) info.GetValue("_publicKey", typeof(byte[]));
}
- // Get the public portion of the key pair.
- public byte[] PublicKey
+ public StrongNameKeyPair(String keyPairContainer)
{
- [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;
- }
+ throw new PlatformNotSupportedException();
}
-
- [System.Security.SecurityCritical] // auto-generated
- private unsafe byte[] ComputePublicKey()
+
+ public byte[] PublicKey
{
- byte[] publicKey = null;
-
- // Make sure pbPublicKey is not leaked with async exceptions
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- }
- finally
+ get
{
- 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);
- }
+ throw new PlatformNotSupportedException();
}
- return publicKey;
}
/// <internalonly/>
- [System.Security.SecurityCritical]
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {
info.AddValue("_keyPairExported", _keyPairExported);
info.AddValue("_keyPairArray", _keyPairArray);
@@ -182,13 +93,5 @@ namespace System.Reflection
/// <internalonly/>
void IDeserializationCallback.OnDeserialization (Object sender) {}
-
- // 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;
- }
}
-#endif // FEATURE_CORECLR
}
diff --git a/src/mscorlib/src/System/Reflection/TargetException.cs b/src/mscorlib/src/System/Reflection/TargetException.cs
index 02772f763f..9c56c121cc 100644
--- a/src/mscorlib/src/System/Reflection/TargetException.cs
+++ b/src/mscorlib/src/System/Reflection/TargetException.cs
@@ -19,11 +19,7 @@ namespace System.Reflection {
using System.Runtime.Serialization;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
- public class TargetException : Exception {
-#else
public class TargetException : ApplicationException {
-#endif //FEATURE_CORECLR
public TargetException() : base() {
SetErrorCode(__HResults.COR_E_TARGET);
}
diff --git a/src/mscorlib/src/System/Reflection/TargetInvocationException.cs b/src/mscorlib/src/System/Reflection/TargetInvocationException.cs
index 70de4227dd..4a32ed245d 100644
--- a/src/mscorlib/src/System/Reflection/TargetInvocationException.cs
+++ b/src/mscorlib/src/System/Reflection/TargetInvocationException.cs
@@ -19,11 +19,7 @@ namespace System.Reflection {
using System.Runtime.Serialization;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
- public sealed class TargetInvocationException : Exception {
-#else
public sealed class TargetInvocationException : ApplicationException {
-#endif //FEATURE_CORECLR
// This exception is not creatable without specifying the
// inner exception.
private TargetInvocationException()
diff --git a/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs b/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
index 4f95b09c40..846732b449 100644
--- a/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
+++ b/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
@@ -19,11 +19,7 @@ namespace System.Reflection {
using System.Runtime.Serialization;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
- public sealed class TargetParameterCountException : Exception {
-#else
public sealed class TargetParameterCountException : ApplicationException {
-#endif //FEATURE_CORECLR
public TargetParameterCountException()
: base(Environment.GetResourceString("Arg_TargetParameterCountException")) {
SetErrorCode(__HResults.COR_E_TARGETPARAMCOUNT);
diff --git a/src/mscorlib/src/System/Reflection/TypeDelegator.cs b/src/mscorlib/src/System/Reflection/TypeDelegator.cs
index cad4a4295a..d715df8950 100644
--- a/src/mscorlib/src/System/Reflection/TypeDelegator.cs
+++ b/src/mscorlib/src/System/Reflection/TypeDelegator.cs
@@ -24,14 +24,11 @@ namespace System.Reflection {
protected Type typeImpl;
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- #endif
protected TypeDelegator() {}
public TypeDelegator(Type delegatingType) {
if (delegatingType == null)
- throw new ArgumentNullException("delegatingType");
+ throw new ArgumentNullException(nameof(delegatingType));
Contract.EndContractBlock();
typeImpl = delegatingType;
diff --git a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
index efd949f565..76bf0008f9 100644
--- a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
+++ b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
@@ -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)
{
diff --git a/src/mscorlib/src/System/Resources/IResourceGroveler.cs b/src/mscorlib/src/System/Resources/IResourceGroveler.cs
index 983fd1204c..77c5c95890 100644
--- a/src/mscorlib/src/System/Resources/IResourceGroveler.cs
+++ b/src/mscorlib/src/System/Resources/IResourceGroveler.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs b/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs
index 8235d608be..15a076bc5c 100644
--- a/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs
+++ b/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs
@@ -36,13 +36,13 @@ namespace System.Resources {
public LooselyLinkedResourceReference(String looselyLinkedResourceName, String typeName)
{
if (looselyLinkedResourceName == null)
- throw new ArgumentNullException("looselyLinkedResourceName");
+ throw new ArgumentNullException(nameof(looselyLinkedResourceName));
if (typeName == null)
- throw new ArgumentNullException("typeName");
+ throw new ArgumentNullException(nameof(typeName));
if (looselyLinkedResourceName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "looselyLinkedResourceName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(looselyLinkedResourceName));
if (typeName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "typeName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(typeName));
Contract.EndContractBlock();
_manifestResourceName = looselyLinkedResourceName;
@@ -60,7 +60,7 @@ namespace System.Resources {
public Object Resolve(Assembly assembly)
{
if (assembly == null)
- throw new ArgumentNullException("assembly");
+ throw new ArgumentNullException(nameof(assembly));
Contract.EndContractBlock();
Stream data = assembly.GetManifestResourceStream(_manifestResourceName);
diff --git a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
index 5fd0daad09..78e961a7f9 100644
--- a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
+++ b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs b/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
index 560cd5faa9..6517a56b6a 100644
--- a/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
+++ b/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
@@ -35,7 +35,7 @@ namespace System.Resources {
public NeutralResourcesLanguageAttribute(String cultureName)
{
if (cultureName == null)
- throw new ArgumentNullException("cultureName");
+ throw new ArgumentNullException(nameof(cultureName));
Contract.EndContractBlock();
_culture = cultureName;
@@ -45,7 +45,7 @@ namespace System.Resources {
public NeutralResourcesLanguageAttribute(String cultureName, UltimateResourceFallbackLocation location)
{
if (cultureName == null)
- throw new ArgumentNullException("cultureName");
+ throw new ArgumentNullException(nameof(cultureName));
if (!Enum.IsDefined(typeof(UltimateResourceFallbackLocation), location))
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", location));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs b/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs
index def7836e05..de50cccc33 100644
--- a/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs
+++ b/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Resources/ResourceManager.cs b/src/mscorlib/src/System/Resources/ResourceManager.cs
index b088e7f492..15f6af7bcf 100644
--- a/src/mscorlib/src/System/Resources/ResourceManager.cs
+++ b/src/mscorlib/src/System/Resources/ResourceManager.cs
@@ -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();
@@ -292,18 +278,11 @@ namespace System.Resources {
//
private ResourceManager(String baseName, String resourceDir, Type usingResourceSet) {
if (null==baseName)
- throw new ArgumentNullException("baseName");
+ throw new ArgumentNullException(nameof(baseName));
if (null==resourceDir)
- throw new ArgumentNullException("resourceDir");
+ 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,30 +296,16 @@ 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)
{
if (null==baseName)
- throw new ArgumentNullException("baseName");
+ throw new ArgumentNullException(nameof(baseName));
if (null==assembly)
- throw new ArgumentNullException("assembly");
+ throw new ArgumentNullException(nameof(assembly));
Contract.EndContractBlock();
if (!(assembly is RuntimeAssembly))
@@ -368,18 +333,11 @@ namespace System.Resources {
public ResourceManager(String baseName, Assembly assembly, Type usingResourceSet)
{
if (null==baseName)
- throw new ArgumentNullException("baseName");
+ throw new ArgumentNullException(nameof(baseName));
if (null==assembly)
- throw new ArgumentNullException("assembly");
+ 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"));
@@ -387,7 +345,7 @@ namespace System.Resources {
BaseNameField = baseName;
if (usingResourceSet != null && (usingResourceSet != _minResourceSet) && !(usingResourceSet.IsSubclassOf(_minResourceSet)))
- throw new ArgumentException(Environment.GetResourceString("Arg_ResMgrNotResSet"), "usingResourceSet");
+ throw new ArgumentException(Environment.GetResourceString("Arg_ResMgrNotResSet"), nameof(usingResourceSet));
_userResourceSet = usingResourceSet;
CommonAssemblyInit();
@@ -404,7 +362,7 @@ namespace System.Resources {
public ResourceManager(Type resourceSource)
{
if (null==resourceSource)
- throw new ArgumentNullException("resourceSource");
+ throw new ArgumentNullException(nameof(resourceSource));
Contract.EndContractBlock();
if (!(resourceSource is RuntimeType))
@@ -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,11 +585,10 @@ 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)
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
Contract.EndContractBlock();
Dictionary<String,ResourceSet> localResourceSets = _resourceSets;
@@ -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;
@@ -846,7 +734,7 @@ namespace System.Resources {
{
// Ensure that the assembly reference is not null
if (a == null) {
- throw new ArgumentNullException("a", Environment.GetResourceString("ArgumentNull_Assembly"));
+ throw new ArgumentNullException(nameof(a), Environment.GetResourceString("ArgumentNull_Assembly"));
}
Contract.EndContractBlock();
@@ -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;
@@ -1225,7 +1104,7 @@ namespace System.Resources {
//
public virtual String GetString(String name, CultureInfo culture) {
if (null==name)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
#if FEATURE_APPX
@@ -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;
@@ -1342,7 +1208,7 @@ namespace System.Resources {
private Object GetObject(String name, CultureInfo culture, bool wrapUnmanagedMemStream)
{
if (null==name)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
#if FEATURE_APPX
@@ -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)
{
@@ -1422,12 +1282,6 @@ namespace System.Resources {
}
}
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerLookupFailed(BaseNameField, MainAssembly, culture.Name);
- }
-#endif
return null;
}
@@ -1448,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) {
@@ -1471,110 +1324,14 @@ namespace System.Resources {
// The config file told us what satellites might be installed.
int pos = Array.IndexOf(installedSatellites, lookForCulture.Name);
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled()) {
- if (pos < 0) {
- FrameworkEventSource.Log.ResourceManagerCultureNotFoundInConfigFile(BaseNameField, MainAssembly, lookForCulture.Name);
- }
- else {
- FrameworkEventSource.Log.ResourceManagerCultureFoundInConfigFile(BaseNameField, MainAssembly, lookForCulture.Name);
- }
- }
-#endif
return pos >= 0;
}
// Note: There is one config file per appdomain. This is not
// per-process nor per-assembly.
- [System.Security.SecurityCritical] // auto-generated
private Hashtable GetSatelliteAssembliesFromConfig()
{
-#if FEATURE_FUSION
-
- String fileName = AppDomain.CurrentDomain.FusionStore.ConfigurationFileInternal;
- if (fileName == null) {
- return null;
- }
-
- // Don't do a security assert. We need to support semi-trusted
- // scenarios, but asserting here causes infinite resource lookups
- // while initializing security & looking up mscorlib's config file.
- // Use internal methods to bypass security checks.
-
- // If we're dealing with a local file name or a UNC path instead
- // of a URL, check to see if the file exists here for perf (avoids
- // throwing a FileNotFoundException).
- if (fileName.Length >= 2 &&
- ((fileName[1] == Path.VolumeSeparatorChar) || (fileName[0] == Path.DirectorySeparatorChar && fileName[1] == Path.DirectorySeparatorChar)) &&
- !File.InternalExists(fileName))
- return null;
-
- ConfigTreeParser parser = new ConfigTreeParser();
- String queryPath = "/configuration/satelliteassemblies";
- ConfigNode node = null;
- // Catch exceptions in case a web app doesn't have a config file.
- try {
- node = parser.Parse(fileName, queryPath, true);
- }
- catch(Exception) {}
-
- if (node == null) {
- return null;
- }
-
- // The application config file will contain sections like this:
- // <?xml version="1.0"?>
- // <configuration>
- // <satelliteassemblies>
- // <assembly name="mscorlib, Version=..., PublicKeyToken=...">
- // <culture>fr</culture>
- // </assembly>
- // <assembly name="UserAssembly, ...">
- // <culture>fr-FR</culture>
- // <culture>de-CH</culture>
- // </assembly>
- // <assembly name="UserAssembly2, ...">
- // </assembly>
- // </satelliteassemblies>
- // </configuration>
- Hashtable satelliteInfo = new Hashtable(StringComparer.OrdinalIgnoreCase);
- foreach(ConfigNode assemblyNode in node.Children) {
- if (!String.Equals(assemblyNode.Name, "assembly"))
- throw new ApplicationException(Environment.GetResourceString("XMLSyntax_InvalidSyntaxSatAssemTag", Path.GetFileName(fileName), assemblyNode.Name));
-
- if (assemblyNode.Attributes.Count == 0)
- throw new ApplicationException(Environment.GetResourceString("XMLSyntax_InvalidSyntaxSatAssemTagNoAttr", Path.GetFileName(fileName)));
-
- DictionaryEntry de = (DictionaryEntry) assemblyNode.Attributes[0];
- String assemblyName = (String) de.Value;
- if (!String.Equals(de.Key, "name") || String.IsNullOrEmpty(assemblyName) || assemblyNode.Attributes.Count > 1)
- throw new ApplicationException(Environment.GetResourceString("XMLSyntax_InvalidSyntaxSatAssemTagBadAttr", Path.GetFileName(fileName), de.Key, de.Value));
-
- ArrayList list = new ArrayList(5);
- foreach(ConfigNode child in assemblyNode.Children)
- if (child.Value != null)
- list.Add(child.Value);
-
- String[] satellites = new String[list.Count];
- for(int i=0; i<satellites.Length; i++) {
- String cultureName = (String)list[i];
- satellites[i] = cultureName;
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerAddingCultureFromConfigFile(BaseNameField, MainAssembly, cultureName);
- }
-#endif
- }
-
- satelliteInfo.Add(assemblyName, satellites);
- }
-
- return satelliteInfo;
-#else
return null;
-#endif //FEATURE_FUSION
-
}
#endif // RESOURCE_SATELLITE_CONFIG
@@ -1586,7 +1343,7 @@ namespace System.Resources {
{
if (rm == null)
{
- throw new ArgumentNullException("rm");
+ throw new ArgumentNullException(nameof(rm));
}
_rm = rm;
}
@@ -1667,7 +1424,6 @@ namespace System.Resources {
#if RESOURCE_SATELLITE_CONFIG
- [System.Security.SecurityCritical] // auto-generated
internal bool TryLookingForSatellite(CultureInfo lookForCulture)
{
return _rm.TryLookingForSatellite(lookForCulture);
diff --git a/src/mscorlib/src/System/Resources/ResourceReader.cs b/src/mscorlib/src/System/Resources/ResourceReader.cs
index a269d5c5fe..89cfdb1b9f 100644
--- a/src/mscorlib/src/System/Resources/ResourceReader.cs
+++ b/src/mscorlib/src/System/Resources/ResourceReader.cs
@@ -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,11 +166,10 @@ namespace System.Resources {
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public ResourceReader(Stream stream)
{
if (stream==null)
- throw new ArgumentNullException("stream");
+ throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
Contract.EndContractBlock();
@@ -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];
@@ -1165,7 +1145,7 @@ namespace System.Resources {
public void GetResourceData(String resourceName, out String resourceType, out byte[] resourceData)
{
if (resourceName == null)
- throw new ArgumentNullException("resourceName");
+ throw new ArgumentNullException(nameof(resourceName));
Contract.EndContractBlock();
if (_resCache == null)
throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed"));
@@ -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));
diff --git a/src/mscorlib/src/System/Resources/ResourceSet.cs b/src/mscorlib/src/System/Resources/ResourceSet.cs
index ed40a1237f..1b272fc6ff 100644
--- a/src/mscorlib/src/System/Resources/ResourceSet.cs
+++ b/src/mscorlib/src/System/Resources/ResourceSet.cs
@@ -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);
@@ -111,7 +102,7 @@ namespace System.Resources {
public ResourceSet(IResourceReader reader)
{
if (reader == null)
- throw new ArgumentNullException("reader");
+ throw new ArgumentNullException(nameof(reader));
Contract.EndContractBlock();
Reader = reader;
CommonInit();
@@ -122,7 +113,7 @@ namespace System.Resources {
public ResourceSet(IResourceReader reader, Assembly assembly)
{
if (reader == null)
- throw new ArgumentNullException("reader");
+ throw new ArgumentNullException(nameof(reader));
Contract.EndContractBlock();
Reader = reader;
CommonInit();
@@ -182,15 +173,13 @@ namespace System.Resources {
return typeof(ResourceReader);
}
-#if !FEATURE_CORECLR
// Returns the preferred IResourceWriter class for this kind of ResourceSet.
// Subclasses of ResourceSet using their own Readers &; should override
// GetDefaultReader and GetDefaultWriter.
public virtual Type GetDefaultWriter()
{
- return typeof(ResourceWriter);
+ return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, throwOnError: true);
}
-#endif // !FEATURE_CORECLR
[ComVisible(false)]
public virtual IDictionaryEnumerator GetEnumerator()
@@ -291,7 +280,7 @@ namespace System.Resources {
private Object GetObjectInternal(String name)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
Hashtable copyOfTable = Table; // Avoid a race with Dispose
diff --git a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs b/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
index 6b512bcf6a..a94ac82781 100644
--- a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
+++ b/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
@@ -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)");
@@ -285,7 +284,7 @@ namespace System.Resources {
private Object GetObject(String key, bool ignoreCase, bool isString)
{
if (key==null)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
if (Reader == null || _resCache == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
Contract.EndContractBlock();
@@ -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.
diff --git a/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs b/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
index f72e810227..327279062a 100644
--- a/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
+++ b/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
@@ -27,7 +27,7 @@ namespace System.Resources {
public SatelliteContractVersionAttribute(String version)
{
if (version == null)
- throw new ArgumentNullException("version");
+ throw new ArgumentNullException(nameof(version));
Contract.EndContractBlock();
_version = version;
}
diff --git a/src/mscorlib/src/System/Resources/__FastResourceComparer.cs b/src/mscorlib/src/System/Resources/__FastResourceComparer.cs
index 5bc7333863..e0911fae1d 100644
--- a/src/mscorlib/src/System/Resources/__FastResourceComparer.cs
+++ b/src/mscorlib/src/System/Resources/__FastResourceComparer.cs
@@ -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;
diff --git a/src/mscorlib/src/System/RtType.cs b/src/mscorlib/src/System/RtType.cs
index 037576fc33..168beefd4e 100644
--- a/src/mscorlib/src/System/RtType.cs
+++ b/src/mscorlib/src/System/RtType.cs
@@ -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
@@ -1869,7 +1788,7 @@ namespace System
ref StackCrawlMark stackMark)
{
if (typeName == null)
- throw new ArgumentNullException("typeName");
+ throw new ArgumentNullException(nameof(typeName));
Contract.EndContractBlock();
return RuntimeTypeHandle.GetTypeByName(
@@ -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,31 +2814,30 @@ 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)
throw new InvalidOperationException(Environment.GetResourceString("Arg_GenericParameter"));
if ((object)ifaceType == null)
- throw new ArgumentNullException("ifaceType");
+ throw new ArgumentNullException(nameof(ifaceType));
Contract.EndContractBlock();
RuntimeType ifaceRtType = ifaceType as RuntimeType;
if (ifaceRtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "ifaceType");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(ifaceType));
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);
@@ -3446,7 +3347,7 @@ namespace System
public override bool IsSubclassOf(Type type)
{
if ((object)type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
@@ -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,22 +3535,13 @@ 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()
{
- return RuntimeTypeHandle.IsContextful(this);
- }
-
- /*
- protected override bool IsMarshalByRefImpl()
- {
- return GetTypeHandleInternal().IsMarshalByRef();
+ return false;
}
- */
protected override bool IsByRefImpl()
{
@@ -3685,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);
@@ -3736,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);
@@ -3753,7 +3610,6 @@ namespace System
public override GenericParameterAttributes GenericParameterAttributes
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (!IsGenericParameter)
@@ -3796,7 +3652,6 @@ namespace System
return RuntimeTypeHandle.IsArray(this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override int GetArrayRank()
{
if (!IsArrayImpl())
@@ -3828,7 +3683,6 @@ namespace System
return retVal;
}
- [SecuritySafeCritical]
public override Array GetEnumValues()
{
if (!IsEnum)
@@ -3862,7 +3716,7 @@ namespace System
public override bool IsEnumDefined(object value)
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Check if both of them are of the same type
@@ -3909,13 +3763,13 @@ namespace System
public override string GetEnumName(object value)
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
Type valueType = value.GetType();
if (!(valueType.IsEnum || IsIntegerType(valueType)))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), nameof(value));
ulong ulValue = Enum.ToUInt64(value);
@@ -3939,11 +3793,10 @@ namespace System
return types;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type MakeGenericType(Type[] instantiation)
{
if (instantiation == null)
- throw new ArgumentNullException("instantiation");
+ throw new ArgumentNullException(nameof(instantiation));
Contract.EndContractBlock();
RuntimeType[] instantiationRuntimeType = new RuntimeType[instantiation.Length];
@@ -3953,7 +3806,7 @@ namespace System
Environment.GetResourceString("Arg_NotGenericTypeDefinition", this));
if (GetGenericArguments().Length != instantiation.Length)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericArgsCount"), "instantiation");
+ throw new ArgumentException(Environment.GetResourceString("Argument_GenericArgsCount"), nameof(instantiation));
for (int i = 0; i < instantiation.Length; i ++)
{
@@ -4055,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(); }
@@ -4069,7 +3921,6 @@ namespace System
}
public override StructLayoutAttribute StructLayoutAttribute
{
- [System.Security.SecuritySafeCritical] // overrides transparent public member
get
{
return (StructLayoutAttribute)StructLayoutAttribute.GetCustomAttribute(this);
@@ -4091,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.
@@ -4107,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))
{
@@ -4186,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)
@@ -4245,7 +4075,6 @@ namespace System
}
#if FEATURE_COMINTEROP
- [System.Security.SecuritySafeCritical] // auto-generated
#endif
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
@@ -4260,7 +4089,7 @@ namespace System
#region Preconditions
if ((bindingFlags & InvocationMask) == 0)
// "Must specify binding flags describing the invoke operation required."
- throw new ArgumentException(Environment.GetResourceString("Arg_NoAccessSpec"),"bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_NoAccessSpec"),nameof(bindingFlags));
// Provide a default binding mask if none is provided
if ((bindingFlags & MemberBindingMask) == 0)
@@ -4278,13 +4107,13 @@ namespace System
{
if (namedParams.Length > providedArgs.Length)
// "Named parameter array can not be bigger than argument array."
- throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamTooBig"), "namedParams");
+ throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamTooBig"), nameof(namedParams));
}
else
{
if (namedParams.Length != 0)
// "Named parameter array can not be bigger than argument array."
- throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamTooBig"), "namedParams");
+ throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamTooBig"), nameof(namedParams));
}
}
#endregion
@@ -4295,31 +4124,28 @@ namespace System
{
#region Preconditions
if ((bindingFlags & ClassicBindingMask) == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_COMAccess"), "bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_COMAccess"), nameof(bindingFlags));
if ((bindingFlags & BindingFlags.GetProperty) != 0 && (bindingFlags & ClassicBindingMask & ~(BindingFlags.GetProperty | BindingFlags.InvokeMethod)) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), "bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), nameof(bindingFlags));
if ((bindingFlags & BindingFlags.InvokeMethod) != 0 && (bindingFlags & ClassicBindingMask & ~(BindingFlags.GetProperty | BindingFlags.InvokeMethod)) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), "bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), nameof(bindingFlags));
if ((bindingFlags & BindingFlags.SetProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.SetProperty) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), "bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), nameof(bindingFlags));
if ((bindingFlags & BindingFlags.PutDispProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.PutDispProperty) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), "bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), nameof(bindingFlags));
if ((bindingFlags & BindingFlags.PutRefDispProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.PutRefDispProperty) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), "bindingFlags");
+ 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)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
bool[] isByRef = modifiers == null ? null : modifiers[0].IsByRefArray;
@@ -4329,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
@@ -4344,7 +4162,7 @@ namespace System
#region Check that any named paramters are not null
if (namedParams != null && Array.IndexOf(namedParams, null) != -1)
// "Named parameter value must not be null."
- throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamNull"),"namedParams");
+ throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamNull"),nameof(namedParams));
#endregion
int argCnt = (providedArgs != null) ? providedArgs.Length : 0;
@@ -4361,7 +4179,7 @@ namespace System
{
if ((bindingFlags & BindingFlags.CreateInstance) != 0 && (bindingFlags & BinderNonCreateInstance) != 0)
// "Can not specify both CreateInstance and another access type."
- throw new ArgumentException(Environment.GetResourceString("Arg_CreatInstAccess"),"bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_CreatInstAccess"),nameof(bindingFlags));
return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture);
}
@@ -4373,7 +4191,7 @@ namespace System
#region Name
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (name.Length == 0 || name.Equals(@"[DISPID=0]"))
{
@@ -4398,26 +4216,26 @@ namespace System
{
if (IsSetField)
// "Can not specify both Get and Set on a field."
- throw new ArgumentException(Environment.GetResourceString("Arg_FldSetGet"),"bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_FldSetGet"),nameof(bindingFlags));
if ((bindingFlags & BindingFlags.SetProperty) != 0)
// "Can not specify both GetField and SetProperty."
- throw new ArgumentException(Environment.GetResourceString("Arg_FldGetPropSet"),"bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_FldGetPropSet"),nameof(bindingFlags));
}
else
{
- Contract.Assert(IsSetField);
+ Debug.Assert(IsSetField);
if (providedArgs == null)
- throw new ArgumentNullException("providedArgs");
+ throw new ArgumentNullException(nameof(providedArgs));
if ((bindingFlags & BindingFlags.GetProperty) != 0)
// "Can not specify both SetField and GetProperty."
- throw new ArgumentException(Environment.GetResourceString("Arg_FldSetPropGet"),"bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_FldSetPropGet"),nameof(bindingFlags));
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
// "Can not specify Set on a Field and Invoke on a method."
- throw new ArgumentException(Environment.GetResourceString("Arg_FldSetInvoke"),"bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_FldSetInvoke"),nameof(bindingFlags));
}
#endregion
@@ -4425,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)
{
@@ -4491,7 +4309,7 @@ namespace System
{
#region Get the field value
if (argCnt != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_FldGetArgErr"),"bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_FldGetArgErr"),nameof(bindingFlags));
return selFld.GetValue(target);
#endregion
@@ -4500,7 +4318,7 @@ namespace System
{
#region Set the field Value
if (argCnt != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_FldSetArgErr"),"bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_FldSetArgErr"),nameof(bindingFlags));
selFld.SetValue(target,providedArgs[0],bindingFlags,binder,culture);
@@ -4548,19 +4366,19 @@ namespace System
#region Preconditions
if (isGetProperty)
{
- Contract.Assert(!IsSetField);
+ Debug.Assert(!IsSetField);
if (isSetProperty)
- throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), "bindingFlags");
+ 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"), "bindingFlags");
+ throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), nameof(bindingFlags));
}
#endregion
}
@@ -4579,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;
@@ -4602,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);
}
@@ -4610,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)
@@ -4656,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);
}
@@ -4726,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);
@@ -4752,11 +4558,10 @@ namespace System
#endregion
#region ISerializable
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
UnitySerializationHolder.GetUnitySerializationInfo(info, this);
@@ -4764,38 +4569,35 @@ 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)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if ((object)attributeType == null)
- throw new ArgumentNullException("attributeType");
+ throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
@@ -4887,7 +4689,6 @@ namespace System
public override int MetadataToken
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return RuntimeTypeHandle.GetToken(this);
@@ -4915,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)
{
@@ -4923,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
@@ -5103,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;
@@ -5137,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();
@@ -5184,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);
@@ -5212,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);
@@ -5238,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)
@@ -5265,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
{
@@ -5296,7 +5031,6 @@ namespace System
Cache.InvalidateCachedNestedType();
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsGenericCOMObjectImpl()
{
return RuntimeTypeHandle.IsComObject(this, true);
@@ -5304,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
@@ -5342,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
}
@@ -5580,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;
@@ -5613,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;
@@ -5631,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)
@@ -5652,7 +5166,6 @@ namespace System
return false;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe bool EqualsCaseInsensitive(Utf8String s)
{
if (m_pStringHeap == null)
@@ -5666,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
@@ -5750,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)
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
index 05850605b8..6a16462383 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
@@ -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,14 +58,13 @@ 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
{
// See comment on AsyncMethodBuilderCore.Start
// AsyncMethodBuilderCore.Start(ref stateMachine);
- if (stateMachine == null) throw new ArgumentNullException("stateMachine");
+ if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
Contract.EndContractBlock();
// Run the MoveNext method within a copy-on-write ExecutionContext scope.
@@ -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)
@@ -200,7 +197,7 @@ namespace System.Runtime.CompilerServices
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
public void SetException(Exception exception)
{
- if (exception == null) throw new ArgumentNullException("exception");
+ if (exception == null) throw new ArgumentNullException(nameof(exception));
Contract.EndContractBlock();
if (AsyncCausalityTracer.LoggingOn)
@@ -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,14 +290,13 @@ 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
{
// See comment on AsyncMethodBuilderCore.Start
// AsyncMethodBuilderCore.Start(ref stateMachine);
- if (stateMachine == null) throw new ArgumentNullException("stateMachine");
+ if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
Contract.EndContractBlock();
// Run the MoveNext method within a copy-on-write ExecutionContext scope.
@@ -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,14 +444,13 @@ 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
{
// See comment on AsyncMethodBuilderCore.Start
// AsyncMethodBuilderCore.Start(ref stateMachine);
- if (stateMachine == null) throw new ArgumentNullException("stateMachine");
+ if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
Contract.EndContractBlock();
// Run the MoveNext method within a copy-on-write ExecutionContext scope.
@@ -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
@@ -650,7 +642,7 @@ namespace System.Runtime.CompilerServices
/// <exception cref="System.InvalidOperationException">The task has already completed.</exception>
public void SetException(Exception exception)
{
- if (exception == null) throw new ArgumentNullException("exception");
+ if (exception == null) throw new ArgumentNullException(nameof(exception));
Contract.EndContractBlock();
@@ -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,12 +845,11 @@ 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
{
- if (stateMachine == null) throw new ArgumentNullException("stateMachine");
+ if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
Contract.EndContractBlock();
// Run the MoveNext method within a copy-on-write ExecutionContext scope.
@@ -887,7 +877,7 @@ namespace System.Runtime.CompilerServices
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
- if (stateMachine == null) throw new ArgumentNullException("stateMachine");
+ if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
Contract.EndContractBlock();
if (m_stateMachine != null) throw new InvalidOperationException(Environment.GetResourceString("AsyncMethodBuilder_InstanceNotInitialized"));
m_stateMachine = stateMachine;
@@ -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();
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CallingConvention.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CallingConvention.cs
deleted file mode 100644
index f44251d480..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CallingConvention.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.CompilerServices
-{
- // Types used in Custom Modifier to specify calling conventions.
- [System.Runtime.InteropServices.ComVisible(true)]
- public class CallConvCdecl
- {
- }
-
- [System.Runtime.InteropServices.ComVisible(true)]
- public class CallConvStdcall
- {
- }
-
- [System.Runtime.InteropServices.ComVisible(true)]
- public class CallConvThiscall
- {
- }
-
- [System.Runtime.InteropServices.ComVisible(true)]
- public class CallConvFastcall
- {
- }
-
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
index 21d677241d..74559673bb 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
@@ -60,31 +60,29 @@
** 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,46 +206,39 @@ 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)
{
- throw new ArgumentNullException("createValueCallback");
+ throw new ArgumentNullException(nameof(createValueCallback));
}
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
}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
index 39a4c86b72..7bfaa7aafd 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
@@ -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))
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs
index aee3bc2230..4b99a8a5d9 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs
@@ -26,12 +26,12 @@ namespace System.Runtime.CompilerServices
{
if (format == null)
{
- throw new ArgumentNullException("format");
+ throw new ArgumentNullException(nameof(format));
}
if (arguments == null)
{
- throw new ArgumentNullException("arguments");
+ throw new ArgumentNullException(nameof(arguments));
}
return new ConcreteFormattableString(format, arguments);
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/HasCopySemanticsAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/HasCopySemanticsAttribute.cs
deleted file mode 100644
index 944a2868f2..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/HasCopySemanticsAttribute.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
-[Serializable]
-[AttributeUsage(AttributeTargets.Struct)]
- public sealed class HasCopySemanticsAttribute : Attribute
- {
- public HasCopySemanticsAttribute()
- {}
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs
deleted file mode 100644
index d6dfcbbbb9..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Runtime.InteropServices;
-
-namespace System.Runtime.CompilerServices
-{
-[Serializable]
-[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class IDispatchConstantAttribute : CustomConstantAttribute
- {
- public IDispatchConstantAttribute()
- {
- }
-
- public override Object Value
- {
- get
- {
- return new DispatchWrapper(null);
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs b/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs
index 872a79b72b..aba0a0691f 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs
@@ -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);
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IUnknownConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IUnknownConstantAttribute.cs
deleted file mode 100644
index f8717cff52..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IUnknownConstantAttribute.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Runtime.InteropServices;
-
-namespace System.Runtime.CompilerServices
-{
-[Serializable]
-[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class IUnknownConstantAttribute : CustomConstantAttribute
- {
- public IUnknownConstantAttribute()
- {
- }
-
- public override Object Value
- {
- get
- {
- return new UnknownWrapper(null);
- }
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsBoxed.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsBoxed.cs
deleted file mode 100644
index 8b6691c09d..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsBoxed.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- // Indicates that the modified reference type is a boxed valuetype
- public static class IsBoxed
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsByValue.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsByValue.cs
deleted file mode 100644
index d16a853597..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsByValue.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- // Indicates that the modified method argument is passed by value
- public static class IsByValue
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsConst.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsConst.cs
deleted file mode 100644
index 210e5997a7..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsConst.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- // Indicates that the modified type is const (i.e. has a const modifier)
- public static class IsConst
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsCopyConstructed.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsCopyConstructed.cs
deleted file mode 100644
index ee40ee7b02..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsCopyConstructed.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- [System.Runtime.InteropServices.ComVisible(true)]
- public static class IsCopyConstructed
- {}
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsExplicitlyDereferenced.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsExplicitlyDereferenced.cs
deleted file mode 100644
index 480a62175d..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsExplicitlyDereferenced.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- // Consider the following C++ method prototypes:
- // 1) int foo(int ^arg);
- // 2) int foo(int &arg);
- //
- // Both of these methods will have a .NET type signature that looks the
- // same, but when importing a method from a metadata scope, the compiler
- // needs to know what the calling syntax should be. This modopt and its
- // partner "IsImplicitlyDereferenced" disambiguate reference versus
- // pointer arguments.
- //
- // Indicates that the modified GC reference represents a pointer in a
- // method signature.
- public static class IsExplicitlyDereferenced
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsImplicitlyDereferenced.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsImplicitlyDereferenced.cs
deleted file mode 100644
index ea81cb8ec5..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsImplicitlyDereferenced.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- // Consider the following C++ method prototypes:
- // 1) int foo(int ^arg);
- // 2) int foo(int &arg);
- //
- // Both of these methods will have a .NET type signature that looks the
- // same, but when importing a method from a metadata scope, the compiler
- // needs to know what the calling syntax should be. This modopt and its
- // partner "IsExplicitlyDereferenced" disambiguate reference versus
- // pointer arguments.
- //
- // Indicates that the modified GC reference represents a reference in a
- // method signature.
- public static class IsImplicitlyDereferenced
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsJitIntrinsic.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsJitIntrinsic.cs
deleted file mode 100644
index 013e50f3ea..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsJitIntrinsic.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- // Indicates that the modified method is an intrinsic for which the JIT
- // can perform special code generation.
- public static class IsJitIntrinsic
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsLong.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsLong.cs
deleted file mode 100644
index e8bebfb2d3..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsLong.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- // The C++ standard indicates that a long is always 4-bytes, whereas the
- // size of an integer is system dependent (not exceedign sizeof(long)).
- // The CLR does not offer a mechanism for encoding this distinction,
- // but it is critically important for maintaining language level type
- // safety.
- //
- // Indicates that the modified integer is a standard C++ long.
- // Could also be called IsAlternateIntegerType or something else.
- public static class IsLong
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsSignUnspecifiedByte.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsSignUnspecifiedByte.cs
deleted file mode 100644
index e68f4d7751..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsSignUnspecifiedByte.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- // C++ recognizes three char types: signed char, unsigned char, and char.
- // When a char is neither signed nor unsigned, it is a char.
- // This modopt indicates that the modified instance is a char.
- //
- // Any compiler could use this to indicate that the user has not specified
- // Sign behavior for the given byte.
- public static class IsSignUnspecifiedByte
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsUdtReturn.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsUdtReturn.cs
deleted file mode 100644
index dd85914b53..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsUdtReturn.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
- // Indicates that the return type is a user defined type
- public static class IsUdtReturn
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/NativeCppClassAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/NativeCppClassAttribute.cs
deleted file mode 100644
index 0d6c759d76..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/NativeCppClassAttribute.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace System.Runtime.CompilerServices {
-[Serializable]
-[AttributeUsage(AttributeTargets.Struct, Inherited = true),
- System.Runtime.InteropServices.ComVisible(true)]
- public sealed class NativeCppClassAttribute : Attribute
- {
- public NativeCppClassAttribute () {}
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RequiredAttributeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RequiredAttributeAttribute.cs
deleted file mode 100644
index f363696ebd..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RequiredAttributeAttribute.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace System.Runtime.CompilerServices
-{
-[Serializable]
-[AttributeUsage (AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface,
- AllowMultiple=true, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class RequiredAttributeAttribute : Attribute
- {
- private Type requiredContract;
-
- public RequiredAttributeAttribute (Type requiredContract)
- {
- this.requiredContract= requiredContract;
- }
- public Type RequiredContract
- {
- get { return this.requiredContract; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
index d20fe0bffd..926eb6c3cb 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
@@ -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);
@@ -89,72 +83,25 @@ namespace System.Runtime.CompilerServices {
_RunModuleConstructor(module.GetRuntimeModule());
}
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static unsafe extern void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void _CompileMethod(IRuntimeMethodInfo method);
- // Simple (instantiation not required) method.
- [System.Security.SecurityCritical] // auto-generated_required
- public static void PrepareMethod(RuntimeMethodHandle method)
+ public static void PrepareMethod(RuntimeMethodHandle method){}
+ public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation){}
+ public static void PrepareContractedDelegate(Delegate d){}
+
+ public static void PrepareDelegate(Delegate d)
{
- unsafe
+ if (d == null)
{
- _PrepareMethod(method.GetMethodInfo(), null, 0);
+ throw new ArgumentNullException ("d");
}
}
- // 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);
-
- [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);
@@ -183,30 +130,24 @@ 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();
-#if FEATURE_CORECLR
// This method ensures that there is sufficient stack to execute the average Framework function.
// 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)]
- internal static extern bool TryEnsureSufficientExecutionStack();
-#endif
+ public static extern bool TryEnsureSufficientExecutionStack();
- [System.Security.SecurityCritical] // auto-generated_required
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- public static extern void ProbeForSufficientStack();
+ public static void ProbeForSufficientStack()
+ {
+ }
// 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()
{
@@ -215,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)
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
index 2751d61db7..d2691df6b9 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
@@ -33,10 +33,9 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
base.GetObjectData(info, context);
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ScopelessEnumAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ScopelessEnumAttribute.cs
deleted file mode 100644
index 91769187cc..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ScopelessEnumAttribute.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.CompilerServices
-{
-[Serializable]
-[AttributeUsage(AttributeTargets.Enum)]
- public sealed class ScopelessEnumAttribute : Attribute
- {
- public ScopelessEnumAttribute()
- {}
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
index ea6bb96e16..98a81ea470 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
@@ -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,10 +199,9 @@ 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("continuation");
+ if (continuation == null) throw new ArgumentNullException(nameof(continuation));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// If TaskWait* ETW events are enabled, trace a beginning event for this await
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs
index db04eb9348..2de9c1f785 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs
@@ -17,7 +17,7 @@ namespace System.Runtime.CompilerServices
public TypeDependencyAttribute (string typeName)
{
- if(typeName == null) throw new ArgumentNullException("typeName");
+ if(typeName == null) throw new ArgumentNullException(nameof(typeName));
Contract.EndContractBlock();
this.typeName = typeName;
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs
index c1656dcf99..671d1f0071 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs
@@ -20,7 +20,7 @@ namespace System.Runtime.CompilerServices
{
if (String.IsNullOrEmpty(assemblyFullName))
{
- throw new ArgumentNullException("assemblyFullName");
+ throw new ArgumentNullException(nameof(assemblyFullName));
}
this.assemblyFullName = assemblyFullName;
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
index 034dad1afe..d9e067bd4c 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
@@ -26,7 +26,6 @@ namespace System.Runtime.CompilerServices
}
}
- [System.Security.SecurityCritical]
internal static TypeForwardedToAttribute[] GetCustomAttribute(RuntimeAssembly assembly)
{
Type[] types = null;
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
new file mode 100644
index 0000000000..b212f4555b
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
@@ -0,0 +1,80 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.Versioning;
+
+namespace System.Runtime.CompilerServices
+{
+ //
+ // Subsetted clone of System.Runtime.CompilerServices.Unsafe for internal runtime use.
+ // Keep in sync with https://github.com/dotnet/corefx/tree/master/src/System.Runtime.CompilerServices.Unsafe.
+ //
+
+ /// <summary>
+ /// Contains generic, low-level functionality for manipulating pointers.
+ /// </summary>
+ internal static unsafe class Unsafe
+ {
+ /// <summary>
+ /// Returns a pointer to the given by-ref parameter.
+ /// </summary>
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void* AsPointer<T>(ref T value)
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementationForUnsafe for how this happens.
+ throw new InvalidOperationException();
+ }
+
+ /// <summary>
+ /// Returns the size of an object of the given type parameter.
+ /// </summary>
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static int SizeOf<T>()
+ {
+ // The body of this function will be replaced by the EE with unsafe code that just returns sizeof !!T
+ // See getILIntrinsicImplementationForUnsafe for how this happens.
+ throw new InvalidOperationException();
+ }
+
+ /// <summary>
+ /// Reinterprets the given reference as a reference to a value of type <typeparamref name="TTo"/>.
+ /// </summary>
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ref TTo As<TFrom, TTo>(ref TFrom source)
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementationForUnsafe for how this happens.
+ throw new InvalidOperationException();
+ }
+
+ /// <summary>
+ /// Adds an element offset to the given reference.
+ /// </summary>
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ref T Add<T>(ref T source, int elementOffset)
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementationForUnsafe for how this happens.
+ typeof(T).ToString(); // Type used by the actual method body
+ throw new InvalidOperationException();
+ }
+
+ /// <summary>
+ /// Determines whether the specified references point to the same location.
+ /// </summary>
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static bool AreSame<T>(ref T left, ref T right)
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementationForUnsafe for how this happens.
+ throw new InvalidOperationException();
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs
index b29b39c5bf..86789bf12d 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs
@@ -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,11 +74,10 @@ 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
- if (continuation == null) throw new ArgumentNullException("continuation");
+ if (continuation == null) throw new ArgumentNullException(nameof(continuation));
Contract.EndContractBlock();
if (TplEtwProvider.Log.IsEnabled())
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
index 8ee50da290..c1346f7527 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
@@ -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;
@@ -60,6 +61,12 @@ namespace System.Runtime.CompilerServices {
public byte m_data;
}
+ internal class ArrayPinningHelper
+ {
+ public IntPtr m_lengthAndPadding;
+ public byte m_arrayData;
+ }
+
[FriendAccessAllowed]
internal static class JitHelpers
{
@@ -68,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));
@@ -76,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));
@@ -84,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!!!
@@ -112,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)
@@ -132,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!");
@@ -148,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!!!
@@ -166,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
{
@@ -189,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!!!
@@ -199,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
@@ -216,9 +212,33 @@ namespace System.Runtime.CompilerServices {
}
#if _DEBUG
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static bool IsAddressInStack(IntPtr ptr);
#endif
+
+#if FEATURE_SPAN_OF_T
+ static internal bool ByRefLessThan<T>(ref T refA, ref T refB)
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementation for how this happens.
+ throw new InvalidOperationException();
+ }
+
+ /// <returns>true if given type is reference type or value type that contains references</returns>
+ static internal bool ContainsReferences<T>()
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementation for how this happens.
+ throw new InvalidOperationException();
+ }
+
+ static internal ref T GetArrayData<T>(T[] array)
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementation for how this happens.
+ typeof(ArrayPinningHelper).ToString(); // Type used by the actual method body
+ throw new InvalidOperationException();
+ }
+#endif // FEATURE_SPAN_OF_T
}
}
diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
new file mode 100644
index 0000000000..b084891768
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
@@ -0,0 +1,41 @@
+// 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.
+/*=============================================================================
+**
+** File: ExceptionNotification.cs
+**
+**
+** Purpose: Contains definitions for supporting Exception Notifications.
+**
+** Created: 10/07/2008
+**
+** <owner>gkhanna</owner>
+**
+=============================================================================*/
+#if FEATURE_EXCEPTION_NOTIFICATIONS
+namespace System.Runtime.ExceptionServices {
+ using System;
+ using System.Runtime.ConstrainedExecution;
+
+ // Definition of the argument-type passed to the FirstChanceException event handler
+ public class FirstChanceExceptionEventArgs : EventArgs
+ {
+ // Constructor
+ public FirstChanceExceptionEventArgs(Exception exception)
+ {
+ m_Exception = exception;
+ }
+
+ // Returns the exception object pertaining to the first chance exception
+ public Exception Exception
+ {
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+ get { return m_Exception; }
+ }
+
+ // Represents the FirstChance exception instance
+ private Exception m_Exception;
+ }
+}
+#endif // FEATURE_EXCEPTION_NOTIFICATIONS \ No newline at end of file
diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs
index 7251d901cd..905f12dfb5 100644
--- a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs
+++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs
@@ -101,7 +101,7 @@ namespace System.Runtime.ExceptionServices {
{
if (source == null)
{
- throw new ArgumentNullException("source", Environment.GetResourceString("ArgumentNull_Obj"));
+ throw new ArgumentNullException(nameof(source), Environment.GetResourceString("ArgumentNull_Obj"));
}
return new ExceptionDispatchInfo(source);
diff --git a/src/mscorlib/src/System/Runtime/GcSettings.cs b/src/mscorlib/src/System/Runtime/GcSettings.cs
index 5b4be27757..91997f5297 100644
--- a/src/mscorlib/src/System/Runtime/GcSettings.cs
+++ b/src/mscorlib/src/System/Runtime/GcSettings.cs
@@ -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();
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
index 83eae1c59c..77db3a7f2c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
@@ -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();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
index 06c963a555..2de7304a0b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
index 58e93a87ea..1673c913a6 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
index 95b925c3f4..fd500fdbce 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
@@ -46,7 +46,6 @@ namespace System.Runtime.InteropServices {
SetErrorCode(errorCode);
}
- [SecuritySafeCritical]
internal COMException(int hresult)
: base(Win32Native.GetMessage(hresult))
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
index 0bf616d94c..82692c1c54 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
@@ -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;
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs
index 6feb52445d..2456ba35bf 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
index a414eff3a1..05978a607f 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
@@ -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");
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
index 54fd6b0cdd..700e059293 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
@@ -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)
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
index 1f7a9f18bf..470e7b20dd 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
@@ -27,7 +27,7 @@ namespace System.Runtime.InteropServices {
public CurrencyWrapper(Object obj)
{
if (!(obj is Decimal))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDecimal"), "obj");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDecimal"), nameof(obj));
m_WrappedObject = (Decimal)obj;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
index 1fc72f74c8..47b7542caf 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
index d63d69cabd..a9fa58f65f 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
@@ -28,14 +28,10 @@ namespace System.Runtime.InteropServices {
public ErrorWrapper(Object errorCode)
{
if (!(errorCode is int))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt32"), "errorCode");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt32"), nameof(errorCode));
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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs
index 62718de757..a12a38ec6d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ExtensibleClassFactory.cs
@@ -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);
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs b/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs
index 417cf94bd4..70a6dfe366 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs
@@ -52,7 +52,6 @@ namespace System.Runtime.InteropServices {
}
}
-#if !FEATURE_CORECLR // Breaks the subset-of-Orcas property
public override String ToString() {
String message = Message;
String s;
@@ -75,6 +74,5 @@ namespace System.Runtime.InteropServices {
return s;
}
-#endif // !FEATURE_CORECLR
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
index 58fea97cb8..5530819c5f 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
@@ -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,12 +56,11 @@ 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.
if ((uint)type > (uint)MaxHandleType)
- throw new ArgumentOutOfRangeException("type", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(type), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
m_handle = InternalAlloc(value, type);
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
index 61688b90b4..c7d7937895 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
@@ -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);
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/IException.cs b/src/mscorlib/src/System/Runtime/InteropServices/IException.cs
index 2da0a564a2..2330365834 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/IException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/IException.cs
@@ -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
}
-
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs b/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs
index ae330e8652..f2f7c61843 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/IRegistrationServices.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
index 86e88306f0..3a79650bd9 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
@@ -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,36 +134,32 @@ namespace System.Runtime.InteropServices
}
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringAnsi(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
- throw new ArgumentNullException("ptr");
+ throw new ArgumentNullException(nameof(ptr));
if (len < 0)
- throw new ArgumentException("len");
+ throw new ArgumentException(null, nameof(len));
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)
- throw new ArgumentNullException("ptr");
+ throw new ArgumentNullException(nameof(ptr));
if (len < 0)
- throw new ArgumentException("len");
+ throw new ArgumentException(null, nameof(len));
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,26 +173,23 @@ 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)
{
- throw new ArgumentException("byteLen");
+ throw new ArgumentException(null, nameof(byteLen));
}
else if (IntPtr.Zero == ptr)
{
@@ -227,7 +217,7 @@ namespace System.Runtime.InteropServices
public static int SizeOf(Object structure)
{
if (structure == null)
- throw new ArgumentNullException("structure");
+ throw new ArgumentNullException(nameof(structure));
// we never had a check for generics here
Contract.EndContractBlock();
@@ -243,11 +233,11 @@ namespace System.Runtime.InteropServices
public static int SizeOf(Type t)
{
if (t == null)
- throw new ArgumentNullException("t");
+ throw new ArgumentNullException(nameof(t));
if (!(t is RuntimeType))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(t));
if (t.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t));
Contract.EndContractBlock();
return SizeOfHelper(t, true);
@@ -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);
@@ -302,15 +289,15 @@ namespace System.Runtime.InteropServices
public static IntPtr OffsetOf(Type t, String fieldName)
{
if (t == null)
- throw new ArgumentNullException("t");
+ throw new ArgumentNullException(nameof(t));
Contract.EndContractBlock();
FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (f == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetOfFieldNotFound", t.FullName), "fieldName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_OffsetOfFieldNotFound", t.FullName), nameof(fieldName));
RtFieldInfo rtField = f as RtFieldInfo;
if (rtField == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), "fieldName");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(fieldName));
return OffsetOfHelper(rtField);
}
@@ -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,11 +797,10 @@ namespace System.Runtime.InteropServices
//====================================================================
// Prelink
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static void Prelink(MethodInfo m)
{
if (m == null)
- throw new ArgumentNullException("m");
+ throw new ArgumentNullException(nameof(m));
Contract.EndContractBlock();
RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
@@ -927,14 +812,12 @@ 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)
- throw new ArgumentNullException("c");
+ throw new ArgumentNullException(nameof(c));
Contract.EndContractBlock();
MethodInfo[] mi = c.GetMethods();
@@ -950,11 +833,10 @@ namespace System.Runtime.InteropServices
//====================================================================
// NumParamBytes
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static int NumParamBytes(MethodInfo m)
{
if (m == null)
- throw new ArgumentNullException("m");
+ throw new ArgumentNullException(nameof(m));
Contract.EndContractBlock();
RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
@@ -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)
@@ -1027,15 +901,15 @@ namespace System.Runtime.InteropServices
if (ptr == IntPtr.Zero) return null;
if (structureType == null)
- throw new ArgumentNullException("structureType");
+ throw new ArgumentNullException(nameof(structureType));
if (structureType.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "structureType");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(structureType));
RuntimeType rt = structureType.UnderlyingSystemType as RuntimeType;
if (rt == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(structureType));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -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,27 +934,25 @@ 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));
}
+#if FEATURE_COMINTEROP
//====================================================================
// Returns the HInstance for this module. Returns -1 if the module
// 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)
- throw new ArgumentNullException("m");
+ throw new ArgumentNullException(nameof(m));
Contract.EndContractBlock();
RuntimeModule rtModule = m as RuntimeModule;
@@ -1093,26 +964,24 @@ namespace System.Runtime.InteropServices
}
if (rtModule == null)
- throw new ArgumentNullException("m",Environment.GetResourceString("Argument_MustBeRuntimeModule"));
+ throw new ArgumentNullException(nameof(m),Environment.GetResourceString("Argument_MustBeRuntimeModule"));
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);
+#endif // FEATURE_COMINTEROP
//====================================================================
// 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)
@@ -1126,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)
@@ -1134,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)
@@ -1151,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);
@@ -1160,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);
@@ -1171,12 +1036,11 @@ 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)
{
if (cookie == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_ArgumentZero"), "cookie");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ArgumentZero"), nameof(cookie));
Contract.EndContractBlock();
return InternalGetThreadFromFiberCookie(cookie);
@@ -1189,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)
{
@@ -1214,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)
{
@@ -1232,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);
@@ -1246,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)
@@ -1259,7 +1118,7 @@ namespace System.Runtime.InteropServices
// Overflow checking
if (nb < s.Length)
- throw new ArgumentOutOfRangeException("s");
+ throw new ArgumentOutOfRangeException(nameof(s));
UIntPtr len = new UIntPtr((uint)nb);
IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
@@ -1276,7 +1135,6 @@ namespace System.Runtime.InteropServices
}
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToHGlobalUni(String s)
{
if (s == null)
@@ -1289,7 +1147,7 @@ namespace System.Runtime.InteropServices
// Overflow checking
if (nb < s.Length)
- throw new ArgumentOutOfRangeException("s");
+ throw new ArgumentOutOfRangeException(nameof(s));
UIntPtr len = new UIntPtr((uint)nb);
IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
@@ -1309,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
@@ -1322,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);
@@ -1332,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);
@@ -1341,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)
{
@@ -1352,11 +1206,10 @@ 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)
- throw new ArgumentNullException("typelib");
+ throw new ArgumentNullException(nameof(typelib));
Contract.EndContractBlock();
String strTypeLibName = null;
@@ -1373,11 +1226,10 @@ 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)
- throw new ArgumentNullException("typelib");
+ throw new ArgumentNullException(nameof(typelib));
Contract.EndContractBlock();
// Try GUID_ManagedName first
@@ -1415,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)
{
@@ -1425,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 ();
@@ -1439,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)
{
@@ -1449,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);
@@ -1463,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 ();
@@ -1478,16 +1325,15 @@ 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)
- throw new ArgumentNullException("asm");
+ throw new ArgumentNullException(nameof(asm));
Contract.EndContractBlock();
RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "asm");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(asm));
Guid result = new Guid();
FCallGetTypeLibGuidForAssembly(ref result, rtAssembly);
@@ -1504,16 +1350,15 @@ 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)
- throw new ArgumentNullException("inputAssembly");
+ throw new ArgumentNullException(nameof(inputAssembly));
Contract.EndContractBlock();
RuntimeAssembly rtAssembly = inputAssembly as RuntimeAssembly;
if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "inputAssembly");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(inputAssembly));
_GetTypeLibVersionForAssembly(rtAssembly, out majorVersion, out minorVersion);
}
@@ -1521,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)
{
@@ -1531,11 +1375,10 @@ 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)
- throw new ArgumentNullException("typeInfo");
+ throw new ArgumentNullException(nameof(typeInfo));
Contract.EndContractBlock();
String strTypeLibName = null;
@@ -1552,11 +1395,10 @@ 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)
- throw new ArgumentNullException("typeInfo");
+ throw new ArgumentNullException(nameof(typeInfo));
Contract.EndContractBlock();
// Try ManagedNameGuid first
@@ -1590,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;
@@ -1609,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);
@@ -1706,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);
@@ -1715,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);
@@ -1737,22 +1488,22 @@ namespace System.Runtime.InteropServices
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o);
+#endif // FEATURE_COMINTEROP
//====================================================================
// return the IDispatch* for an Object
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IDispatch */ GetIDispatchForObject(Object o)
{
- return GetIDispatchForObjectNative(o, false);
+ throw new PlatformNotSupportedException();
}
-
+
+#if FEATURE_COMINTEROP
//====================================================================
// return the IDispatch* for an Object if the current context
// 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);
@@ -1765,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));
@@ -1782,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);
@@ -1795,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);
@@ -1807,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);
@@ -1818,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);
@@ -1828,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));
@@ -1872,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)
@@ -1885,7 +1620,7 @@ namespace System.Runtime.InteropServices
// Overflow checking
if (nb < s.Length)
- throw new ArgumentOutOfRangeException("s");
+ throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
@@ -1904,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;
@@ -1918,7 +1652,7 @@ namespace System.Runtime.InteropServices
// Overflow checking
if (nb < s.Length)
- throw new ArgumentOutOfRangeException("s");
+ throw new ArgumentOutOfRangeException(nameof(s));
IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb +1));
@@ -1936,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)
@@ -1956,7 +1688,7 @@ namespace System.Runtime.InteropServices
// Overflow checking
if (nb < s.Length)
- throw new ArgumentOutOfRangeException("s");
+ throw new ArgumentOutOfRangeException(nameof(s));
IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
@@ -1972,7 +1704,6 @@ namespace System.Runtime.InteropServices
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void FreeCoTaskMem(IntPtr ptr)
{
if (IsNotWin32Atom(ptr)) {
@@ -1980,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));
@@ -1994,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))
@@ -2003,7 +1732,6 @@ namespace System.Runtime.InteropServices
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr StringToBSTR(String s)
{
if (s == null)
@@ -2011,7 +1739,7 @@ namespace System.Runtime.InteropServices
// Overflow checking
if (s.Length + 1 < s.Length)
- throw new ArgumentOutOfRangeException("s");
+ throw new ArgumentOutOfRangeException(nameof(s));
IntPtr bstr = Win32Native.SysAllocStringLen(s, s.Length);
if (bstr == IntPtr.Zero)
@@ -2020,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));
@@ -2031,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;
@@ -2043,7 +1769,7 @@ namespace System.Runtime.InteropServices
}
catch (InvalidCastException)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o));
}
return co.ReleaseSelf();
@@ -2057,11 +1783,10 @@ 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)
- throw new ArgumentNullException("o");
+ throw new ArgumentNullException(nameof(o));
Contract.EndContractBlock();
__ComObject co = null;
@@ -2073,7 +1798,7 @@ namespace System.Runtime.InteropServices
}
catch (InvalidCastException)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o));
}
co.FinalReleaseSelf();
@@ -2083,39 +1808,14 @@ namespace System.Runtime.InteropServices
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalFinalReleaseComObject(Object o);
+#endif // FEATURE_COMINTEROP
//====================================================================
// This method retrieves data from the COM object.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Object GetComObjectData(Object obj, Object key)
{
- // Validate that the arguments aren't null.
- if (obj == null)
- throw new ArgumentNullException("obj");
- if (key == null)
- throw new ArgumentNullException("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"), "obj");
- }
-
- if (obj.GetType().IsWindowsRuntimeObject)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "obj");
- }
-
- // Retrieve the data from the __ComObject.
- return comObj.GetData(key);
+ throw new PlatformNotSupportedException();
}
//====================================================================
@@ -2124,55 +1824,29 @@ 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)
{
- // Validate that the arguments aren't null. The data can validly be null.
- if (obj == null)
- throw new ArgumentNullException("obj");
- if (key == null)
- throw new ArgumentNullException("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"), "obj");
- }
-
- if (obj.GetType().IsWindowsRuntimeObject)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "obj");
- }
-
- // Retrieve the data from the __ComObject.
- return comObj.SetData(key, data);
+ throw new PlatformNotSupportedException();
}
+#if FEATURE_COMINTEROP
//====================================================================
// 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.
if (t == null)
- throw new ArgumentNullException("t");
+ throw new ArgumentNullException(nameof(t));
if (!t.IsCOMObject)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotComObject"), "t");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotComObject"), nameof(t));
if (t.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t));
Contract.EndContractBlock();
if (t.IsWindowsRuntimeObject)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeIsWinRTType"), "t");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TypeIsWinRTType"), nameof(t));
// Check for the null case.
if (o == null)
@@ -2180,9 +1854,9 @@ namespace System.Runtime.InteropServices
// Make sure the object is a COM object.
if (!o.GetType().IsCOMObject)
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o));
if (o.GetType().IsWindowsRuntimeObject)
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "o");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), nameof(o));
// Check to see if the type of the object is the requested type.
if (o.GetType() == t)
@@ -2206,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));
@@ -2215,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);
@@ -2223,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()
{
@@ -2232,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);
@@ -2294,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);
@@ -2312,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);
@@ -2320,19 +1978,18 @@ 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)
- throw new ArgumentNullException("m");
+ throw new ArgumentNullException(nameof(m));
if (!(m is RuntimeMethodInfo))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "m");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(m));
if (!m.DeclaringType.IsInterface)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeInterfaceMethod"), "m");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeInterfaceMethod"), nameof(m));
if (m.DeclaringType.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "m");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(m));
Contract.EndContractBlock();
return InternalGetComSlotForMethodInfo((IRuntimeMethodInfo)m);
@@ -2340,6 +1997,7 @@ namespace System.Runtime.InteropServices
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int InternalGetComSlotForMethodInfo(IRuntimeMethodInfo m);
+#endif // FEATURE_COMINTEROP
//====================================================================
// This method generates a GUID for the specified type. If the type
@@ -2347,38 +2005,27 @@ 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)
{
- Guid result = new Guid ();
- FCallGenerateGuidForType (ref result, type);
- return result;
+ return type.GUID;
}
- // 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);
-
//====================================================================
// This method generates a PROGID for the specified type. If the type
// has a PROGID in the metadata then it is returned otherwise a stable
// 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)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
if (type.IsImport)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustNotBeComImport"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustNotBeComImport"), nameof(type));
if (type.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
Contract.EndContractBlock();
- if (!RegistrationServices.TypeRequiresRegistrationHelper(type))
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"), "type");
-
IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type);
for (int i = 0; i < cas.Count; i ++)
{
@@ -2386,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;
@@ -2404,10 +2051,10 @@ namespace System.Runtime.InteropServices
return type.FullName;
}
+#if FEATURE_COMINTEROP
//====================================================================
// This method binds to the specified moniker.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Object BindToMoniker(String monikerName)
{
Object obj = null;
@@ -2425,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;
@@ -2449,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);
//========================================================================
@@ -2489,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 +
@@ -2500,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
@@ -2517,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);
@@ -2525,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;
@@ -2547,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)
@@ -2572,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)
@@ -2599,7 +2228,6 @@ namespace System.Runtime.InteropServices
return result;
}
- [System.Security.SecurityCritical]
internal static System.Type[] GetCachedWinRTTypes(
System.AppDomain ad)
{
@@ -2610,31 +2238,29 @@ namespace System.Runtime.InteropServices
#endif // FEATURE_COMINTEROP
- [System.Security.SecurityCritical] // auto-generated_required
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
{
// Validate the parameters
if (ptr == IntPtr.Zero)
- throw new ArgumentNullException("ptr");
+ throw new ArgumentNullException(nameof(ptr));
if (t == null)
- throw new ArgumentNullException("t");
+ throw new ArgumentNullException(nameof(t));
Contract.EndContractBlock();
if ((t as RuntimeType) == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(t));
if (t.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t));
Type c = t.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "t");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(t));
return GetDelegateForFunctionPointerInternal(ptr, t);
}
- [System.Security.SecurityCritical]
public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
{
return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
@@ -2643,17 +2269,15 @@ 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)
- throw new ArgumentNullException("d");
+ throw new ArgumentNullException(nameof(d));
Contract.EndContractBlock();
return GetFunctionPointerForDelegateInternal(d);
}
- [System.Security.SecurityCritical]
public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
{
return GetFunctionPointerForDelegate((Delegate)(object)d);
@@ -2662,47 +2286,39 @@ namespace System.Runtime.InteropServices
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d);
-#if FEATURE_LEGACYSURFACE
-
-#if FEATURE_COMINTEROP
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToBSTR(SecureString s) {
if( s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
- return s.ToBSTR();
- }
+#if FEATURE_COMINTEROP
+ return s.MarshalToBSTR();
+#else
+ throw new PlatformNotSupportedException();
#endif
+ }
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) {
if( s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
- return s.ToAnsiStr(false);
+ return s.MarshalToString(globalAlloc: false, unicode: false);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
- if (s == null)
- {
- throw new ArgumentNullException("s");
+ if( s == null) {
+ throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
- return s.ToUniStr(false);
+ return s.MarshalToString(globalAlloc: false, unicode: true);
}
-#endif // FEATURE_LEGACYSURFACE
-
-
#if FEATURE_COMINTEROP
- [System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeBSTR(IntPtr s)
{
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2));
@@ -2710,97 +2326,51 @@ 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);
}
-#if FEATURE_LEGACYSURFACE
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) {
if( s == null) {
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
- return s.ToAnsiStr(true);
+ 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("s");
+ throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
- return s.ToUniStr(true);
+ return s.MarshalToString(globalAlloc: true, unicode: true);;
}
-#endif // FEATURE_LEGACYSURFACE
- [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
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NativeBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/NativeBuffer.cs
deleted file mode 100644
index 94261621c3..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/NativeBuffer.cs
+++ /dev/null
@@ -1,175 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Runtime.CompilerServices;
-
-namespace System.Runtime.InteropServices
-{
- /// <summary>
- /// Wrapper for access to the native heap. Dispose to free the memory. Try to use with using statements.
- /// Does not allocate zero size buffers, and will free the existing native buffer if capacity is dropped to zero.
- /// </summary>
- /// <remarks>
- /// Suggested use through P/Invoke: define DllImport arguments that take a byte buffer as SafeHandle.
- ///
- /// Using SafeHandle will ensure that the buffer will not get collected during a P/Invoke.
- /// (Notably AddRef and ReleaseRef will be called by the interop layer.)
- ///
- /// This class is not threadsafe, changing the capacity or disposing on multiple threads risks duplicate heap
- /// handles or worse.
- /// </remarks>
- internal class NativeBuffer : IDisposable
- {
- [System.Security.SecurityCritical]
- private readonly static SafeHandle s_emptyHandle;
- [System.Security.SecurityCritical]
- private SafeHeapHandle _handle;
- private ulong _capacity;
-
- [System.Security.SecuritySafeCritical]
- static NativeBuffer()
- {
- s_emptyHandle = new EmptySafeHandle();
- }
-
- /// <summary>
- /// Create a buffer with at least the specified initial capacity in bytes.
- /// </summary>
- public NativeBuffer(ulong initialMinCapacity = 0)
- {
- EnsureByteCapacity(initialMinCapacity);
- }
-
- protected unsafe void* VoidPointer
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- [System.Security.SecurityCritical]
- get
- {
- return _handle == null ? null : _handle.DangerousGetHandle().ToPointer();
- }
- }
-
- protected unsafe byte* BytePointer
- {
- [System.Security.SecurityCritical]
- get
- {
- return (byte*)VoidPointer;
- }
- }
-
- /// <summary>
- /// Get the handle for the buffer.
- /// </summary>
- [System.Security.SecuritySafeCritical]
- public SafeHandle GetHandle()
- {
- // Marshalling code will throw on null for SafeHandle
- return _handle ?? s_emptyHandle;
- }
-
- /// <summary>
- /// The capacity of the buffer in bytes.
- /// </summary>
- public ulong ByteCapacity
- {
- get { return _capacity; }
- }
-
- /// <summary>
- /// Ensure capacity in bytes is at least the given minimum.
- /// </summary>
- /// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Thrown if attempting to set <paramref name="nameof(minCapacity)"/> to a value that is larger than the maximum addressable memory.</exception>
- [System.Security.SecuritySafeCritical]
- public void EnsureByteCapacity(ulong minCapacity)
- {
- if (_capacity < minCapacity)
- {
- Resize(minCapacity);
- _capacity = minCapacity;
- }
- }
-
- public unsafe byte this[ulong index]
- {
- [System.Security.SecuritySafeCritical]
- get
- {
- if (index >= _capacity) throw new ArgumentOutOfRangeException();
- return BytePointer[index];
- }
- [System.Security.SecuritySafeCritical]
- set
- {
- if (index >= _capacity) throw new ArgumentOutOfRangeException();
- BytePointer[index] = value;
- }
- }
-
- [System.Security.SecuritySafeCritical]
- private unsafe void Resize(ulong byteLength)
- {
- if (byteLength == 0)
- {
- ReleaseHandle();
- return;
- }
-
- if (_handle == null)
- {
- _handle = new SafeHeapHandle(byteLength);
- }
- else
- {
- _handle.Resize(byteLength);
- }
- }
-
- [System.Security.SecuritySafeCritical]
- private void ReleaseHandle()
- {
- if (_handle != null)
- {
- _capacity = 0;
- _handle = null;
- }
- }
-
- /// <summary>
- /// Release the backing buffer
- /// </summary>
- [System.Security.SecuritySafeCritical]
- public virtual void Free()
- {
- ReleaseHandle();
- }
-
- [System.Security.SecuritySafeCritical]
- public void Dispose()
- {
- Free();
- }
-
- [System.Security.SecurityCritical]
- private sealed class EmptySafeHandle : SafeHandle
- {
- public EmptySafeHandle() : base(IntPtr.Zero, true) { }
-
- public override bool IsInvalid
- {
- [System.Security.SecurityCritical]
- get
- { return true; }
- }
-
- [System.Security.SecurityCritical]
- protected override bool ReleaseHandle()
- {
- return true;
- }
- }
- }
-} \ No newline at end of file
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
index 82cd4fa963..650ea65697 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
@@ -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,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
index 408f56c8e2..0c8ae7649c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
@@ -33,6 +33,18 @@ namespace System.Runtime.InteropServices
}
[System.Security.SecurityCriticalAttribute]
+ public static Object BindToMoniker(String monikerName)
+ {
+ throw new PlatformNotSupportedException();
+ }
+
+ [System.Security.SecurityCriticalAttribute]
+ public static void CleanupUnusedObjectsInCurrentContext()
+ {
+ return;
+ }
+
+ [System.Security.SecurityCriticalAttribute]
public static System.IntPtr CreateAggregatedObject<T>(System.IntPtr pOuter, T o)
{
throw new PlatformNotSupportedException();
@@ -51,6 +63,12 @@ namespace System.Runtime.InteropServices
}
[System.Security.SecurityCriticalAttribute]
+ public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak)
+ {
+ throw new PlatformNotSupportedException();
+ }
+
+ [System.Security.SecurityCriticalAttribute]
public static int FinalReleaseComObject(object o)
{
throw new PlatformNotSupportedException();
@@ -75,6 +93,16 @@ namespace System.Runtime.InteropServices
}
[System.Security.SecurityCriticalAttribute]
+ public static System.IntPtr GetHINSTANCE(System.Reflection.Module m)
+ {
+ if (m == null)
+ {
+ throw new ArgumentNullException(nameof(m));
+ }
+ return (System.IntPtr) (-1);
+ }
+
+ [System.Security.SecurityCriticalAttribute]
public static System.IntPtr GetIUnknownForObject(object o)
{
throw new PlatformNotSupportedException();
@@ -93,6 +121,12 @@ namespace System.Runtime.InteropServices
}
[System.Security.SecurityCriticalAttribute]
+ public static Object GetTypedObjectForIUnknown(System.IntPtr pUnk, System.Type t)
+ {
+ throw new PlatformNotSupportedException();
+ }
+
+ [System.Security.SecurityCriticalAttribute]
public static object GetObjectForIUnknown(System.IntPtr pUnk)
{
throw new PlatformNotSupportedException();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs b/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs
index 7d3670d877..0105866415 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/RegistrationServices.cs
@@ -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,12 +92,11 @@ namespace System.Runtime.InteropServices {
#region IRegistrationServices
- [System.Security.SecurityCritical] // auto-generated_required
public virtual bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags)
{
// Validate the arguments.
if (assembly == null)
- throw new ArgumentNullException("assembly");
+ throw new ArgumentNullException(nameof(assembly));
if (assembly.ReflectionOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly"));
@@ -154,12 +154,11 @@ namespace System.Runtime.InteropServices {
return false;
}
- [System.Security.SecurityCritical] // auto-generated_required
public virtual bool UnregisterAssembly(Assembly assembly)
{
// Validate the arguments.
if (assembly == null)
- throw new ArgumentNullException("assembly");
+ throw new ArgumentNullException(nameof(assembly));
if (assembly.ReflectionOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly"));
@@ -214,16 +213,15 @@ namespace System.Runtime.InteropServices {
return false;
}
- [System.Security.SecurityCritical] // auto-generated_required
public virtual Type[] GetRegistrableTypesInAssembly(Assembly assembly)
{
// Validate the arguments.
if (assembly == null)
- throw new ArgumentNullException("assembly");
+ throw new ArgumentNullException(nameof(assembly));
Contract.EndContractBlock();
if (!(assembly is RuntimeAssembly))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "assembly");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(assembly));
// Retrieve the list of types in the assembly.
Type[] aTypes = assembly.GetExportedTypes();
@@ -246,23 +244,21 @@ 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
if(type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
if((type as RuntimeType) == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),"type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),nameof(type));
if(!TypeRequiresRegistration(type))
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),"type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),nameof(type));
// Call the native method to do CoRegisterClassObject
RegisterTypeForComClientsNative(type, ref g);
@@ -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,18 +301,17 @@ 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)
{
#if FEATURE_COMINTEROP_MANAGED_ACTIVATION
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
if ((type as RuntimeType) == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),"type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),nameof(type));
if (!TypeRequiresRegistration(type))
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),"type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),nameof(type));
// Call the native method to do CoRegisterClassObject
return RegisterTypeForComClientsExNative(type, classContext, 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
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
index d722843ae8..a5c058da43 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
index a659daf2b5..eba67ae74e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
@@ -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.
@@ -101,13 +101,13 @@ using System.Diagnostics.Contracts;
public void Initialize(ulong numBytes)
{
if (numBytes < 0)
- throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue)
- throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace"));
+ throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_AddressSpace"));
Contract.EndContractBlock();
if (numBytes >= (ulong)Uninitialized)
- throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
+ throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
_numBytes = (UIntPtr) numBytes;
}
@@ -120,16 +120,16 @@ using System.Diagnostics.Contracts;
public void Initialize(uint numElements, uint sizeOfEachElement)
{
if (numElements < 0)
- throw new ArgumentOutOfRangeException("numElements", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (sizeOfEachElement < 0)
- throw new ArgumentOutOfRangeException("sizeOfEachElement", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue)
throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace"));
Contract.EndContractBlock();
if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
- throw new ArgumentOutOfRangeException("numElements", Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
+ throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
_numBytes = checked((UIntPtr) (numElements * sizeOfEachElement));
}
@@ -245,11 +245,11 @@ using System.Diagnostics.Contracts;
where T : struct
{
if (array == null)
- throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -317,11 +317,11 @@ using System.Diagnostics.Contracts;
where T : struct
{
if (array == null)
- throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -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"));
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
index c26852874d..ed9910e4e4 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
@@ -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();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeHeapHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeHeapHandle.cs
deleted file mode 100644
index b0c422d0c0..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeHeapHandle.cs
+++ /dev/null
@@ -1,115 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.InteropServices
-{
- /// <summary>
- /// Handle for heap memory that allows tracking of capacity and reallocating.
- /// </summary>
- [System.Security.SecurityCritical]
- internal sealed class SafeHeapHandle : SafeBuffer
- {
- /// <summary>
- /// Allocate a buffer of the given size if requested.
- /// </summary>
- /// <param name="byteLength">Required size in bytes. Must be less than UInt32.MaxValue for 32 bit or UInt64.MaxValue for 64 bit.</param>
- /// <exception cref="OutOfMemoryException">Thrown if the requested memory size cannot be allocated.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Thrown if size is greater than the maximum memory size.</exception>
- public SafeHeapHandle(ulong byteLength) : base(ownsHandle: true)
- {
- Resize(byteLength);
- }
-
- public override bool IsInvalid
- {
- [System.Security.SecurityCritical]
- get
- { return handle == IntPtr.Zero; }
- }
-
- /// <summary>
- /// Resize the buffer to the given size if requested.
- /// </summary>
- /// <param name="byteLength">Required size in bytes. Must be less than UInt32.MaxValue for 32 bit or UInt64.MaxValue for 64 bit.</param>
- /// <exception cref="OutOfMemoryException">Thrown if the requested memory size cannot be allocated.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Thrown if size is greater than the maximum memory size.</exception>
- public void Resize(ulong byteLength)
- {
- if (IsClosed) throw new ObjectDisposedException("SafeHeapHandle");
-
- ulong originalLength = 0;
- if (handle == IntPtr.Zero)
- {
- handle = Marshal.AllocHGlobal((IntPtr)byteLength);
- }
- else
- {
- originalLength = ByteLength;
-
- // This may or may not be the same handle, may realloc in place. If the
- // handle changes Windows will deal with the old handle, trying to free it will
- // cause an error.
- handle = Marshal.ReAllocHGlobal(pv: handle, cb: (IntPtr)byteLength);
- }
-
- if (handle == IntPtr.Zero)
- {
- // Only real plausible answer
- throw new OutOfMemoryException();
- }
-
- if (byteLength > originalLength)
- {
- // Add pressure
- ulong addedBytes = byteLength - originalLength;
- if (addedBytes > long.MaxValue)
- {
- GC.AddMemoryPressure(long.MaxValue);
- GC.AddMemoryPressure((long)(addedBytes - long.MaxValue));
- }
- else
- {
- GC.AddMemoryPressure((long)addedBytes);
- }
- }
- else
- {
- // Shrank or did nothing, release pressure if needed
- RemoveMemoryPressure(originalLength - byteLength);
- }
-
- Initialize(byteLength);
- }
-
- private void RemoveMemoryPressure(ulong removedBytes)
- {
- if (removedBytes == 0) return;
-
- if (removedBytes > long.MaxValue)
- {
- GC.RemoveMemoryPressure(long.MaxValue);
- GC.RemoveMemoryPressure((long)(removedBytes - long.MaxValue));
- }
- else
- {
- GC.RemoveMemoryPressure((long)removedBytes);
- }
- }
-
- [System.Security.SecurityCritical]
- protected override bool ReleaseHandle()
- {
- IntPtr handle = this.handle;
- this.handle = IntPtr.Zero;
-
- if (handle != IntPtr.Zero)
- {
- RemoveMemoryPressure(ByteLength);
- Marshal.FreeHGlobal(handle);
- }
-
- return true;
- }
- }
-} \ No newline at end of file
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/StringBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/StringBuffer.cs
deleted file mode 100644
index 15b1b6ae8e..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/StringBuffer.cs
+++ /dev/null
@@ -1,402 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.InteropServices
-{
- /// <summary>
- /// Native buffer that deals in char size increments. Dispose to free memory. Allows buffers larger
- /// than a maximum size string to enable working with very large string arrays. Always makes ordinal
- /// comparisons.
- ///
- /// A more performant replacement for StringBuilder when performing native interop.
- /// </summary>
- /// <remarks>
- /// Suggested use through P/Invoke: define DllImport arguments that take a character buffer as IntPtr.
- /// NativeStringBuffer has an implicit conversion to IntPtr.
- /// </remarks>
- internal class StringBuffer : NativeBuffer
- {
- private uint _length;
-
- /// <summary>
- /// Instantiate the buffer with capacity for at least the specified number of characters. Capacity
- /// includes the trailing null character.
- /// </summary>
- public StringBuffer(uint initialCapacity = 0)
- : base(initialCapacity * (ulong)sizeof(char))
- {
- }
-
- /// <summary>
- /// Instantiate the buffer with a copy of the specified string.
- /// </summary>
- public StringBuffer(string initialContents)
- : base(0)
- {
- // We don't pass the count of bytes to the base constructor, appending will
- // initialize to the correct size for the specified initial contents.
- if (initialContents != null)
- {
- Append(initialContents);
- }
- }
-
- /// <summary>
- /// Instantiate the buffer with a copy of the specified StringBuffer.
- /// </summary>
- public StringBuffer(StringBuffer initialContents)
- : base(0)
- {
- // We don't pass the count of bytes to the base constructor, appending will
- // initialize to the correct size for the specified initial contents.
- if (initialContents != null)
- {
- Append(initialContents);
- }
- }
-
- /// <summary>
- /// Get/set the character at the given index.
- /// </summary>
- /// <exception cref="ArgumentOutOfRangeException">Thrown if attempting to index outside of the buffer length.</exception>
- public unsafe char this[uint index]
- {
- [System.Security.SecuritySafeCritical]
- get
- {
- if (index >= _length) throw new ArgumentOutOfRangeException("index");
- return CharPointer[index];
- }
- [System.Security.SecuritySafeCritical]
- set
- {
- if (index >= _length) throw new ArgumentOutOfRangeException("index");
- CharPointer[index] = value;
- }
- }
-
- /// <summary>
- /// Character capacity of the buffer. Includes the count for the trailing null character.
- /// </summary>
- public uint CharCapacity
- {
- [System.Security.SecuritySafeCritical]
- get
- {
- ulong byteCapacity = ByteCapacity;
- ulong charCapacity = byteCapacity == 0 ? 0 : byteCapacity / sizeof(char);
- return charCapacity > uint.MaxValue ? uint.MaxValue : (uint)charCapacity;
- }
- }
-
- /// <summary>
- /// Ensure capacity in characters is at least the given minimum. Capacity includes space for the trailing
- /// null, which is not part of the Length.
- /// </summary>
- /// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception>
- [System.Security.SecuritySafeCritical]
- public void EnsureCharCapacity(uint minCapacity)
- {
- EnsureByteCapacity(minCapacity * (ulong)sizeof(char));
- }
-
- /// <summary>
- /// The logical length of the buffer in characters. (Does not include the final null, which is auto appended.) Will automatically attempt to increase capacity.
- /// This is where the usable data ends.
- /// </summary>
- /// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Thrown if the set size in bytes is uint.MaxValue (as space is implicitly reservced for the trailing null).</exception>
- public unsafe uint Length
- {
- get { return _length; }
- [System.Security.SecuritySafeCritical]
- set
- {
- if (value == uint.MaxValue) throw new ArgumentOutOfRangeException("Length");
-
- // Null terminate
- EnsureCharCapacity(value + 1);
- CharPointer[value] = '\0';
-
- _length = value;
- }
- }
-
- /// <summary>
- /// For use when the native api null terminates but doesn't return a length.
- /// If no null is found, the length will not be changed.
- /// </summary>
- [System.Security.SecuritySafeCritical]
- public unsafe void SetLengthToFirstNull()
- {
- char* buffer = CharPointer;
- uint capacity = CharCapacity;
- for (uint i = 0; i < capacity; i++)
- {
- if (buffer[i] == '\0')
- {
- _length = i;
- break;
- }
- }
- }
-
- internal unsafe char* CharPointer
- {
- [System.Security.SecurityCritical]
- get
- {
- return (char*)VoidPointer;
- }
- }
-
- /// <summary>
- /// True if the buffer contains the given character.
- /// </summary>
- [System.Security.SecurityCritical]
- public unsafe bool Contains(char value)
- {
- char* start = CharPointer;
- uint length = _length;
-
- for (uint i = 0; i < length; i++)
- {
- if (*start++ == value) return true;
- }
-
- return false;
- }
-
- /// <summary>
- /// Returns true if the buffer starts with the given string.
- /// </summary>
- [System.Security.SecuritySafeCritical]
- public bool StartsWith(string value)
- {
- if (value == null) throw new ArgumentNullException("value");
- if (_length < (uint)value.Length) return false;
- return SubstringEquals(value, startIndex: 0, count: value.Length);
- }
-
- /// <summary>
- /// Returns true if the specified StringBuffer substring equals the given value.
- /// </summary>
- /// <param name="value">The value to compare against the specified substring.</param>
- /// <param name="startIndex">Start index of the sub string.</param>
- /// <param name="count">Length of the substring, or -1 to check all remaining.</param>
- /// <exception cref="ArgumentOutOfRangeException">
- /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
- /// of the buffer's length.
- /// </exception>
- [System.Security.SecuritySafeCritical]
- public unsafe bool SubstringEquals(string value, uint startIndex = 0, int count = -1)
- {
- if (value == null) return false;
- if (count < -1) throw new ArgumentOutOfRangeException("count");
- if (startIndex > _length) throw new ArgumentOutOfRangeException("startIndex");
-
- uint realCount = count == -1 ? _length - startIndex : (uint)count;
- if (checked(startIndex + realCount) > _length) throw new ArgumentOutOfRangeException("count");
-
- int length = value.Length;
-
- // Check the substring length against the input length
- if (realCount != (uint)length) return false;
-
- fixed (char* valueStart = value)
- {
- char* bufferStart = CharPointer + startIndex;
- for (int i = 0; i < length; i++)
- {
- // Note that indexing in this case generates faster code than trying to copy the pointer and increment it
- if (*bufferStart++ != valueStart[i]) return false;
- }
- }
-
- return true;
- }
-
- /// <summary>
- /// Append the given string.
- /// </summary>
- /// <param name="value">The string to append.</param>
- /// <param name="startIndex">The index in the input string to start appending from.</param>
- /// <param name="count">The count of characters to copy from the input string, or -1 for all remaining.</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
- /// <exception cref="ArgumentOutOfRangeException">
- /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
- /// of <paramref name="value"/> characters.
- /// </exception>
- [System.Security.SecuritySafeCritical]
- public void Append(string value, int startIndex = 0, int count = -1)
- {
- CopyFrom(
- bufferIndex: _length,
- source: value,
- sourceIndex: startIndex,
- count: count);
- }
-
- /// <summary>
- /// Append the given buffer.
- /// </summary>
- /// <param name="value">The buffer to append.</param>
- /// <param name="startIndex">The index in the input buffer to start appending from.</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
- /// <exception cref="ArgumentOutOfRangeException">
- /// Thrown if <paramref name="startIndex"/> is outside the range of <paramref name="value"/> characters.
- /// </exception>
- public void Append(StringBuffer value, uint startIndex = 0)
- {
- if (value == null) throw new ArgumentNullException("value");
- if (value.Length == 0) return;
- value.CopyTo(
- bufferIndex: startIndex,
- destination: this,
- destinationIndex: _length,
- count: value.Length);
- }
-
- /// <summary>
- /// Append the given buffer.
- /// </summary>
- /// <param name="value">The buffer to append.</param>
- /// <param name="startIndex">The index in the input buffer to start appending from.</param>
- /// <param name="count">The count of characters to copy from the buffer string.</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
- /// <exception cref="ArgumentOutOfRangeException">
- /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
- /// of <paramref name="value"/> characters.
- /// </exception>
- public void Append(StringBuffer value, uint startIndex, uint count)
- {
- if (value == null) throw new ArgumentNullException("value");
- if (count == 0) return;
- value.CopyTo(
- bufferIndex: startIndex,
- destination: this,
- destinationIndex: _length,
- count: count);
- }
-
- /// <summary>
- /// Copy contents to the specified buffer. Destination index must be within current destination length.
- /// Will grow the destination buffer if needed.
- /// </summary>
- /// <exception cref="ArgumentOutOfRangeException">
- /// Thrown if <paramref name="bufferIndex"/> or <paramref name="destinationIndex"/> or <paramref name="count"/> are outside the range
- /// of <paramref name="value"/> characters.
- /// </exception>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="destination"/> is null.</exception>
- [System.Security.SecuritySafeCritical]
- public unsafe void CopyTo(uint bufferIndex, StringBuffer destination, uint destinationIndex, uint count)
- {
- if (destination == null) throw new ArgumentNullException("destination");
- if (destinationIndex > destination._length) throw new ArgumentOutOfRangeException("destinationIndex");
- if (bufferIndex >= _length) throw new ArgumentOutOfRangeException("bufferIndex");
- if (_length < checked(bufferIndex + count)) throw new ArgumentOutOfRangeException("count");
-
- if (count == 0) return;
- uint lastIndex = checked(destinationIndex + count);
- if (destination._length < lastIndex) destination.Length = lastIndex;
-
- Buffer.MemoryCopy(
- source: CharPointer + bufferIndex,
- destination: destination.CharPointer + destinationIndex,
- destinationSizeInBytes: checked((long)(destination.ByteCapacity - (destinationIndex * sizeof(char)))),
- sourceBytesToCopy: checked((long)count * sizeof(char)));
- }
-
- /// <summary>
- /// Copy contents from the specified string into the buffer at the given index. Start index must be within the current length of
- /// the buffer, will grow as necessary.
- /// </summary>
- /// <exception cref="ArgumentOutOfRangeException">
- /// Thrown if <paramref name="bufferIndex"/> or <paramref name="sourceIndex"/> or <paramref name="count"/> are outside the range
- /// of <paramref name="value"/> characters.
- /// </exception>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="source"/> is null.</exception>
- [System.Security.SecuritySafeCritical]
- public unsafe void CopyFrom(uint bufferIndex, string source, int sourceIndex = 0, int count = -1)
- {
- if (source == null) throw new ArgumentNullException("source");
- if (bufferIndex > _length) throw new ArgumentOutOfRangeException("bufferIndex");
- if (sourceIndex < 0 || sourceIndex >= source.Length) throw new ArgumentOutOfRangeException("sourceIndex");
- if (count == -1) count = source.Length - sourceIndex;
- if (count < 0 || source.Length - count < sourceIndex) throw new ArgumentOutOfRangeException("count");
-
- if (count == 0) return;
- uint lastIndex = bufferIndex + (uint)count;
- if (_length < lastIndex) Length = lastIndex;
-
- fixed (char* content = source)
- {
- Buffer.MemoryCopy(
- source: content + sourceIndex,
- destination: CharPointer + bufferIndex,
- destinationSizeInBytes: checked((long)(ByteCapacity - (bufferIndex * sizeof(char)))),
- sourceBytesToCopy: (long)count * sizeof(char));
- }
- }
-
- /// <summary>
- /// Trim the specified values from the end of the buffer. If nothing is specified, nothing is trimmed.
- /// </summary>
- [System.Security.SecuritySafeCritical]
- public unsafe void TrimEnd(char[] values)
- {
- if (values == null || values.Length == 0 || _length == 0) return;
-
- char* end = CharPointer + _length - 1;
-
- while (_length > 0 && Array.IndexOf(values, *end) >= 0)
- {
- Length = _length - 1;
- end--;
- }
- }
-
- /// <summary>
- /// String representation of the entire buffer. If the buffer is larger than the maximum size string (int.MaxValue) this will throw.
- /// </summary>
- /// <exception cref="InvalidOperationException">Thrown if the buffer is too big to fit into a string.</exception>
- [System.Security.SecuritySafeCritical]
- public unsafe override string ToString()
- {
- if (_length == 0) return string.Empty;
- if (_length > int.MaxValue) throw new InvalidOperationException();
- return new string(CharPointer, startIndex: 0, length: (int)_length);
- }
-
- /// <summary>
- /// Get the given substring in the buffer.
- /// </summary>
- /// <param name="count">Count of characters to take, or remaining characters from <paramref name="startIndex"/> if -1.</param>
- /// <exception cref="ArgumentOutOfRangeException">
- /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range of the buffer's length
- /// or count is greater than the maximum string size (int.MaxValue).
- /// </exception>
- [System.Security.SecuritySafeCritical]
- public unsafe string Substring(uint startIndex, int count = -1)
- {
- if (startIndex > (_length == 0 ? 0 : _length - 1)) throw new ArgumentOutOfRangeException("startIndex");
- if (count < -1) throw new ArgumentOutOfRangeException("count");
-
- uint realCount = count == -1 ? _length - startIndex : (uint)count;
- if (realCount > int.MaxValue || checked(startIndex + realCount) > _length) throw new ArgumentOutOfRangeException("count");
- if (realCount == 0) return string.Empty;
-
- // The buffer could be bigger than will fit into a string, but the substring might fit. As the starting
- // index might be bigger than int we need to index ourselves.
- return new string(value: CharPointer + startIndex, startIndex: 0, length: (int)realCount);
- }
-
- [System.Security.SecuritySafeCritical]
- public override void Free()
- {
- base.Free();
- _length = 0;
- }
- }
-} \ No newline at end of file
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs
index 58f70e57b7..160a0ab491 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs
@@ -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 );
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs
index 0367e79bdd..862419cc98 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventSinkHelperWriter.cs
@@ -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
index e6b148a0a5..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/TypeLibConverter.cs
+++ /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("typeLib");
- if (asmFileName == null)
- throw new ArgumentNullException("asmFileName");
- if (notifySink == null)
- throw new ArgumentNullException("notifySink");
- if (String.Empty.Equals(asmFileName))
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "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
-
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs b/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs
index 9be1588ac0..c7bbb78ae6 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Variant.cs
@@ -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
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
index 5574f3c251..e3c6a926d3 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
@@ -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,11 +61,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void CopyTo(Array array, int index)
[Pure]
- [SecurityCritical]
internal void CopyTo(Array array, int arrayIndex)
{
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
// ICollection expects the destination array to be single-dimensional.
if (array.Rank != 1)
@@ -79,7 +76,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
int destLen = array.GetLength(0);
if (arrayIndex < destLB)
- throw new ArgumentOutOfRangeException("arrayIndex");
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex));
// Does the dimension in question have sufficient space to copy the expected number of entries?
// We perform this check before valid index check to ensure the exception message is in sync with
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
index 73ebf721ee..d6e50f5164 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
@@ -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,33 +28,30 @@ 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)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
return GetAt(_this, (uint)index);
}
// object this[int index] { set }
- [SecurityCritical]
internal void Indexer_Set(int index, object value)
{
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
SetAt(_this, (uint)index, value);
}
// 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,18 +116,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
// void Insert(int index, object item)
- [SecurityCritical]
internal void Insert(int index, object item)
{
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
InsertAtHelper(_this, (uint)index, item);
}
// bool Remove(object item)
- [SecurityCritical]
internal void Remove(object item)
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
@@ -154,11 +145,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
// void RemoveAt(int index)
- [SecurityCritical]
internal void RemoveAt(int index)
{
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
RemoveAtHelper(_this, (uint)index);
@@ -178,7 +168,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
@@ -196,7 +186,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
@@ -214,7 +204,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
@@ -232,7 +222,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
index c88f13dd0b..702e0c9e52 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
@@ -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)));
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs
index e379d38cf3..9705b61148 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
index af1381c366..a5abb4f23e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
@@ -45,7 +45,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal ConstantSplittableMap(IReadOnlyDictionary<TKey, TValue> data)
{
if (data == null)
- throw new ArgumentNullException("data");
+ throw new ArgumentNullException(nameof(data));
Contract.EndContractBlock();
this.firstItemIndex = 0;
@@ -56,7 +56,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal ConstantSplittableMap(IMapView<TKey, TValue> data)
{
if (data == null)
- throw new ArgumentNullException("data");
+ throw new ArgumentNullException(nameof(data));
if (((UInt32)Int32.MaxValue) < data.Size)
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
index 04fe1bf9b2..d575201bb9 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
@@ -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;
@@ -29,7 +30,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public CustomPropertyImpl(PropertyInfo propertyInfo)
{
if (propertyInfo == null)
- throw new ArgumentNullException("propertyInfo");
+ throw new ArgumentNullException(nameof(propertyInfo));
m_property = propertyInfo;
}
@@ -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);
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
index c1586ee9ce..c33e002e0e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
@@ -18,7 +18,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public DictionaryKeyCollection(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
- throw new ArgumentNullException("dictionary");
+ throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
}
@@ -26,9 +26,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public void CopyTo(TKey[] array, int index)
{
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException"));
if (array.Length - index < dictionary.Count)
@@ -90,7 +90,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public DictionaryKeyEnumerator(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
- throw new ArgumentNullException("dictionary");
+ throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
this.enumeration = dictionary.GetEnumerator();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
index fa021b7f3d..24e5777768 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
index 03e897a917..fcc7755d67 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
@@ -21,7 +21,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
public DictionaryValueCollection(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
- throw new ArgumentNullException("dictionary");
+ throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
}
@@ -29,9 +29,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
public void CopyTo(TValue[] array, int index)
{
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException"));
if (array.Length - index < dictionary.Count)
@@ -97,7 +97,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
public DictionaryValueEnumerator(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
- throw new ArgumentNullException("dictionary");
+ throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
this.enumeration = dictionary.GetEnumerator();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
index 7329d31ae8..3f9d516162 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs
index 847147ade8..4c6169a4e8 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs
index 143a33e4c7..3bbde35a3c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
index 3600a3ae70..a7424da3fb 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
@@ -28,15 +28,14 @@ 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)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
Contract.EndContractBlock();
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
@@ -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,22 +60,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// bool ContainsKey(K key)
[Pure]
- [SecurityCritical]
internal bool ContainsKey<K, V>(K key)
{
if (key == null)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
return _this.HasKey(key);
}
// bool TryGetValue(TKey key, out TValue value)
- [SecurityCritical]
internal bool TryGetValue<K, V>(K key, out V value)
{
if (key == null)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
@@ -137,7 +132,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public ReadOnlyDictionaryKeyCollection(IReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
- throw new ArgumentNullException("dictionary");
+ throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
}
@@ -146,9 +141,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public void CopyTo(TKey[] array, int index)
{
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException"));
if (array.Length - index < dictionary.Count)
@@ -192,7 +187,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public ReadOnlyDictionaryKeyEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
- throw new ArgumentNullException("dictionary");
+ throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
this.enumeration = dictionary.GetEnumerator();
@@ -232,7 +227,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public ReadOnlyDictionaryValueCollection(IReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
- throw new ArgumentNullException("dictionary");
+ throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
}
@@ -241,9 +236,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public void CopyTo(TValue[] array, int index)
{
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException"));
if (array.Length - index < dictionary.Count)
@@ -291,7 +286,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public ReadOnlyDictionaryValueEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
- throw new ArgumentNullException("dictionary");
+ throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
this.enumeration = dictionary.GetEnumerator();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
index d57f8f1f46..b185b41be0 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
index 95780bcb13..431d16256e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
@@ -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);
@@ -130,7 +126,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// that Size > Int32.MaxValue:
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
- Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
+ Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs
index 48bcc4f618..9de5e3f36d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs
@@ -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)]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
index 72d6fa8cc3..37f21307dc 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
@@ -30,15 +30,14 @@ 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)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
IVectorView<T> _this = JitHelpers.UnsafeCast<IVectorView<T>>(this);
@@ -52,14 +51,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
}
// T this[int index] { get }
- [SecurityCritical]
internal T Indexer_Get_Variance<T>(int index) where T : class
{
bool fUseString;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
index f1b799aa84..e219a86769 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
@@ -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);
@@ -123,10 +121,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// The enumerator has not been advanced to the first element yet.
if (!m_isInitialized)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
// The enumerator has reached the end of the collection
if (!m_hadCurrent)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return m_current;
}
}
@@ -137,15 +135,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// The enumerator has not been advanced to the first element yet.
if (!m_isInitialized)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
// The enumerator has reached the end of the collection
if (!m_hadCurrent)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return m_current;
}
}
- [SecuritySafeCritical]
public bool MoveNext()
{
// If we've passed the end of the iteration, IEnumerable<T> should return false, while
@@ -187,7 +184,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Translate E_CHANGED_STATE into an InvalidOperationException for an updated enumeration
if (Marshal.GetHRForException(e) == __HResults.E_CHANGED_STATE)
{
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
else
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
index 35dc495d3f..b9fe11557d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
@@ -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);
@@ -179,7 +170,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// that Size > Int32.MaxValue:
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
- Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
+ Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
index f760576aaa..2e2ea9b876 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
@@ -25,7 +25,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal ListToBindableVectorViewAdapter(IList list)
{
if (list == null)
- throw new ArgumentNullException("list");
+ throw new ArgumentNullException(nameof(list));
Contract.EndContractBlock();
@@ -38,7 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// that Size > Int32.MaxValue:
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
- Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
+ Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
index 77f3a9464f..b73f4d7a99 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
@@ -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);
@@ -212,7 +201,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// that Size > Int32.MaxValue:
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
- Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
+ Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
index 3e93428d26..2d08cab0ee 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
@@ -33,16 +33,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
private Type m_type;
- [SecurityCritical]
internal ManagedActivationFactory(Type type)
{
if (type == null)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
// Check whether the type is "exported to WinRT", i.e. it is declared in a managed .winmd and is decorated
// with at least one ActivatableAttribute or StaticAttribute.
if (!(type is RuntimeType) || !type.IsExportedToWindowsRuntime)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotActivatableViaWindowsRuntime", type), "type");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotActivatableViaWindowsRuntime", type), nameof(type));
m_type = type;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs
index 395bef93d5..f11260eb4a 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs
@@ -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,14 +131,13 @@ 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)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException("arrayIndex");
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (array.Length <= arrayIndex && Count<K, V>() > 0)
throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds"));
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
index d7897ced9f..981972ca9f 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
@@ -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,15 +27,14 @@ 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)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
Contract.EndContractBlock();
@@ -43,11 +43,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
// V this[K key] { set }
- [SecurityCritical]
internal void Indexer_Set<K, V>(K key, V value)
{
if (key == null)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
Contract.EndContractBlock();
@@ -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,22 +72,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// bool ContainsKey(K key)
[Pure]
- [SecurityCritical]
internal bool ContainsKey<K, V>(K key)
{
if (key == null)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this);
return _this.HasKey(key);
}
// void Add(K key, V value)
- [SecurityCritical]
internal void Add<K, V>(K key, V value)
{
if (key == null)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
if (ContainsKey<K, V>(key))
throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate"));
@@ -102,11 +97,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
// bool Remove(TKey key)
- [SecurityCritical]
internal bool Remove<K, V>(K key)
{
if (key == null)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this);
if (!_this.HasKey(key))
@@ -128,11 +122,10 @@ 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)
- throw new ArgumentNullException("key");
+ throw new ArgumentNullException(nameof(key));
IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this);
if (!_this.HasKey(key))
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs
index 58427fbd71..a3715da0b0 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
index b8cd65efa6..4380369754 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
@@ -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);
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs
index 5dd7d00579..cd3c53ab4e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs
@@ -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();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs
index 5eeb0afcfc..898f1a68a0 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs
@@ -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,14 +74,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
// void CopyTo(T[] array, int arrayIndex)
- [SecurityCritical]
internal void CopyTo<T>(T[] array, int arrayIndex)
{
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException("arrayIndex");
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (array.Length <= arrayIndex && Count<T>() > 0)
throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds"));
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
index f27cc95176..3e3324864d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
@@ -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,33 +27,30 @@ 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)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
return GetAt(_this, (uint)index);
}
// T this[int index] { set }
- [SecurityCritical]
internal void Indexer_Set<T>(int index, T value)
{
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
SetAt(_this, (uint)index, value);
}
// int IndexOf(T item)
- [SecurityCritical]
internal int IndexOf<T>(T item)
{
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
@@ -72,22 +70,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
// void Insert(int index, T item)
- [SecurityCritical]
internal void Insert<T>(int index, T item)
{
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
InsertAtHelper<T>(_this, (uint)index, item);
}
// void RemoveAt(int index)
- [SecurityCritical]
internal void RemoveAt<T>(int index)
{
if (index < 0)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
RemoveAtHelper<T>(_this, (uint)index);
@@ -107,7 +103,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
@@ -125,7 +121,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
@@ -143,7 +139,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
@@ -161,7 +157,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new ArgumentOutOfRangeException("index");
+ throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs
index 4b4ae5d6fc..6b7785d2dc 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
index 0d59895bc4..a786880fab 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
@@ -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) {
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
index 038efd5013..a7ad4912de 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
@@ -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,15 +24,14 @@ 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)
{
if (addMethod == null)
- throw new ArgumentNullException("addMethod");
+ throw new ArgumentNullException(nameof(addMethod));
if (removeMethod == null)
- throw new ArgumentNullException("removeMethod");
+ throw new ArgumentNullException(nameof(removeMethod));
Contract.EndContractBlock();
// Managed code allows adding a null event handler, the effect is a no-op. To match this behavior
@@ -54,11 +54,10 @@ 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)
- throw new ArgumentNullException("removeMethod");
+ throw new ArgumentNullException(nameof(removeMethod));
Contract.EndContractBlock();
// Managed code allows removing a null event handler, the effect is a no-op. To match this behavior
@@ -79,11 +78,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
ManagedEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler);
}
- [SecurityCritical]
public static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
{
if (removeMethod == null)
- throw new ArgumentNullException("removeMethod");
+ throw new ArgumentNullException(nameof(removeMethod));
Contract.EndContractBlock();
// Delegate to managed event registration implementation or native event registration implementation
@@ -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,11 +1252,10 @@ 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)
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
if (type.IsWindowsRuntimeObject && type.IsImport)
{
@@ -1291,14 +1274,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// HSTRING marshaling methods:
- [SecurityCritical]
public static IntPtr StringToHString(String s)
{
if (!Environment.IsWinRTSupported)
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
if (s == null)
- throw new ArgumentNullException("s");
+ throw new ArgumentNullException(nameof(s));
unsafe
{
@@ -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)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
index e2ad203583..9ca959c528 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
@@ -19,18 +19,16 @@ 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)
- throw new ArgumentNullException("namespaceName");
+ throw new ArgumentNullException(nameof(namespaceName));
Contract.EndContractBlock();
string[] packageGraphFilePathsArray = 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(
diff --git a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
index 75529868bd..e158a5aa8a 100644
--- a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
+++ b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
@@ -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.
@@ -83,6 +81,17 @@ namespace System.Runtime.Loader
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private static extern void GetLoadedAssembliesInternal(ObjectHandleOnStack assemblies);
+
+ public static Assembly[] GetLoadedAssemblies()
+ {
+ Assembly[] assemblies = null;
+ GetLoadedAssembliesInternal(JitHelpers.GetObjectHandleOnStack(ref assemblies));
+ return assemblies;
+ }
// These are helpers that can be used by AssemblyLoadContext derivations.
// They are used to load assemblies in DefaultContext.
@@ -90,12 +99,12 @@ namespace System.Runtime.Loader
{
if (assemblyPath == null)
{
- throw new ArgumentNullException("assemblyPath");
+ throw new ArgumentNullException(nameof(assemblyPath));
}
- if (Path.IsRelative(assemblyPath))
+ if (PathInternal.IsPartiallyQualified(assemblyPath))
{
- throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath");
+ throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath));
}
RuntimeAssembly loadedAssembly = null;
@@ -107,17 +116,17 @@ namespace System.Runtime.Loader
{
if (nativeImagePath == null)
{
- throw new ArgumentNullException("nativeImagePath");
+ throw new ArgumentNullException(nameof(nativeImagePath));
}
- if (Path.IsRelative(nativeImagePath))
+ if (PathInternal.IsPartiallyQualified(nativeImagePath))
{
- throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "nativeImagePath");
+ throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(nativeImagePath));
}
- if (assemblyPath != null && Path.IsRelative(assemblyPath))
+ if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath");
+ throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath));
}
// Basic validation has succeeded - lets try to load the NI image.
@@ -136,7 +145,7 @@ namespace System.Runtime.Loader
{
if (assembly == null)
{
- throw new ArgumentNullException("assembly");
+ throw new ArgumentNullException(nameof(assembly));
}
int iAssemblyStreamLength = (int)assembly.Length;
@@ -291,15 +300,15 @@ namespace System.Runtime.Loader
{
if (unmanagedDllPath == null)
{
- throw new ArgumentNullException("unmanagedDllPath");
+ throw new ArgumentNullException(nameof(unmanagedDllPath));
}
if (unmanagedDllPath.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "unmanagedDllPath");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(unmanagedDllPath));
}
- if (Path.IsRelative(unmanagedDllPath))
+ if (PathInternal.IsPartiallyQualified(unmanagedDllPath))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "unmanagedDllPath");
+ throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(unmanagedDllPath));
}
return InternalLoadUnmanagedDllFromPath(unmanagedDllPath);
@@ -355,7 +364,7 @@ namespace System.Runtime.Loader
{
if (context == null)
{
- throw new ArgumentNullException("context");
+ throw new ArgumentNullException(nameof(context));
}
// Try to override the default assembly load context
@@ -378,10 +387,10 @@ namespace System.Runtime.Loader
{
if (assemblyPath == null)
{
- throw new ArgumentNullException("assemblyPath");
+ throw new ArgumentNullException(nameof(assemblyPath));
}
-
- String fullPath = Path.GetFullPathInternal(assemblyPath);
+
+ string fullPath = Path.GetFullPath(assemblyPath);
return nGetFileInformation(fullPath);
}
@@ -394,7 +403,7 @@ namespace System.Runtime.Loader
{
if (assembly == null)
{
- throw new ArgumentNullException("assembly");
+ throw new ArgumentNullException(nameof(assembly));
}
AssemblyLoadContext loadContextForAssembly = null;
@@ -459,16 +468,43 @@ namespace System.Runtime.Loader
// Synchronization primitive for controlling initialization of Default load context
private static readonly object s_initLock = new Object();
+
+ // Occurs when an Assembly is loaded
+ public static event AssemblyLoadEventHandler AssemblyLoad
+ {
+ add { AppDomain.CurrentDomain.AssemblyLoad += value; }
+ remove { AppDomain.CurrentDomain.AssemblyLoad -= value; }
+ }
+
+ // Occurs when resolution of type fails
+ public static event ResolveEventHandler TypeResolve
+ {
+ add { AppDomain.CurrentDomain.TypeResolve += value; }
+ remove { AppDomain.CurrentDomain.TypeResolve -= value; }
+ }
+
+ // Occurs when resolution of resource fails
+ public static event ResolveEventHandler ResourceResolve
+ {
+ add { AppDomain.CurrentDomain.ResourceResolve += value; }
+ remove { AppDomain.CurrentDomain.ResourceResolve -= value; }
+ }
+
+ // Occurs when resolution of assembly fails
+ // This event is fired after resolve events of AssemblyLoadContext fails
+ public static event ResolveEventHandler AssemblyResolve
+ {
+ add { AppDomain.CurrentDomain.AssemblyResolve += value; }
+ remove { AppDomain.CurrentDomain.AssemblyResolve -= value; }
+ }
}
- [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.
@@ -476,6 +512,18 @@ namespace System.Runtime.Loader
return null;
}
}
+
+ internal class IndividualAssemblyLoadContext : AssemblyLoadContext
+ {
+ internal IndividualAssemblyLoadContext() : base(false)
+ {
+ }
+
+ protected override Assembly Load(AssemblyName assemblyName)
+ {
+ return null;
+ }
+ }
}
#endif // FEATURE_HOST_ASSEMBLY_RESOLVER
diff --git a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
index 6e35568310..bd87d9027c 100644
--- a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
+++ b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
@@ -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,13 +153,13 @@ 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)
- throw new ArgumentOutOfRangeException("sizeInMegabytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
+#if !FEATURE_PAL // Remove this when CheckForAvailableMemory is able to provide legitimate estimates
ulong size = ((ulong)sizeInMegabytes) << 20;
_reservedMemory = size;
@@ -283,7 +283,7 @@ namespace System.Runtime
break;
default:
- Contract.Assert(false, "Fell through switch statement!");
+ Debug.Assert(false, "Fell through switch statement!");
break;
}
}
@@ -302,9 +302,9 @@ namespace System.Runtime
SharedStatics.AddMemoryFailPointReservation((long) size);
_mustSubtractReservation = true;
}
+#endif
}
- [System.Security.SecurityCritical] // auto-generated
private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree)
{
bool r;
@@ -321,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
@@ -348,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)
@@ -375,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);
@@ -392,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)
{
diff --git a/src/mscorlib/src/System/Runtime/ProfileOptimization.cs b/src/mscorlib/src/System/Runtime/ProfileOptimization.cs
index c877d2106d..1e42308ecc 100644
--- a/src/mscorlib/src/System/Runtime/ProfileOptimization.cs
+++ b/src/mscorlib/src/System/Runtime/ProfileOptimization.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs b/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
index 2524aaaecb..eb5a186b65 100644
--- a/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
+++ b/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
@@ -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()
{
diff --git a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
index d10df9d57b..5555670498 100644
--- a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
+++ b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
@@ -14,23 +14,14 @@
**
===========================================================*/
-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
}
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs
index 7df221c9cd..b710ed0b3a 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs
@@ -25,7 +25,7 @@ namespace System.Runtime.Serialization {
public Object Convert(Object value, Type type) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
@@ -33,7 +33,7 @@ namespace System.Runtime.Serialization {
public Object Convert(Object value, TypeCode typeCode) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture);
@@ -41,7 +41,7 @@ namespace System.Runtime.Serialization {
public bool ToBoolean(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToBoolean(value, CultureInfo.InvariantCulture);
@@ -49,7 +49,7 @@ namespace System.Runtime.Serialization {
public char ToChar(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToChar(value, CultureInfo.InvariantCulture);
@@ -58,7 +58,7 @@ namespace System.Runtime.Serialization {
[CLSCompliant(false)]
public sbyte ToSByte(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToSByte(value, CultureInfo.InvariantCulture);
@@ -66,7 +66,7 @@ namespace System.Runtime.Serialization {
public byte ToByte(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToByte(value, CultureInfo.InvariantCulture);
@@ -74,7 +74,7 @@ namespace System.Runtime.Serialization {
public short ToInt16(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToInt16(value, CultureInfo.InvariantCulture);
@@ -83,7 +83,7 @@ namespace System.Runtime.Serialization {
[CLSCompliant(false)]
public ushort ToUInt16(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToUInt16(value, CultureInfo.InvariantCulture);
@@ -91,7 +91,7 @@ namespace System.Runtime.Serialization {
public int ToInt32(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToInt32(value, CultureInfo.InvariantCulture);
@@ -100,7 +100,7 @@ namespace System.Runtime.Serialization {
[CLSCompliant(false)]
public uint ToUInt32(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToUInt32(value, CultureInfo.InvariantCulture);
@@ -108,7 +108,7 @@ namespace System.Runtime.Serialization {
public long ToInt64(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToInt64(value, CultureInfo.InvariantCulture);
@@ -117,7 +117,7 @@ namespace System.Runtime.Serialization {
[CLSCompliant(false)]
public ulong ToUInt64(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToUInt64(value, CultureInfo.InvariantCulture);
@@ -125,7 +125,7 @@ namespace System.Runtime.Serialization {
public float ToSingle(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToSingle(value, CultureInfo.InvariantCulture);
@@ -133,7 +133,7 @@ namespace System.Runtime.Serialization {
public double ToDouble(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToDouble(value, CultureInfo.InvariantCulture);
@@ -141,7 +141,7 @@ namespace System.Runtime.Serialization {
public Decimal ToDecimal(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToDecimal(value, CultureInfo.InvariantCulture);
@@ -149,7 +149,7 @@ namespace System.Runtime.Serialization {
public DateTime ToDateTime(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture);
@@ -157,7 +157,7 @@ namespace System.Runtime.Serialization {
public String ToString(Object value) {
if (value==null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToString(value, CultureInfo.InvariantCulture);
diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
index c6f27b5b2a..27c3f15136 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
@@ -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,12 +191,11 @@ 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;
if ((object)type==null) {
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
@@ -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,10 +245,9 @@ 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("type");
+ throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
@@ -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("type");
+ 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,18 +323,17 @@ 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("obj");
+ throw new ArgumentNullException(nameof(obj));
}
if (members==null) {
- throw new ArgumentNullException("members");
+ throw new ArgumentNullException(nameof(members));
}
if (data==null) {
- throw new ArgumentNullException("data");
+ throw new ArgumentNullException(nameof(data));
}
if (members.Length!=data.Length) {
@@ -372,7 +349,7 @@ namespace System.Runtime.Serialization {
mi = members[i];
if (mi==null) {
- throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i));
+ throw new ArgumentNullException(nameof(members), Environment.GetResourceString("ArgumentNull_NullMember", i));
}
//If we find an empty, it means that the value was never set during deserialization.
@@ -400,15 +377,14 @@ 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) {
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
}
if (members==null) {
- throw new ArgumentNullException("members");
+ throw new ArgumentNullException(nameof(members));
}
Contract.EndContractBlock();
@@ -421,11 +397,11 @@ namespace System.Runtime.Serialization {
mi=members[i];
if (mi==null) {
- throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i));
+ throw new ArgumentNullException(nameof(members), Environment.GetResourceString("ArgumentNull_NullMember", i));
}
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,12 +419,11 @@ namespace System.Runtime.Serialization {
return data;
}
- [System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
{
if (innerSurrogate == null)
- throw new ArgumentNullException("innerSurrogate");
+ throw new ArgumentNullException(nameof(innerSurrogate));
Contract.EndContractBlock();
return new SurrogateForCyclicalReference(innerSurrogate);
}
@@ -459,10 +434,9 @@ 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("assem");
+ throw new ArgumentNullException(nameof(assem));
Contract.EndContractBlock();
return assem.GetType(name, false, false);
}
@@ -499,7 +473,7 @@ namespace System.Runtime.Serialization {
internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom) {
if ((object)type == null) {
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
}
object[] typeAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false);
@@ -566,17 +540,15 @@ namespace System.Runtime.Serialization {
internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
{
if (innerSurrogate == null)
- throw new ArgumentNullException("innerSurrogate");
+ throw new ArgumentNullException(nameof(innerSurrogate));
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);
diff --git a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
index f1a1bc0590..42662a10f6 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
@@ -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);
}
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs b/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
index e59fa65043..fc283d41f1 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
@@ -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);
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs b/src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs
index 9bb30d99e0..226bbdcc75 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/ISerializationSurrogate.cs
@@ -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);
}
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs b/src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs
index 01b960f86b..87b7845894 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/ISurrogateSelector.cs
@@ -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();
}
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs b/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs
new file mode 100644
index 0000000000..585d367605
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs
@@ -0,0 +1,446 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+using System.Reflection;
+using System.Security;
+
+namespace System.Runtime.Serialization
+{
+ //
+ // #SafeSerialization
+ //
+ // Types which are serializable via the ISerializable interface have a problem when it comes to allowing
+ // transparent subtypes which can allow themselves to serialize since the GetObjectData method is
+ // SecurityCritical.
+ //
+ // For instance, System.Exception implements ISerializable, however it is also desirable to have
+ // transparent exceptions with their own fields that need to be serialized. (For instance, in transparent
+ // assemblies such as the DLR and F#, or even in partial trust application code). Since overriding
+ // GetObjectData requires that the overriding method be security critical, this won't work directly.
+ //
+ // SafeSerializationManager solves this problem by allowing any partial trust code to contribute
+ // individual chunks of serializable data to be included in the serialized version of the derived class.
+ // These chunks are then deserialized back out of the serialized type and notified that they should
+ // populate the fields of the deserialized object when serialization is complete. This allows partial
+ // trust or transparent code to participate in serialization of an ISerializable type without having to
+ // override GetObjectData or implement the ISerializable constructor.
+ //
+ // On the serialization side, SafeSerializationManager has an event SerializeObjectState which it will
+ // fire in response to serialization in order to gather the units of serializable data that should be
+ // stored with the rest of the object during serialization. Methods which respond to these events
+ // create serializable objects which implement the ISafeSerializationData interface and add them to the
+ // collection of other serialized data by calling AddSerializedState on the SafeSerializationEventArgs
+ // passed into the event.
+ //
+ // By using an event rather than a virtual method on the base ISerializable object, we allow multiple
+ // potentially untrusted subclasses to participate in serialization, without each one having to ensure
+ // that it calls up to the base type in order for the whole system to work. (For instance Exception :
+ // TrustedException : UntrustedException, in this scenario UntrustedException would be able to override
+ // the virtual method an prevent TrustedException from ever seeing the method call, either accidentally
+ // or maliciously).
+ //
+ // Further, by only allowing additions of new chunks of serialization state rather than exposing the
+ // whole underlying list, we avoid exposing potentially sensitive serialized state to any of the
+ // potentially untrusted subclasses.
+ //
+ // At deserialization time, SafeSerializationManager performs the reverse operation. It deserializes the
+ // chunks of serialized state, and then notifies them that the object they belong to is deserialized by
+ // calling their CompleteSerialization method. In repsonse to this call, the state objects populate the
+ // fields of the object being deserialized with the state that they held.
+ //
+ // From a security perspective, the chunks of serialized state can only contain data that the specific
+ // subclass itself had access to read (otherwise it wouldn't be able to populate the type with that
+ // data), as opposed to having access to far more data in the SerializationInfo that GetObjectData uses.
+ // Similarly, at deserialization time, the serialized state can only modify fields that the type itself
+ // has access to (again, as opposed to the full SerializationInfo which could be modified).
+ //
+ // Individual types which wish to participate in safe serialization do so by containing an instance of a
+ // SafeSerializationManager and exposing its serialization event. During GetObjectData, the
+ // SafeSerializationManager is serialized just like any other field of the containing type. However, at
+ // the end of serialization it is called back one last time to CompleteSerialization.
+ //
+ // In CompleteSerialization, if the SafeSerializationManager detects that it has extra chunks of
+ // data to handle, it substitutes the root type being serialized (formerly the real type hosting the
+ // SafeSerializationManager) with itself. This allows it to gain more control over the deserialization
+ // process. It also saves away an extra bit of state in the serialization info indicating the real type
+ // of object that should be recreated during deserialization.
+ //
+ // At this point the serialized state looks like this:
+ // Data:
+ // realSerializedData1
+ // ...
+ // realSerializedDataN
+ // safeSerializationData -> this is the serialization data member of the parent type
+ // m_serializedState -> list of saved serialized states from subclasses responding to the safe
+ // serialization event
+ // RealTypeSerializationName -> type which is using safe serialization
+ // Type:
+ // SafeSerializationManager
+ //
+ // That is, the serialized data claims to be of type SafeSerializationManager, however contains only the
+ // data from the real object being serialized along with one bit of safe serialization metadata.
+ //
+ // At deserialization time, since the serialized data claims to be of type SafeSerializationManager, the
+ // root object being created is an instance of the SafeSerializationManager class. However, it detects
+ // that this isn't a real SafeSerializationManager (by looking for the real type field in the metadata),
+ // and simply saves away the SerializationInfo and the real type being deserialized.
+ //
+ // Since SafeSerializationManager implements IObjectReference, the next step of deserialization is the
+ // GetRealObject callback. This callback is the one responsible for getting the
+ // SafeSerializationManager out of the way and instead creating an instance of the actual type which was
+ // serialized.
+ //
+ // It does this by first creating an instance of the real type being deserialzed (saved away in the
+ // deserialzation constructor), but not running any of its constructors. Instead, it walks the
+ // inheritance hierarchy (moving toward the most derived type) looking for the last full trust type to
+ // implement the standard ISerializable constructor before any type does not implement the constructor.
+ // It is this last type's deserialization constructor which is then invoked, passing in the saved
+ // SerializationInfo. Once the constructors are run, we return this object as the real deserialized
+ // object.
+ //
+ // The reason that we do this walk is so that ISerializable types can protect themselves from malicious
+ // input during deserialization by making their deserialization constructors unavailable to partial
+ // trust code. By not requiring every type have a copy of this constructor, partial trust code can
+ // participate in safe serialization and not be required to have access to the parent's constructor.
+ //
+ // It should be noted however, that this heuristic means that if a full trust type does derive from
+ // a transparent or partial trust type using this safe serialization mechanism, that full trust type
+ // will not have its constructor called. Further, the protection of not invoking partial trust
+ // deserialization constructors only comes into play if SafeSerializationManager is in control of
+ // deserialization, which means there must be at least one (even empty) safe serialization event
+ // handler registered.
+ //
+ // Another interesting note is that at this point there are now two SafeSerializationManagers alive for
+ // this deserialization. The first object is the one which is controlling the deserialization and was
+ // created as the root object of the deserialization. The second one is the object which contains the
+ // serialized data chunks and is a data member of the real object being deserialized. For this reason,
+ // the data objects cannot be notified that the deserialization is complete during GetRealObject since
+ // the ISafeSerializationData objects are not members of the active SafeSerializationManager instance.
+ //
+ // The next step is the OnDeserialized callback, which comes to SafeSerializableObject since it was
+ // pretending to be the root object of the deserialization. It responds to this callback by calling
+ // any existing OnDeserialized callback on the real type that was deserialized.
+ //
+ // The real type needs to call its data member SafeSerializationData object's CompleteDeserialization
+ // method in response to the OnDeserialized call. This CompleteDeserialization call will then iterate
+ // through the ISafeSerializationData objects calling each of their CompleteDeserialization methods so
+ // that they can plug the nearly-complete object with their saved data.
+ //
+ // The reason for having a new ISafeSerializationData interface which is basically identical to
+ // IDeserializationCallback is that IDeserializationCallback will be called on the stored data chunks
+ // by the serialization code when they are deserialized, and that's not a desirable behavior.
+ // Essentially, we need to change the meaning of the object parameter to mean "parent object which
+ // participated in safe serialization", rather than "this object".
+ //
+ // Implementing safe serialization on an ISerialiable type is relatively straight forward. (For an
+ // example, see System.Exception):
+ //
+ // 1. Include a data member of type SafeSerializationManager:
+ //
+ // private SafeSerializationManager m_safeSerializationManager;
+ //
+ // 2. Add a protected SerializeObjectState event, which passes through to the SafeSerializationManager:
+ //
+ // protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
+ // {
+ // add { m_safeSerializationManager.SerializeObjectState += value; }
+ // remove { m_safeSerializationManager.SerializeObjectState -= value; }
+ // }
+ //
+ // 3. Serialize the safe serialization object in GetObjectData, and call its CompleteSerialization method:
+ //
+ // {
+ // info.AddValue("m_safeSerializationManager", m_safeSerializationManager, typeof(SafeSerializationManager));
+ // m_safeSerializationManager.CompleteSerialization(this, info, context);
+ // }
+ //
+ // 4. Add an OnDeserialized handler if one doesn't already exist, and call CompleteDeserialization in it:
+ //
+ // [OnDeserialized]
+ // private void OnDeserialized(StreamingContext context)
+ // {
+ // m_safeSerializationManager.CompleteDeserialization(this);
+ // }
+ //
+ // On the client side, using safe serialization is also pretty easy. For example:
+ //
+ // [Serializable]
+ // public class TransparentException : Exception
+ // {
+ // [Serializable]
+ // private struct TransparentExceptionState : ISafeSerializationData
+ // {
+ // public string m_extraData;
+ //
+ // void ISafeSerializationData.CompleteDeserialization(object obj)
+ // {
+ // TransparentException exception = obj as TransparentException;
+ // exception.m_state = this;
+ // }
+ // }
+ //
+ // [NonSerialized]
+ // private TransparentExceptionState m_state = new TransparentExceptionState();
+ //
+ // public TransparentException()
+ // {
+ // SerializeObjectState += delegate(object exception, SafeSerializationEventArgs eventArgs)
+ // {
+ // eventArgs.AddSerializedState(m_state);
+ // };
+ // }
+ //
+ // public string ExtraData
+ // {
+ // get { return m_state.m_extraData; }
+ // set { m_state.m_extraData = value; }
+ // }
+ // }
+ //
+
+ // SafeSerializationEventArgs are provided to the delegates which do safe serialization. Each delegate
+ // serializes its own state into an IDeserializationCallback instance which must, itself, be serializable.
+ // These indivdiual states are then added to the SafeSerializationEventArgs in order to be saved away when
+ // the original ISerializable type is serialized.
+ public sealed class SafeSerializationEventArgs : EventArgs
+ {
+ private StreamingContext m_streamingContext;
+ private List<object> m_serializedStates = new List<object>();
+
+ internal SafeSerializationEventArgs(StreamingContext streamingContext)
+ {
+ m_streamingContext = streamingContext;
+ }
+
+ public void AddSerializedState(ISafeSerializationData serializedState)
+ {
+ if (serializedState == null)
+ throw new ArgumentNullException(nameof(serializedState));
+ if (!serializedState.GetType().IsSerializable)
+ throw new ArgumentException(Environment.GetResourceString("Serialization_NonSerType", serializedState.GetType(), serializedState.GetType().Assembly.FullName));
+
+ m_serializedStates.Add(serializedState);
+ }
+
+ internal IList<object> SerializedStates
+ {
+ get { return m_serializedStates; }
+ }
+
+ public StreamingContext StreamingContext
+ {
+ get { return m_streamingContext; }
+ }
+ }
+
+ // Interface to be supported by objects which are stored in safe serialization stores
+ public interface ISafeSerializationData
+ {
+ // CompleteDeserialization is called when the object to which the extra serialized data was attached
+ // has completed its deserialization, and now needs to be populated with the extra data stored in
+ // this object.
+ void CompleteDeserialization(object deserialized);
+ }
+#if FEATURE_SERIALIZATION
+ // Helper class to implement safe serialization. Concrete ISerializable types which want to allow
+ // transparent subclasses code to participate in serialization should contain an instance of
+ // SafeSerializationManager and wire up to it as described in code:#SafeSerialization.
+ [Serializable]
+ internal sealed class SafeSerializationManager : IObjectReference, ISerializable
+ {
+ // Saved states to store in the serialization stream. This is typed as object rather than
+ // ISafeSerializationData because ISafeSerializationData can't be marked serializable.
+ private IList<object> m_serializedStates;
+
+ // This is the SerializationInfo that is used when the SafeSerializationManager type has replaced
+ // itself as the target of serialziation. It is not used directly by the safe serialization code,
+ // but just held onto so that the real object being deserialzed can use it later.
+ private SerializationInfo m_savedSerializationInfo;
+
+ // Real object that we've deserialized - this is stored when we complete construction and calling
+ // the deserialization .ctors on it and is used when we need to notify the stored safe
+ // deserialization data that they should populate the object with their fields.
+ private object m_realObject;
+
+ // Real type that should be deserialized
+ private RuntimeType m_realType;
+
+ // Event fired when we need to collect state to serialize into the parent object
+ internal event EventHandler<SafeSerializationEventArgs> SerializeObjectState;
+
+ // Name that is used to store the real type being deserialized in the main SerializationInfo
+ private const string RealTypeSerializationName = "CLR_SafeSerializationManager_RealType";
+
+ internal SafeSerializationManager()
+ {
+ }
+
+ private SafeSerializationManager(SerializationInfo info, StreamingContext context)
+ {
+ // We need to determine if we're being called to really deserialize a SafeSerializationManager,
+ // or if we're being called because we've intercepted the deserialization callback for the real
+ // object being deserialized. We use the presence of the RealTypeSerializationName field in the
+ // serialization info to indicate that this is the interception callback and we just need to
+ // safe the info. If that field is not present, then we should be in a real deserialization
+ // construction.
+ RuntimeType realType = info.GetValueNoThrow(RealTypeSerializationName, typeof(RuntimeType)) as RuntimeType;
+
+ if (realType == null)
+ {
+ m_serializedStates = info.GetValue("m_serializedStates", typeof(List<object>)) as List<object>;
+ }
+ else
+ {
+ m_realType = realType;
+ m_savedSerializationInfo = info;
+ }
+ }
+
+ // Determine if the serialization manager is in an active state - that is if any code is hooked up
+ // to use it for serialization
+ internal bool IsActive
+ {
+ get { return SerializeObjectState != null; }
+ }
+
+ // 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.
+ internal void CompleteSerialization(object serializedObject,
+ SerializationInfo info,
+ StreamingContext context)
+ {
+ Contract.Requires(serializedObject != null);
+ Contract.Requires(info != null);
+ Contract.Requires(typeof(ISerializable).IsAssignableFrom(serializedObject.GetType()));
+ Contract.Requires(serializedObject.GetType().IsAssignableFrom(info.ObjectType));
+
+ // Clear out any stale state
+ m_serializedStates = null;
+
+ // We only want to kick in our special serialization sauce if someone wants to participate in
+ // it, otherwise if we have no delegates registered there's no reason for us to get in the way
+ // of the regular serialization machinery.
+ EventHandler<SafeSerializationEventArgs> serializeObjectStateEvent = SerializeObjectState;
+ if (serializeObjectStateEvent != null)
+ {
+ // Get any extra data to add to our serialization state now
+ SafeSerializationEventArgs eventArgs = new SafeSerializationEventArgs(context);
+ serializeObjectStateEvent(serializedObject, eventArgs);
+ m_serializedStates = eventArgs.SerializedStates;
+
+ // Replace the type to be deserialized by the standard serialization code paths with
+ // ourselves, which allows us to control the deserialization process.
+ info.AddValue(RealTypeSerializationName, serializedObject.GetType(), typeof(RuntimeType));
+ info.SetType(typeof(SafeSerializationManager));
+ }
+ }
+
+ // CompleteDeserialization is called by the base ISerializable object's OnDeserialized handler to
+ // finish the deserialization of the object by notifying the saved states that they should
+ // re-populate their portions of the deserialized object.
+ internal void CompleteDeserialization(object deserializedObject)
+ {
+ Contract.Requires(deserializedObject != null);
+
+ if (m_serializedStates != null)
+ {
+ foreach (ISafeSerializationData serializedState in m_serializedStates)
+ {
+ serializedState.CompleteDeserialization(deserializedObject);
+ }
+ }
+ }
+
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ info.AddValue("m_serializedStates", m_serializedStates, typeof(List<IDeserializationCallback>));
+ }
+
+ // 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.
+ object IObjectReference.GetRealObject(StreamingContext context)
+ {
+ // If we've already deserialized the real object, use that rather than deserializing it again
+ if (m_realObject != null)
+ {
+ return m_realObject;
+ }
+
+ // If we don't have a real type to deserialize, then this is really a SafeSerializationManager
+ // and we don't need to rebuild the object that we're standing in for.
+ if (m_realType == null)
+ {
+ return this;
+ }
+
+ // Look for the last type in GetRealType's inheritance hierarchy which implements a critical
+ // deserialization constructor. This will be the object that we use as the deserialization
+ // construction type to initialize via standard ISerializable semantics
+
+ // First build up the chain starting at the type below Object and working to the real type we
+ // serialized.
+ Stack inheritanceChain = new Stack();
+ RuntimeType currentType = m_realType;
+ do
+ {
+ inheritanceChain.Push(currentType);
+ currentType = currentType.BaseType as RuntimeType;
+ }
+ while (currentType != typeof(object));
+
+ // Now look for the first type that does not implement the ISerializable .ctor. When we find
+ // that, previousType will point at the last type that did implement the .ctor. We require that
+ // the .ctor we invoke also be non-transparent
+ RuntimeConstructorInfo serializationCtor = null;
+ RuntimeType previousType = null;
+ do
+ {
+ previousType = currentType;
+ currentType = inheritanceChain.Pop() as RuntimeType;
+ serializationCtor = currentType.GetSerializationCtor();
+ }
+ while (serializationCtor != null && serializationCtor.IsSecurityCritical);
+
+ // previousType is the last type that did implement the deserialization .ctor before the first
+ // type that did not, so we'll grab it's .ctor to use for deserialization.
+ BCLDebug.Assert(previousType != null, "We should have at least one inheritance from the base type");
+ serializationCtor = ObjectManager.GetConstructor(previousType);
+
+ // Allocate an instance of the final type and run the selected .ctor on that instance to get the
+ // standard ISerializable initialization done.
+ object deserialized = FormatterServices.GetUninitializedObject(m_realType);
+ serializationCtor.SerializationInvoke(deserialized, m_savedSerializationInfo, context);
+ m_savedSerializationInfo = null;
+ m_realType = null;
+
+ // Save away the real object that was deserialized so that we can fill it in later, and return
+ // it back as the object that should result from the final deserialization.
+ m_realObject = deserialized;
+ return deserialized;
+ }
+
+ [OnDeserialized]
+ private void OnDeserialized(StreamingContext context)
+ {
+ // We only need to complete deserialization if we were hooking the deserialization process. If
+ // we have not deserialized an object in the GetRealObject call, then there's nothing more for
+ // us to do here.
+ if (m_realObject != null)
+ {
+ // Fire the real object's OnDeserialized method if they registered one. Since we replaced
+ // ourselves as the target of the deserialization, OnDeserialized on the target won't
+ // automatically get triggered unless we do it manually.
+ SerializationEvents cache = SerializationEventsCache.GetSerializationEventsForType(m_realObject.GetType());
+ cache.InvokeOnDeserialized(m_realObject, context);
+ m_realObject = null;
+ }
+ }
+ }
+#endif
+}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs
index 5e7851bc57..82536ce3b4 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationFieldInfo.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
index 94e6825b51..55909c85fd 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
@@ -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
@@ -61,12 +57,12 @@ namespace System.Runtime.Serialization
{
if ((object)type == null)
{
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
}
if (converter == null)
{
- throw new ArgumentNullException("converter");
+ throw new ArgumentNullException(nameof(converter));
}
Contract.EndContractBlock();
@@ -96,7 +92,7 @@ namespace System.Runtime.Serialization
{
if (null == value)
{
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -111,12 +107,11 @@ namespace System.Runtime.Serialization
{
return m_assemName;
}
- [SecuritySafeCritical]
set
{
if (null == value)
{
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
if (this.requireSameTokenInPartialTrust)
@@ -128,12 +123,11 @@ namespace System.Runtime.Serialization
}
}
- [SecuritySafeCritical]
public void SetType(Type type)
{
if ((object)type == null)
{
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
@@ -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);
@@ -280,12 +267,12 @@ namespace System.Runtime.Serialization
{
if (null == name)
{
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
}
if ((object)type == null)
{
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
@@ -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)
@@ -447,7 +429,7 @@ namespace System.Runtime.Serialization
{
if (null == name)
{
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
BCLDebug.Trace("SER", "[SerializationInfo.FindElement]Looking for ", name, " CurrMember is: ", m_currMember);
@@ -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,13 +490,12 @@ namespace System.Runtime.Serialization
// form requested.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public Object GetValue(String name, Type type)
{
if ((object)type == null)
{
- throw new ArgumentNullException("type");
+ throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
@@ -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);
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
index 6b256a6e1f..32c65492e1 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Runtime/Versioning/BinaryCompatibility.cs b/src/mscorlib/src/System/Runtime/Versioning/BinaryCompatibility.cs
deleted file mode 100644
index 99e30b5488..0000000000
--- a/src/mscorlib/src/System/Runtime/Versioning/BinaryCompatibility.cs
+++ /dev/null
@@ -1,485 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-**
-** Purpose: This class is used to determine which binary compatibility
-** behaviors are enabled at runtime. A type for
-** tracking which target Framework an app was built against, or an
-** appdomain-wide setting from the host telling us which .NET
-** Framework version we should emulate.
-**
-**
-===========================================================*/
-using System;
-using System.Diagnostics.Contracts;
-using System.Globalization;
-using System.Runtime.CompilerServices;
-
-namespace System.Runtime.Versioning
-{
- // Provides a simple way to test whether an application was built against specific .NET Framework
- // flavors and versions, with the intent of allowing Framework developers to mimic behavior of older
- // Framework releases. This allows us to make behavioral breaking changes in a binary compatible way,
- // for an application. This works at the per-AppDomain level, not process nor per-Assembly.
- //
- // To opt into newer behavior, applications must specify a TargetFrameworkAttribute on their assembly
- // saying what version they targeted, or a host must set this when creating an AppDomain. Note
- // that command line apps don't have this attribute!
- //
- // To use this class:
- // Developers need to figure out whether they're working on the phone, desktop, or Silverlight, and
- // what version they are introducing a breaking change in. Pick one predicate below, and use that
- // to decide whether to run the new or old behavior. Example:
- //
- // if (BinaryCompatibility.TargetsAtLeast_Phone_V7_1) {
- // // new behavior for phone 7.1 and other releases where we will integrate this change, like .NET Framework 4.5
- // }
- // else {
- // // Legacy behavior
- // }
- //
- // If you are making a breaking change in one specific branch that won't be integrated normally to
- // all other branches (ie, say you're making breaking changes to Windows Phone 8 after .NET Framework v4.5
- // has locked down for release), then add in specific predicates for each relevant platform.
- //
- // Maintainers of this class:
- // Revisit the table once per release, perhaps at the end of the last coding milestone, to verify a
- // default policy saying whether all quirks from a particular flavor & release should be enabled in
- // other releases (ie, should all Windows Phone 8.0 quirks be enabled in .NET Framework v5)?
- //
- // History:
- // Here is the order in which releases were made along with some basic integration information. The idea
- // is to track what set of compatibility features are present in each other.
- // While we cannot guarantee this list is perfectly linear (ie, a feature could be implemented in the last
- // few weeks before shipping and make it into only one of three concommittent releases due to triaging),
- // this is a good high level summary of code flow.
- //
- // Desktop Silverlight Windows Phone
- // .NET Framework 3.0 -> Silverlight 2
- // .NET Framework 3.5
- // Silverlight 3
- // Silverlight 4
- // .NET Framework 4 Phone 8.0
- // .NET Framework 4.5 Phone 8.1
- // .NET Framework 4.5.1 Phone 8.1
- //
- // (Note: Windows Phone 7.0 was built using the .NET Compact Framework, which forked around v1 or v1.1)
- //
- // Compatibility Policy decisions:
- // If we cannot determine that an app was built for a newer .NET Framework (ie, the app has no
- // TargetFrameworkAttribute), then quirks will be enabled to emulate older behavior.
- // As such, your test code should define the TargetFrameworkAttribute (which VS does for you)
- // if you want to see the new behavior!
- [FriendAccessAllowed]
- internal static class BinaryCompatibility
- {
- // Use this for new behavior introduced in the phone branch. It will do the right thing for desktop & SL.
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Phone_V7_1 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Phone_V7_1; } }
-
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Phone_V8_0 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Phone_V8_0; } }
-
- // Use this for new behavior introduced in the Desktop branch. It will do the right thing for Phone & SL.
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Desktop_V4_5 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5; } }
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Desktop_V4_5_1 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5_1; } }
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Desktop_V4_5_2 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5_2; } }
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Desktop_V4_5_3 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5_3; } }
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Desktop_V4_5_4 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V4_5_4; } }
-
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Desktop_V5_0 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Desktop_V5_0; } }
-
- // Use this for new behavior introduced in the Silverlight branch. It will do the right thing for desktop & Phone.
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Silverlight_V4 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Silverlight_V4; } }
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Silverlight_V5 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Silverlight_V5; } }
- [FriendAccessAllowed]
- internal static bool TargetsAtLeast_Silverlight_V6 { [FriendAccessAllowed] get { return s_map.TargetsAtLeast_Silverlight_V6; } }
-
- [FriendAccessAllowed]
- internal static TargetFrameworkId AppWasBuiltForFramework {
- [FriendAccessAllowed]
- get {
- Contract.Ensures(Contract.Result<TargetFrameworkId>() > TargetFrameworkId.NotYetChecked);
-
- if (s_AppWasBuiltForFramework == TargetFrameworkId.NotYetChecked)
- ReadTargetFrameworkId();
-
- return s_AppWasBuiltForFramework;
- }
- }
-
- // Version number is major * 10000 + minor * 100 + build (ie, 4.5.1.0 would be version 40501).
- [FriendAccessAllowed]
- internal static int AppWasBuiltForVersion {
- [FriendAccessAllowed]
- get {
- Contract.Ensures(Contract.Result<int>() > 0 || s_AppWasBuiltForFramework == TargetFrameworkId.Unspecified);
-
- if (s_AppWasBuiltForFramework == TargetFrameworkId.NotYetChecked)
- ReadTargetFrameworkId();
-
- Contract.Assert(s_AppWasBuiltForFramework != TargetFrameworkId.Unrecognized);
-
- return s_AppWasBuiltForVersion;
- }
- }
-
- #region private
- private static TargetFrameworkId s_AppWasBuiltForFramework;
- // Version number is major * 10000 + minor * 100 + build (ie, 4.5.1.0 would be version 40501).
- private static int s_AppWasBuiltForVersion;
-
- readonly static BinaryCompatibilityMap s_map = new BinaryCompatibilityMap();
-
- // For parsing a target Framework moniker, from the FrameworkName class
- private const char c_componentSeparator = ',';
- private const char c_keyValueSeparator = '=';
- private const char c_versionValuePrefix = 'v';
- private const String c_versionKey = "Version";
- private const String c_profileKey = "Profile";
-
- /// <summary>
- /// BinaryCompatibilityMap is basically a bitvector. There is a boolean field for each of the
- /// properties in BinaryCompatibility
- /// </summary>
- private sealed class BinaryCompatibilityMap
- {
- // A bit for each property
- internal bool TargetsAtLeast_Phone_V7_1;
- internal bool TargetsAtLeast_Phone_V8_0;
- internal bool TargetsAtLeast_Phone_V8_1;
- internal bool TargetsAtLeast_Desktop_V4_5;
- internal bool TargetsAtLeast_Desktop_V4_5_1;
- internal bool TargetsAtLeast_Desktop_V4_5_2;
- internal bool TargetsAtLeast_Desktop_V4_5_3;
- internal bool TargetsAtLeast_Desktop_V4_5_4;
- internal bool TargetsAtLeast_Desktop_V5_0;
- internal bool TargetsAtLeast_Silverlight_V4;
- internal bool TargetsAtLeast_Silverlight_V5;
- internal bool TargetsAtLeast_Silverlight_V6;
-
- internal BinaryCompatibilityMap()
- {
- AddQuirksForFramework(AppWasBuiltForFramework, AppWasBuiltForVersion);
- }
-
- // The purpose of this method is to capture information about integrations & behavioral compatibility
- // between our multiple different release vehicles. IE, if a behavior shows up in Silverlight version 5,
- // does it show up in the .NET Framework version 4.5 and Windows Phone 8?
- // Version number is major * 10000 + minor * 100 + build (ie, 4.5.1.0 would be version 40501).
- private void AddQuirksForFramework(TargetFrameworkId builtAgainstFramework, int buildAgainstVersion)
- {
- Contract.Requires(buildAgainstVersion > 0 || builtAgainstFramework == TargetFrameworkId.Unspecified);
-
- switch (builtAgainstFramework)
- {
- case TargetFrameworkId.NetFramework:
- case TargetFrameworkId.NetCore: // Treat Windows 8 tailored apps as normal desktop apps - same product
- if (buildAgainstVersion >= 50000)
- TargetsAtLeast_Desktop_V5_0 = true;
-
- // Potential 4.5 servicing releases
- if (buildAgainstVersion >= 40504)
- TargetsAtLeast_Desktop_V4_5_4 = true;
- if (buildAgainstVersion >= 40503)
- TargetsAtLeast_Desktop_V4_5_3 = true;
- if (buildAgainstVersion >= 40502)
- TargetsAtLeast_Desktop_V4_5_2 = true;
- if (buildAgainstVersion >= 40501)
- TargetsAtLeast_Desktop_V4_5_1 = true;
-
- if (buildAgainstVersion >= 40500)
- {
- TargetsAtLeast_Desktop_V4_5 = true;
- // On XX/XX/XX we integrated all changes from the phone V7_1 into the branch from which contains Desktop V4_5, thus
- // Any application built for V4_5 (or above) should have all the quirks for Phone V7_1 turned on.
- AddQuirksForFramework(TargetFrameworkId.Phone, 70100);
- // All Silverlight 5 behavior should be in the .NET Framework version 4.5
- AddQuirksForFramework(TargetFrameworkId.Silverlight, 50000);
- }
- break;
-
- case TargetFrameworkId.Phone:
- if (buildAgainstVersion >= 80000)
- {
- // This is for Apollo apps. For Apollo apps we don't want to enable any of the 4.5 or 4.5.1 quirks
- TargetsAtLeast_Phone_V8_0 = true;
- //TargetsAtLeast_Desktop_V4_5 = true;
- }
- if (buildAgainstVersion >= 80100)
- {
- // For WindowsPhone 8.1 and SL 8.1 scenarios we want to enable both 4.5 and 4.5.1 quirks.
- TargetsAtLeast_Desktop_V4_5 = true;
- TargetsAtLeast_Desktop_V4_5_1 = true;
- }
-
- if (buildAgainstVersion >= 710)
- TargetsAtLeast_Phone_V7_1 = true;
- break;
-
- case TargetFrameworkId.Silverlight:
- if (buildAgainstVersion >= 40000)
- TargetsAtLeast_Silverlight_V4 = true;
-
- if (buildAgainstVersion >= 50000)
- TargetsAtLeast_Silverlight_V5 = true;
-
- if (buildAgainstVersion >= 60000)
- {
- TargetsAtLeast_Silverlight_V6 = true;
- }
- break;
-
- case TargetFrameworkId.Unspecified:
- break;
-
- case TargetFrameworkId.NotYetChecked:
- case TargetFrameworkId.Unrecognized:
- Contract.Assert(false, "Bad framework kind");
- break;
- default:
- Contract.Assert(false, "Error: we introduced a new Target Framework but did not update our binary compatibility map");
- break;
- }
- }
- }
-
- #region String Parsing
-
- // If this doesn't work, perhaps we could fall back to parsing the metadata version number.
- private static bool ParseTargetFrameworkMonikerIntoEnum(String targetFrameworkMoniker, out TargetFrameworkId targetFramework, out int targetFrameworkVersion)
- {
- Contract.Requires(!String.IsNullOrEmpty(targetFrameworkMoniker));
-
- targetFramework = TargetFrameworkId.NotYetChecked;
- targetFrameworkVersion = 0;
-
- String identifier = null;
- String profile = null;
- ParseFrameworkName(targetFrameworkMoniker, out identifier, out targetFrameworkVersion, out profile);
-
- switch (identifier)
- {
- case ".NETFramework":
- targetFramework = TargetFrameworkId.NetFramework;
- break;
-
- case ".NETPortable":
- targetFramework = TargetFrameworkId.Portable;
- break;
-
- case ".NETCore":
- targetFramework = TargetFrameworkId.NetCore;
- break;
-
- case "WindowsPhone":
- if (targetFrameworkVersion >= 80100)
- {
- // A TFM of the form WindowsPhone,Version=v8.1 corresponds to SL 8.1 scenario
- // and gets the same quirks as WindowsPhoneApp\v8.1 store apps.
- targetFramework = TargetFrameworkId.Phone;
- }
- else
- {
- // There is no TFM for Apollo or below and hence we assign the targetFramework to Unspecified.
- targetFramework = TargetFrameworkId.Unspecified;
- }
- break;
-
- case "WindowsPhoneApp":
- targetFramework = TargetFrameworkId.Phone;
- break;
-
- case "Silverlight":
- targetFramework = TargetFrameworkId.Silverlight;
- // Windows Phone 7 is Silverlight,Version=v4.0,Profile=WindowsPhone
- // Windows Phone 7.1 is Silverlight,Version=v4.0,Profile=WindowsPhone71
- if (!String.IsNullOrEmpty(profile))
- {
- if (profile == "WindowsPhone")
- {
- targetFramework = TargetFrameworkId.Phone;
- targetFrameworkVersion = 70000;
- }
- else if (profile == "WindowsPhone71")
- {
- targetFramework = TargetFrameworkId.Phone;
- targetFrameworkVersion = 70100;
- }
- else if (profile == "WindowsPhone8")
- {
- targetFramework = TargetFrameworkId.Phone;
- targetFrameworkVersion = 80000;
- }
- else if (profile.StartsWith("WindowsPhone", StringComparison.Ordinal))
- {
- Contract.Assert(false, "This is a phone app, but we can't tell what version this is!");
- targetFramework = TargetFrameworkId.Unrecognized;
- targetFrameworkVersion = 70100;
- }
- else
- {
- Contract.Assert(false, String.Format(CultureInfo.InvariantCulture, "Unrecognized Silverlight profile \"{0}\". What is this, an XBox app?", profile));
- targetFramework = TargetFrameworkId.Unrecognized;
- }
- }
- break;
-
- default:
- Contract.Assert(false, String.Format(CultureInfo.InvariantCulture, "Unrecognized Target Framework Moniker in our Binary Compatibility class. Framework name: \"{0}\"", targetFrameworkMoniker));
- targetFramework = TargetFrameworkId.Unrecognized;
- break;
- }
-
- return true;
- }
-
- // This code was a constructor copied from the FrameworkName class, which is located in System.dll.
- // Parses strings in the following format: "<identifier>, Version=[v|V]<version>, Profile=<profile>"
- // - The identifier and version is required, profile is optional
- // - Only three components are allowed.
- // - The version string must be in the System.Version format; an optional "v" or "V" prefix is allowed
- private static void ParseFrameworkName(String frameworkName, out String identifier, out int version, out String profile)
- {
- if (frameworkName == null)
- {
- throw new ArgumentNullException("frameworkName");
- }
- if (frameworkName.Length == 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_StringZeroLength"), "frameworkName");
- }
- Contract.EndContractBlock();
-
- String[] components = frameworkName.Split(c_componentSeparator);
- version = 0;
-
- // Identifer and Version are required, Profile is optional.
- if (components.Length < 2 || components.Length > 3)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_FrameworkNameTooShort"), "frameworkName");
- }
-
- //
- // 1) Parse the "Identifier", which must come first. Trim any whitespace
- //
- identifier = components[0].Trim();
-
- if (identifier.Length == 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_FrameworkNameInvalid"), "frameworkName");
- }
-
- bool versionFound = false;
- profile = null;
-
- //
- // The required "Version" and optional "Profile" component can be in any order
- //
- for (int i = 1; i < components.Length; i++)
- {
- // Get the key/value pair separated by '='
- string[] keyValuePair = components[i].Split(c_keyValueSeparator);
-
- if (keyValuePair.Length != 2)
- {
- throw new ArgumentException(Environment.GetResourceString("SR.Argument_FrameworkNameInvalid"), "frameworkName");
- }
-
- // Get the key and value, trimming any whitespace
- string key = keyValuePair[0].Trim();
- string value = keyValuePair[1].Trim();
-
- //
- // 2) Parse the required "Version" key value
- //
- if (key.Equals(c_versionKey, StringComparison.OrdinalIgnoreCase))
- {
- versionFound = true;
-
- // Allow the version to include a 'v' or 'V' prefix...
- if (value.Length > 0 && (value[0] == c_versionValuePrefix || value[0] == 'V'))
- {
- value = value.Substring(1);
- }
- Version realVersion = new Version(value);
- // The version class will represent some unset values as -1 internally (instead of 0).
- version = realVersion.Major * 10000;
- if (realVersion.Minor > 0)
- version += realVersion.Minor * 100;
- if (realVersion.Build > 0)
- version += realVersion.Build;
- }
- //
- // 3) Parse the optional "Profile" key value
- //
- else if (key.Equals(c_profileKey, StringComparison.OrdinalIgnoreCase))
- {
- if (!String.IsNullOrEmpty(value))
- {
- profile = value;
- }
- }
- else
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_FrameworkNameInvalid"), "frameworkName");
- }
- }
-
- if (!versionFound)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_FrameworkNameMissingVersion"), "frameworkName");
- }
- }
-
- [System.Security.SecuritySafeCritical]
- private static void ReadTargetFrameworkId()
- {
- String targetFrameworkName = AppDomain.CurrentDomain.GetTargetFrameworkName();
-
- var overrideValue = System.Runtime.Versioning.CompatibilitySwitch.GetValueInternal("TargetFrameworkMoniker");
- if (!string.IsNullOrEmpty(overrideValue))
- {
- targetFrameworkName = overrideValue;
- }
-
- // Write to a local then to _targetFramework, after writing the version number.
- TargetFrameworkId fxId;
- int fxVersion = 0;
- if (targetFrameworkName == null)
- {
-#if FEATURE_CORECLR
- // if we don't have a value for targetFrameworkName we need to figure out if we should give the newest behavior or not.
- if (CompatibilitySwitches.UseLatestBehaviorWhenTFMNotSpecified)
- {
- fxId = TargetFrameworkId.NetFramework;
- fxVersion = 50000; // We are going to default to the latest value for version that we have in our code.
- }
- else
-#endif
- fxId = TargetFrameworkId.Unspecified;
- }
- else if (!ParseTargetFrameworkMonikerIntoEnum(targetFrameworkName, out fxId, out fxVersion))
- fxId = TargetFrameworkId.Unrecognized;
-
- s_AppWasBuiltForFramework = fxId;
- s_AppWasBuiltForVersion = fxVersion;
- }
- #endregion String Parsing
-
- #endregion private
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs b/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs
index b06c42437c..6bf8f8cf45 100644
--- a/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs
+++ b/src/mscorlib/src/System/Runtime/Versioning/CompatibilitySwitch.cs
@@ -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();
diff --git a/src/mscorlib/src/System/Runtime/Versioning/ComponentGuaranteesAttribute.cs b/src/mscorlib/src/System/Runtime/Versioning/ComponentGuaranteesAttribute.cs
deleted file mode 100644
index 0f906d518a..0000000000
--- a/src/mscorlib/src/System/Runtime/Versioning/ComponentGuaranteesAttribute.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-** Purpose: Tracking whether a component signs up for a
-** a strong contract spanning multiple versions.
-**
-===========================================================*/
-using System;
-
-namespace System.Runtime.Versioning {
-
- [Flags]
- [Serializable]
- public enum ComponentGuaranteesOptions
- {
- None = 0,
- Exchange = 0x1,
- Stable = 0x2,
- SideBySide = 0x4,
- }
-
- [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class |
- AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Delegate |
- AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property |
- AttributeTargets.Constructor | AttributeTargets.Event,
- AllowMultiple = false, Inherited = false)]
- public sealed class ComponentGuaranteesAttribute : Attribute {
- private ComponentGuaranteesOptions _guarantees;
-
- public ComponentGuaranteesAttribute(ComponentGuaranteesOptions guarantees)
- {
- _guarantees = guarantees;
- }
-
- public ComponentGuaranteesOptions Guarantees {
- get { return _guarantees; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Versioning/ResourceAttributes.cs b/src/mscorlib/src/System/Runtime/Versioning/ResourceAttributes.cs
deleted file mode 100644
index 78a9ddbd07..0000000000
--- a/src/mscorlib/src/System/Runtime/Versioning/ResourceAttributes.cs
+++ /dev/null
@@ -1,237 +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: Resource annotation rules.
-**
-===========================================================*/
-using System;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.CompilerServices;
-using System.Text;
-using Microsoft.Win32;
-using System.Diagnostics.Contracts;
-
-namespace System.Runtime.Versioning
-{
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
- [Conditional("RESOURCE_ANNOTATION_WORK")]
- public sealed class ResourceConsumptionAttribute : Attribute
- {
- private ResourceScope _consumptionScope;
- private ResourceScope _resourceScope;
-
- public ResourceConsumptionAttribute(ResourceScope resourceScope)
- {
- _resourceScope = resourceScope;
- _consumptionScope = _resourceScope;
- }
-
- public ResourceConsumptionAttribute(ResourceScope resourceScope, ResourceScope consumptionScope)
- {
- _resourceScope = resourceScope;
- _consumptionScope = consumptionScope;
- }
-
- public ResourceScope ResourceScope {
- get { return _resourceScope; }
- }
-
- public ResourceScope ConsumptionScope {
- get { return _consumptionScope; }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
- [Conditional("RESOURCE_ANNOTATION_WORK")]
- public sealed class ResourceExposureAttribute : Attribute
- {
- private ResourceScope _resourceExposureLevel;
-
- public ResourceExposureAttribute(ResourceScope exposureLevel)
- {
- _resourceExposureLevel = exposureLevel;
- }
-
- public ResourceScope ResourceExposureLevel {
- get { return _resourceExposureLevel; }
- }
- }
-
-
- // Default visibility is Public, which isn't specified in this enum.
- // Public == the lack of Private or Assembly
- // Does this actually work? Need to investigate that.
- [Flags]
- public enum ResourceScope
- {
- None = 0,
- // Resource type
- Machine = 0x1,
- Process = 0x2,
- AppDomain = 0x4,
- Library = 0x8,
- // Visibility
- Private = 0x10, // Private to this one class.
- Assembly = 0x20, // Assembly-level, like C#'s "internal"
- }
-
-
- [Flags]
- internal enum SxSRequirements
- {
- None = 0,
- AppDomainID = 0x1,
- ProcessID = 0x2,
- CLRInstanceID = 0x4, // for multiple CLR's within the process
- AssemblyName = 0x8,
- TypeName = 0x10
- }
-
- public static class VersioningHelper
- {
- // These depend on the exact values given to members of the ResourceScope enum.
- private const ResourceScope ResTypeMask = ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library;
- private const ResourceScope VisibilityMask = ResourceScope.Private | ResourceScope.Assembly;
-
- [System.Security.SecuritySafeCritical]
- [MethodImpl(MethodImplOptions.InternalCall)]
- private static extern int GetRuntimeId();
-
- public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to)
- {
- return MakeVersionSafeName(name, from, to, null);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to, Type type)
- {
- ResourceScope fromResType = from & ResTypeMask;
- ResourceScope toResType = to & ResTypeMask;
- if (fromResType > toResType)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResourceScopeWrongDirection", fromResType, toResType), "from");
-
- SxSRequirements requires = GetRequirements(to, from);
-
- if ((requires & (SxSRequirements.AssemblyName | SxSRequirements.TypeName)) != 0 && type == null)
- throw new ArgumentNullException("type", Environment.GetResourceString("ArgumentNull_TypeRequiredByResourceScope"));
-
- // Add in process ID, CLR base address, and appdomain ID's. Also, use a character identifier
- // to ensure that these can never accidentally overlap (ie, you create enough appdomains and your
- // appdomain ID might equal your process ID).
- StringBuilder safeName = new StringBuilder(name);
- char separator = '_';
- if ((requires & SxSRequirements.ProcessID) != 0) {
- safeName.Append(separator);
- safeName.Append('p');
- safeName.Append(Win32Native.GetCurrentProcessId());
- }
- if ((requires & SxSRequirements.CLRInstanceID) != 0) {
- String clrID = GetCLRInstanceString();
- safeName.Append(separator);
- safeName.Append('r');
- safeName.Append(clrID);
- }
- if ((requires & SxSRequirements.AppDomainID) != 0) {
- safeName.Append(separator);
- safeName.Append("ad");
- safeName.Append(AppDomain.CurrentDomain.Id);
- }
- if ((requires & SxSRequirements.TypeName) != 0) {
- safeName.Append(separator);
- safeName.Append(type.Name);
- }
- if ((requires & SxSRequirements.AssemblyName) != 0) {
- safeName.Append(separator);
- safeName.Append(type.Assembly.FullName);
- }
- return safeName.ToString();
- }
-
- private static String GetCLRInstanceString()
- {
- int id = GetRuntimeId();
- return id.ToString(CultureInfo.InvariantCulture);
- }
-
- private static SxSRequirements GetRequirements(ResourceScope consumeAsScope, ResourceScope calleeScope)
- {
- SxSRequirements requires = SxSRequirements.None;
-
- switch(calleeScope & ResTypeMask) {
- case ResourceScope.Machine:
- switch(consumeAsScope & ResTypeMask) {
- case ResourceScope.Machine:
- // No work
- break;
-
- case ResourceScope.Process:
- requires |= SxSRequirements.ProcessID;
- break;
-
- case ResourceScope.AppDomain:
- requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID | SxSRequirements.ProcessID;
- break;
-
- default:
- throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", consumeAsScope), "consumeAsScope");
- }
- break;
-
- case ResourceScope.Process:
- if ((consumeAsScope & ResourceScope.AppDomain) != 0)
- requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID;
- break;
-
- case ResourceScope.AppDomain:
- // No work
- break;
-
- default:
- throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", calleeScope), "calleeScope");
- }
-
- switch(calleeScope & VisibilityMask) {
- case ResourceScope.None: // Public - implied
- switch(consumeAsScope & VisibilityMask) {
- case ResourceScope.None: // Public - implied
- // No work
- break;
-
- case ResourceScope.Assembly:
- requires |= SxSRequirements.AssemblyName;
- break;
-
- case ResourceScope.Private:
- requires |= SxSRequirements.TypeName | SxSRequirements.AssemblyName;
- break;
-
- default:
- throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", consumeAsScope), "consumeAsScope");
- }
- break;
-
- case ResourceScope.Assembly:
- if ((consumeAsScope & ResourceScope.Private) != 0)
- requires |= SxSRequirements.TypeName;
- break;
-
- case ResourceScope.Private:
- // No work
- break;
-
- default:
- throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", calleeScope), "calleeScope");
- }
-
- if (consumeAsScope == calleeScope) {
- Contract.Assert(requires == SxSRequirements.None, "Computed a strange set of required resource scoping. It's probably wrong.");
- }
-
- return requires;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs b/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs
index dbf98c08d8..600ba3f154 100644
--- a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs
@@ -26,7 +26,7 @@ namespace System.Runtime.Versioning {
public TargetFrameworkAttribute(String frameworkName)
{
if (frameworkName == null)
- throw new ArgumentNullException("frameworkName");
+ throw new ArgumentNullException(nameof(frameworkName));
Contract.EndContractBlock();
_frameworkName = frameworkName;
}
diff --git a/src/mscorlib/src/System/RuntimeHandles.cs b/src/mscorlib/src/System/RuntimeHandles.cs
index 24ca45e309..127da1e0da 100644
--- a/src/mscorlib/src/System/RuntimeHandles.cs
+++ b/src/mscorlib/src/System/RuntimeHandles.cs
@@ -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,16 +508,14 @@ 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)
- throw new ArgumentException("name");
+ throw new ArgumentException(null, nameof(name));
Contract.EndContractBlock();
RuntimeType type = null;
@@ -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,21 +684,18 @@ 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)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
RuntimeType m = (RuntimeType)info.GetValue("TypeObj", typeof(RuntimeType));
@@ -803,11 +706,10 @@ namespace System
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
- [System.Security.SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if(info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_type == 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,18 +835,16 @@ 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)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MethodBase m =(MethodBase)info.GetValue("MethodObj", typeof(MethodBase));
@@ -970,11 +855,10 @@ namespace System
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
- [System.Security.SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_value == 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,81 +1362,66 @@ 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)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
FieldInfo f =(RuntimeFieldInfo) info.GetValue("FieldObj", typeof(RuntimeFieldInfo));
@@ -1660,11 +1435,10 @@ namespace System
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
- [System.Security.SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_ptr == 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);
//
diff --git a/src/mscorlib/src/System/SByte.cs b/src/mscorlib/src/System/SByte.cs
index a9ec9cf298..da6ac5c88f 100644
--- a/src/mscorlib/src/System/SByte.cs
+++ b/src/mscorlib/src/System/SByte.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Security/AccessControl/Enums.cs b/src/mscorlib/src/System/Security/AccessControl/Enums.cs
index c52176a29b..20f5c5f91a 100644
--- a/src/mscorlib/src/System/Security/AccessControl/Enums.cs
+++ b/src/mscorlib/src/System/Security/AccessControl/Enums.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Security/Attributes.cs b/src/mscorlib/src/System/Security/Attributes.cs
index d2229227a5..e4ebc53053 100644
--- a/src/mscorlib/src/System/Security/Attributes.cs
+++ b/src/mscorlib/src/System/Security/Attributes.cs
@@ -57,14 +57,12 @@ namespace System.Security
NotVisibleByDefault = 1
}
-#if !FEATURE_CORECLR
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
public enum SecurityCriticalScope
{
Explicit = 0,
Everything = 0x1
}
-#endif // FEATURE_CORECLR
// SecurityCriticalAttribute
// Indicates that the decorated code or assembly performs security critical operations (e.g. Assert, "unsafe", LinkDemand, etc.)
@@ -84,12 +82,10 @@ namespace System.Security
{
#pragma warning disable 618 // We still use SecurityCriticalScope for v2 compat
-#if !FEATURE_CORECLR
- private SecurityCriticalScope _val;
-#endif // FEATURE_CORECLR
+ private SecurityCriticalScope _val;
+
public SecurityCriticalAttribute () {}
-#if !FEATURE_CORECLR
public SecurityCriticalAttribute(SecurityCriticalScope scope)
{
_val = scope;
@@ -101,7 +97,6 @@ namespace System.Security
return _val;
}
}
-#endif // FEATURE_CORECLR
#pragma warning restore 618
}
@@ -167,7 +162,6 @@ namespace System.Security
public SecurityTransparentAttribute () {}
}
-#if !FEATURE_CORECLR
public enum SecurityRuleSet : byte
{
None = 0,
@@ -205,5 +199,4 @@ namespace System.Security
get { return m_ruleSet; }
}
}
-#endif // !FEATURE_CORECLR
}
diff --git a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs b/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs
index e29dec3b06..48539574af 100644
--- a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs
+++ b/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Security/CodeAccessPermission.cs b/src/mscorlib/src/System/Security/CodeAccessPermission.cs
index 61334c22bd..70504d902e 100644
--- a/src/mscorlib/src/System/Security/CodeAccessPermission.cs
+++ b/src/mscorlib/src/System/Security/CodeAccessPermission.cs
@@ -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( "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 );
}
}
diff --git a/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs b/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs
index 2a1cf9a0ea..d86897c02e 100644
--- a/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs
+++ b/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs
@@ -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();
diff --git a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs b/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs
index 8f25bda617..0ef5afd282 100644
--- a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs
+++ b/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Security/HostProtectionException.cs b/src/mscorlib/src/System/Security/HostProtectionException.cs
index 83f005fe9b..b08fccd1b3 100644
--- a/src/mscorlib/src/System/Security/HostProtectionException.cs
+++ b/src/mscorlib/src/System/Security/HostProtectionException.cs
@@ -53,7 +53,7 @@ namespace System.Security
protected HostProtectionException(SerializationInfo info, StreamingContext context) : base(info, context)
{
if (info==null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
m_protected = (HostProtectionResource)info.GetValue(ProtectedResourcesName, typeof(HostProtectionResource));
@@ -120,11 +120,10 @@ namespace System.Security
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
base.GetObjectData( info, context );
diff --git a/src/mscorlib/src/System/Security/HostSecurityManager.cs b/src/mscorlib/src/System/Security/HostSecurityManager.cs
index 46d5552478..53137983d3 100644
--- a/src/mscorlib/src/System/Security/HostSecurityManager.cs
+++ b/src/mscorlib/src/System/Security/HostSecurityManager.cs
@@ -9,13 +9,9 @@
// participate in the security decisions in the AppDomain.
//
-namespace System.Security {
+namespace System.Security
+{
using System.Collections;
-#if FEATURE_CLICKONCE
- using System.Deployment.Internal.Isolation;
- using System.Deployment.Internal.Isolation.Manifest;
- using System.Runtime.Hosting;
-#endif
using System.Reflection;
using System.Security;
using System.Security.Permissions;
@@ -24,7 +20,7 @@ namespace System.Security {
using System.Diagnostics.Contracts;
-[Serializable]
+ [Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum HostSecurityManagerOptions {
@@ -38,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 () {}
@@ -56,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;
@@ -80,109 +58,6 @@ namespace System.Security {
return inputEvidence;
}
-#if FEATURE_CLICKONCE
- [System.Security.SecurityCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Assert, Unrestricted=true)]
- public virtual ApplicationTrust DetermineApplicationTrust(Evidence applicationEvidence, Evidence activatorEvidence, TrustManagerContext context)
- {
- if (applicationEvidence == null)
- throw new ArgumentNullException("applicationEvidence");
- Contract.EndContractBlock();
-
- // This method looks for a trust decision for the ActivationContext in three locations, in order
- // of preference:
- //
- // 1. Supplied by the host in the AppDomainSetup. If the host supplied a decision this way, it
- // will be in the applicationEvidence.
- // 2. Reuse the ApplicationTrust from the current AppDomain
- // 3. Ask the TrustManager for a trust decision
-
- // get the activation context from the application evidence.
- // The default HostSecurityManager does not examine the activatorEvidence
- // but other security managers could use it to figure out the
- // evidence of the domain attempting to activate the application.
-
- ActivationArguments activationArgs = applicationEvidence.GetHostEvidence<ActivationArguments>();
- if (activationArgs == null)
- throw new ArgumentException(Environment.GetResourceString("Policy_MissingActivationContextInAppEvidence"));
-
- ActivationContext actCtx = activationArgs.ActivationContext;
- if (actCtx == null)
- throw new ArgumentException(Environment.GetResourceString("Policy_MissingActivationContextInAppEvidence"));
-
- // Make sure that any ApplicationTrust we find applies to the ActivationContext we're
- // creating the new AppDomain for.
- ApplicationTrust appTrust = applicationEvidence.GetHostEvidence<ApplicationTrust>();
- if (appTrust != null &&
- !CmsUtils.CompareIdentities(appTrust.ApplicationIdentity, activationArgs.ApplicationIdentity, ApplicationVersionMatch.MatchExactVersion))
- {
- appTrust = null;
- }
-
- // If there was not a trust decision supplied in the Evidence, we can reuse the existing trust
- // decision from this domain if its identity matches the ActivationContext of the new domain.
- // Otherwise consult the TrustManager for a trust decision
- if (appTrust == null)
- {
- if (AppDomain.CurrentDomain.ApplicationTrust != null &&
- CmsUtils.CompareIdentities(AppDomain.CurrentDomain.ApplicationTrust.ApplicationIdentity, activationArgs.ApplicationIdentity, ApplicationVersionMatch.MatchExactVersion))
- {
- appTrust = AppDomain.CurrentDomain.ApplicationTrust;
- }
- else
- {
- appTrust = ApplicationSecurityManager.DetermineApplicationTrustInternal(actCtx, context);
- }
- }
-
- // If the trust decision allows the application to run, then it should also have a permission set
- // which is at least the permission set the application requested.
- ApplicationSecurityInfo appRequest = new ApplicationSecurityInfo(actCtx);
- if (appTrust != null &&
- appTrust.IsApplicationTrustedToRun &&
- !appRequest.DefaultRequestSet.IsSubsetOf(appTrust.DefaultGrantSet.PermissionSet))
- {
- throw new InvalidOperationException(Environment.GetResourceString("Policy_AppTrustMustGrantAppRequest"));
- }
-
- return appTrust;
- }
-#endif // FEATURE_CLICKONCE
-
-#if FEATURE_CAS_POLICY
- // Query the CLR to see what it would have granted a specific set of evidence
- public virtual PermissionSet ResolvePolicy(Evidence evidence)
- {
- if (evidence == null)
- throw new ArgumentNullException("evidence");
- Contract.EndContractBlock();
-
- //
- // If the evidence is from the GAC then the result is full trust.
- // In a homogenous domain, then the application trust object provides the grant set.
- // When CAS policy is disabled, the result is full trust.
- // Otherwise, the result comes from evaluating CAS policy.
- //
-
- if (evidence.GetHostEvidence<GacInstalled>() != null)
- {
- return new PermissionSet(PermissionState.Unrestricted);
- }
- else if (AppDomain.CurrentDomain.IsHomogenous)
- {
- return AppDomain.CurrentDomain.GetHomogenousGrantSet(evidence);
- }
- else if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- return new PermissionSet(PermissionState.Unrestricted);
- }
- else
- {
- return SecurityManager.PolicyManager.CodeGroupResolve(evidence, false);
- }
- }
-#endif
-
/// <summary>
/// Determine what types of evidence the host might be able to supply for the AppDomain if requested
/// </summary>
diff --git a/src/mscorlib/src/System/Security/IEvidenceFactory.cs b/src/mscorlib/src/System/Security/IEvidenceFactory.cs
index 93f82a6420..592ab533be 100644
--- a/src/mscorlib/src/System/Security/IEvidenceFactory.cs
+++ b/src/mscorlib/src/System/Security/IEvidenceFactory.cs
@@ -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
}
-
}
diff --git a/src/mscorlib/src/System/Security/ISecurityEncodable.cs b/src/mscorlib/src/System/Security/ISecurityEncodable.cs
index 9915da3696..689b3e4b5f 100644
--- a/src/mscorlib/src/System/Security/ISecurityEncodable.cs
+++ b/src/mscorlib/src/System/Security/ISecurityEncodable.cs
@@ -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
}
-
}
-
-
diff --git a/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs b/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs
index b1c8d1654f..567e41e891 100644
--- a/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs
+++ b/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs
@@ -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
}
-
}
diff --git a/src/mscorlib/src/System/Security/NamedPermissionSet.cs b/src/mscorlib/src/System/Security/NamedPermissionSet.cs
index fba76749a1..1bc166fde8 100644
--- a/src/mscorlib/src/System/Security/NamedPermissionSet.cs
+++ b/src/mscorlib/src/System/Security/NamedPermissionSet.cs
@@ -7,212 +7,19 @@
// 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( "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
}
}
diff --git a/src/mscorlib/src/System/Security/PermissionListSet.cs b/src/mscorlib/src/System/Security/PermissionListSet.cs
index 7eb13a72cf..093542ad4e 100644
--- a/src/mscorlib/src/System/Security/PermissionListSet.cs
+++ b/src/mscorlib/src/System/Security/PermissionListSet.cs
@@ -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))
diff --git a/src/mscorlib/src/System/Security/PermissionSet.cs b/src/mscorlib/src/System/Security/PermissionSet.cs
index e36f0752ad..11ca02a81e 100644
--- a/src/mscorlib/src/System/Security/PermissionSet.cs
+++ b/src/mscorlib/src/System/Security/PermissionSet.cs
@@ -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
}
}
}
@@ -253,7 +185,7 @@ namespace System.Security {
public virtual void CopyTo(Array array, int index)
{
if (array == null)
- throw new ArgumentNullException( "array" );
+ throw new ArgumentNullException( nameof(array) );
Contract.EndContractBlock();
PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this);
@@ -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("et");
-
- if (!et.Tag.Equals(s_str_PermissionSet))
- throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), "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("doc");
- Contract.EndContractBlock();
-
- if (!doc.GetTagForElement( position ).Equals(s_str_PermissionSet))
- throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), "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);
diff --git a/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs b/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs
index 55b56cb570..7b234e9cf4 100644
--- a/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs
+++ b/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs
@@ -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;
}
diff --git a/src/mscorlib/src/System/Security/PermissionSetTriple.cs b/src/mscorlib/src/System/Security/PermissionSetTriple.cs
index f1527ac4b1..56eb22996e 100644
--- a/src/mscorlib/src/System/Security/PermissionSetTriple.cs
+++ b/src/mscorlib/src/System/Security/PermissionSetTriple.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Security/PermissionToken.cs b/src/mscorlib/src/System/Security/PermissionToken.cs
index e78c0f1a93..5c6a322c1c 100644
--- a/src/mscorlib/src/System/Security/PermissionToken.cs
+++ b/src/mscorlib/src/System/Security/PermissionToken.cs
@@ -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;
@@ -64,7 +65,7 @@ namespace System.Security {
// The data structure consuming this will be responsible for dealing with null objects as keys.
public int GetHashCode(Object obj)
{
- if (obj == null) throw new ArgumentNullException("obj");
+ if (obj == null) throw new ArgumentNullException(nameof(obj));
Contract.EndContractBlock();
String str = obj 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
}
}
diff --git a/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs b/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs
index 8208ed3fb0..567fe513c0 100644
--- a/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs
@@ -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()
diff --git a/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs b/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs
index 6d6c221cc9..98a7d54c68 100644
--- a/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs
@@ -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 ) {
diff --git a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs b/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs
index b4d4141f82..34b9f1ef80 100644
--- a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs
@@ -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
{
@@ -558,7 +487,7 @@ namespace System.Security.Permissions {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
if (!onlyCheckExtras)
- Path.CheckInvalidPathChars(str[i]);
+ PathInternal.CheckInvalidPathChars(str[i]);
}
#else
// There are no "extras" on Unix
@@ -567,7 +496,7 @@ namespace System.Security.Permissions {
for (int i = 0; i < str.Length; ++i)
{
- Path.CheckInvalidPathChars(str[i]);
+ PathInternal.CheckInvalidPathChars(str[i]);
}
#endif
}
@@ -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())
- {
- new FileIOPermission(access, fullPathList, checkForDuplicates, needFullPath).Demand();
- }
- else
-#endif
+ foreach (string fullPath in fullPathList)
{
- 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>
@@ -1088,18 +842,10 @@ namespace System.Security.Permissions {
// Callers should have already made checks for invalid path format via normalization. This method will only make the
// additional checks needed to throw the same exceptions that would normally throw when using FileIOPermission.
// These checks are done via CheckIllegalCharacters() and StringExpressionSet in AddPathList() above.
- //
- // We have to check the beginning as some paths may be passed in as path + @"\.", which will be normalized away.
- BCLDebug.Assert(
- fullPath.StartsWith(Path.NormalizePath(fullPath, fullCheck: false), StringComparison.OrdinalIgnoreCase),
- string.Format("path isn't normalized: {0}", fullPath));
+#if !PLATFORM_UNIX
// Checking for colon / invalid characters on device paths blocks legitimate access to objects such as named pipes.
- if (
-#if FEATURE_PATHCOMPAT
- AppContextSwitches.UseLegacyPathHandling ||
-#endif
- !PathInternal.IsDevice(fullPath))
+ if (!PathInternal.IsDevice(fullPath))
{
// GetFullPath already checks normal invalid path characters. We need to just check additional (wildcard) characters here.
// (By calling the standard helper we can allow extended paths \\?\ through when the support is enabled.)
@@ -1113,6 +859,7 @@ namespace System.Security.Permissions {
throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported"));
}
}
+#endif // !PLATFORM_UNIX
}
}
@@ -1149,7 +896,6 @@ namespace System.Security.Permissions {
m_pathDiscovery = pathDiscovery;
}
- [System.Security.SecurityCritical] // auto-generated
public FileIOAccess( String value )
{
if (value == null)
@@ -1204,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;
@@ -1255,7 +1000,6 @@ namespace System.Security.Permissions {
return new FileIOAccess( this );
}
- [System.Security.SecuritySafeCritical] // auto-generated
public FileIOAccess Union( FileIOAccess operand )
{
if (operand == null)
@@ -1263,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)
{
@@ -1273,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)
@@ -1281,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)
{
@@ -1343,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)
@@ -1356,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 )))
{
@@ -1400,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
@@ -1429,7 +1170,6 @@ namespace System.Security.Permissions {
}
}
- [SecuritySafeCritical]
public String[] ToStringArray()
{
// SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
@@ -1437,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)
diff --git a/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs
index 5c209afb9d..f93f26daa9 100644
--- a/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs
@@ -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()
{
diff --git a/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs b/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs
index 85be61a00d..c4facbb67e 100644
--- a/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs
@@ -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
diff --git a/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs b/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs
index 1e11b4aa7f..42bc648c72 100644
--- a/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs b/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs
index 308adbdab3..9f09a37098 100644
--- a/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs b/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs
index f14fb0d1b3..b6ac8ece3c 100644
--- a/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs
+++ b/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs
@@ -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 );
}
diff --git a/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs b/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs
index 2bc3c08ff9..1c9dd7696c 100644
--- a/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs
@@ -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()
diff --git a/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs b/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs
index bf801d625b..c0c51e94a2 100644
--- a/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs
@@ -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()
diff --git a/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs b/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs
index b359cc530d..cf3002989d 100644
--- a/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs
@@ -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()
diff --git a/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs
index 6050b580df..ff38d515a1 100644
--- a/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs
@@ -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()
{
diff --git a/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs
index 5f5de0ef80..f09d84de34 100644
--- a/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs
@@ -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;
@@ -135,7 +132,7 @@ namespace System.Security.Permissions
public StrongNameIdentityPermission( StrongNamePublicKeyBlob blob, String name, Version version )
{
if (blob == null)
- throw new ArgumentNullException( "blob" );
+ throw new ArgumentNullException( nameof(blob) );
if (name != null && name.Equals( "" ))
throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyStrongName" ) );
Contract.EndContractBlock();
@@ -156,7 +153,7 @@ namespace System.Security.Permissions
set
{
if (value == null)
- throw new ArgumentNullException( "PublicKey" );
+ throw new ArgumentNullException( nameof(PublicKey) );
Contract.EndContractBlock();
m_unrestricted = false;
if(m_strongNames != null && m_strongNames.Length == 1)
@@ -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()
{
diff --git a/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs b/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs
index e0aacaf80c..823eaba938 100644
--- a/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs
+++ b/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs
@@ -20,7 +20,7 @@ namespace System.Security.Permissions
public StrongNamePublicKeyBlob( byte[] publicKey )
{
if (publicKey == null)
- throw new ArgumentNullException( "PublicKey" );
+ throw new ArgumentNullException( nameof(PublicKey) );
Contract.EndContractBlock();
this.PublicKey = new byte[publicKey.Length];
diff --git a/src/mscorlib/src/System/Security/Permissions/UIPermission.cs b/src/mscorlib/src/System/Security/Permissions/UIPermission.cs
index bb122b734c..4abe801e41 100644
--- a/src/mscorlib/src/System/Security/Permissions/UIPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/UIPermission.cs
@@ -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()
diff --git a/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs
index e62449cf3e..0883bf8979 100644
--- a/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs
@@ -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;
//------------------------------------------------------
//
@@ -110,7 +57,7 @@ namespace System.Security.Permissions
public UrlIdentityPermission( String site )
{
if (site == null)
- throw new ArgumentNullException( "site" );
+ throw new ArgumentNullException( nameof(site) );
Contract.EndContractBlock();
Url = site;
}
@@ -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()
{
diff --git a/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs
index 803bd34cf1..9023c7eece 100644
--- a/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs
@@ -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()
{
diff --git a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs b/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs
index 9691c03da3..d4f1c273c6 100644
--- a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs
+++ b/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs
@@ -11,6 +11,7 @@ namespace System.Security.Permissions {
#endif
using System.Security.Util;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
@@ -88,7 +89,7 @@ namespace System.Security.Permissions {
m_keyStore = "*";
} else {
if (value != "User" && value != "Machine" && value != "*")
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKeyStore", value), "value");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKeyStore", value), nameof(value));
m_keyStore = value;
}
}
@@ -232,7 +233,7 @@ namespace System.Security.Permissions {
if (index < 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumNotStarted"));
if (index >= Count)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return (KeyContainerPermissionAccessEntry)m_list[index];
@@ -247,7 +248,7 @@ namespace System.Security.Permissions {
public int Add (KeyContainerPermissionAccessEntry accessEntry) {
if (accessEntry == null)
- throw new ArgumentNullException("accessEntry");
+ throw new ArgumentNullException(nameof(accessEntry));
Contract.EndContractBlock();
int index = m_list.IndexOf(accessEntry);
@@ -275,7 +276,7 @@ namespace System.Security.Permissions {
public void Remove (KeyContainerPermissionAccessEntry accessEntry) {
if (accessEntry == null)
- throw new ArgumentNullException("accessEntry");
+ throw new ArgumentNullException(nameof(accessEntry));
Contract.EndContractBlock();
m_list.Remove(accessEntry);
}
@@ -292,11 +293,11 @@ namespace System.Security.Permissions {
/// <internalonly/>
void ICollection.CopyTo (Array array, int index) {
if (array == null)
- throw new ArgumentNullException("array");
+ throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0 || index >= array.Length)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (index + this.Count > array.Length)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
@@ -385,7 +386,7 @@ namespace System.Security.Permissions {
public KeyContainerPermission (KeyContainerPermissionFlags flags, KeyContainerPermissionAccessEntry[] accessList) {
if (accessList == null)
- throw new ArgumentNullException("accessList");
+ throw new ArgumentNullException(nameof(accessList));
Contract.EndContractBlock();
VerifyFlags(flags);
@@ -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;
diff --git a/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs b/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs
index 57b216e462..3d4e35adf4 100644
--- a/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs
+++ b/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs
@@ -2,20 +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.
-//
-
-//
//
// This class encapsulates security decisions about an application.
//
-namespace System.Security.Policy {
+namespace System.Security.Policy
+{
using System.Collections;
using System.Collections.Generic;
-#if FEATURE_CLICKONCE
- using System.Deployment.Internal.Isolation;
- using System.Deployment.Internal.Isolation.Manifest;
-#endif
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
@@ -40,14 +34,6 @@ namespace System.Security.Policy {
[Serializable]
public sealed class ApplicationTrust : EvidenceBase, ISecurityEncodable
{
-#if FEATURE_CLICKONCE
- private ApplicationIdentity m_appId;
- private bool m_appTrustedToRun;
- private bool m_persist;
-
- private object m_extraInfo;
- private SecurityElement m_elExtraInfo;
-#endif
private PolicyStatement m_psDefaultGrant;
private IList<StrongName> m_fullTrustAssemblies;
@@ -65,11 +51,6 @@ namespace System.Security.Policy {
[NonSerialized]
private int m_grantSetSpecialFlags;
-#if FEATURE_CLICKONCE
- public ApplicationTrust (ApplicationIdentity applicationIdentity) : this () {
- ApplicationIdentity = applicationIdentity;
- }
-#endif
public ApplicationTrust () : this (new PermissionSet(PermissionState.None))
{
}
@@ -83,7 +64,7 @@ namespace System.Security.Policy {
public ApplicationTrust(PermissionSet defaultGrantSet, IEnumerable<StrongName> fullTrustAssemblies) {
if (fullTrustAssemblies == null) {
- throw new ArgumentNullException("fullTrustAssemblies");
+ throw new ArgumentNullException(nameof(fullTrustAssemblies));
}
InitDefaultGrantSet(defaultGrantSet);
@@ -91,7 +72,7 @@ namespace System.Security.Policy {
List<StrongName> fullTrustList = new List<StrongName>();
foreach (StrongName strongName in fullTrustAssemblies) {
if (strongName == null) {
- throw new ArgumentException(Environment.GetResourceString("Argument_NullFullTrustAssembly"), "fullTrustAssemblies");
+ throw new ArgumentException(Environment.GetResourceString("Argument_NullFullTrustAssembly"), nameof(fullTrustAssemblies));
}
fullTrustList.Add(new StrongName(strongName.PublicKey, strongName.Name, strongName.Version));
@@ -104,7 +85,7 @@ namespace System.Security.Policy {
// IEnumerable virtual dispatches on startup when there are no fullTrustAssemblies (CoreCLR)
private void InitDefaultGrantSet(PermissionSet defaultGrantSet) {
if (defaultGrantSet == null) {
- throw new ArgumentNullException("defaultGrantSet");
+ throw new ArgumentNullException(nameof(defaultGrantSet));
}
// Creating a PolicyStatement copies the incoming permission set, so we don't have to worry
@@ -113,19 +94,6 @@ namespace System.Security.Policy {
DefaultGrantSet = new PolicyStatement(defaultGrantSet);
}
-#if FEATURE_CLICKONCE
- public ApplicationIdentity ApplicationIdentity {
- get {
- return m_appId;
- }
- set {
- if (value == null)
- throw new ArgumentNullException("value", Environment.GetResourceString("Argument_InvalidAppId"));
- Contract.EndContractBlock();
- m_appId = value;
- }
- }
-#endif
public PolicyStatement DefaultGrantSet {
get {
if (m_psDefaultGrant == null)
@@ -149,541 +117,10 @@ namespace System.Security.Policy {
return m_fullTrustAssemblies;
}
}
-#if FEATURE_CLICKONCE
- public bool IsApplicationTrustedToRun {
- get {
- return m_appTrustedToRun;
- }
- set {
- m_appTrustedToRun = value;
- }
- }
-
- public bool Persist {
- get {
- return m_persist;
- }
- set {
- m_persist = value;
- }
- }
-
- public object ExtraInfo {
- get {
- if (m_elExtraInfo != null) {
- m_extraInfo = ObjectFromXml(m_elExtraInfo);
- m_elExtraInfo = null;
- }
- return m_extraInfo;
- }
- set {
- m_elExtraInfo = null;
- m_extraInfo = value;
- }
- }
-#endif //FEATURE_CLICKONCE
-
-#if FEATURE_CAS_POLICY
- public SecurityElement ToXml () {
- SecurityElement elRoot = new SecurityElement("ApplicationTrust");
- elRoot.AddAttribute("version", "1");
-
-#if FEATURE_CLICKONCE
- if (m_appId != null) {
- elRoot.AddAttribute("FullName", SecurityElement.Escape(m_appId.FullName));
- }
- if (m_appTrustedToRun) {
- elRoot.AddAttribute("TrustedToRun", "true");
- }
- if (m_persist) {
- elRoot.AddAttribute("Persist", "true");
- }
-#endif // FEATURE_CLICKONCE
-
- if (m_psDefaultGrant != null) {
- SecurityElement elDefaultGrant = new SecurityElement("DefaultGrant");
- elDefaultGrant.AddChild(m_psDefaultGrant.ToXml());
- elRoot.AddChild(elDefaultGrant);
- }
- if (m_fullTrustAssemblies.Count > 0) {
- SecurityElement elFullTrustAssemblies = new SecurityElement("FullTrustAssemblies");
- foreach (StrongName fullTrustAssembly in m_fullTrustAssemblies) {
- elFullTrustAssemblies.AddChild(fullTrustAssembly.ToXml());
- }
- elRoot.AddChild(elFullTrustAssemblies);
- }
-
-#if FEATURE_CLICKONCE
- if (ExtraInfo != null) {
- elRoot.AddChild(ObjectToXml("ExtraInfo", ExtraInfo));
- }
-#endif // FEATURE_CLICKONCE
- return elRoot;
- }
-
- public void FromXml (SecurityElement element) {
- if (element == null)
- throw new ArgumentNullException("element");
- if (String.Compare(element.Tag, "ApplicationTrust", StringComparison.Ordinal) != 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
-
-#if FEATURE_CLICKONCE
- m_appTrustedToRun = false;
- string isAppTrustedToRun = element.Attribute("TrustedToRun");
- if (isAppTrustedToRun != null && String.Compare(isAppTrustedToRun, "true", StringComparison.Ordinal) == 0) {
- m_appTrustedToRun = true;
- }
-
- m_persist = false;
- string persist = element.Attribute("Persist");
- if (persist != null && String.Compare(persist, "true", StringComparison.Ordinal) == 0) {
- m_persist = true;
- }
-
- m_appId = null;
- string fullName = element.Attribute("FullName");
- if (fullName != null && fullName.Length > 0) {
- m_appId = new ApplicationIdentity(fullName);
- }
-#endif // FEATURE_CLICKONCE
-
- m_psDefaultGrant = null;
- m_grantSetSpecialFlags = 0;
- SecurityElement elDefaultGrant = element.SearchForChildByTag("DefaultGrant");
- if (elDefaultGrant != null) {
- SecurityElement elDefaultGrantPS = elDefaultGrant.SearchForChildByTag("PolicyStatement");
- if (elDefaultGrantPS != null) {
- PolicyStatement ps = new PolicyStatement(null);
- ps.FromXml(elDefaultGrantPS);
- m_psDefaultGrant = ps;
- m_grantSetSpecialFlags = SecurityManager.GetSpecialFlags(ps.PermissionSet, null);
- }
- }
-
- List<StrongName> fullTrustAssemblies = new List<StrongName>();
- SecurityElement elFullTrustAssemblies = element.SearchForChildByTag("FullTrustAssemblies");
- if (elFullTrustAssemblies != null && elFullTrustAssemblies.InternalChildren != null) {
- IEnumerator enumerator = elFullTrustAssemblies.Children.GetEnumerator();
- while (enumerator.MoveNext()) {
- StrongName fullTrustAssembly = new StrongName();
- fullTrustAssembly.FromXml(enumerator.Current as SecurityElement);
- fullTrustAssemblies.Add(fullTrustAssembly);
- }
- }
-
- m_fullTrustAssemblies = fullTrustAssemblies.AsReadOnly();
-
-#if FEATURE_CLICKONCE
- m_elExtraInfo = element.SearchForChildByTag("ExtraInfo");
-#endif // FEATURE_CLICKONCE
- }
-
-#if FEATURE_CLICKONCE
- private static SecurityElement ObjectToXml (string tag, Object obj) {
- BCLDebug.Assert(obj != null, "You need to pass in an object");
-
- ISecurityEncodable encodableObj = obj as ISecurityEncodable;
-
- SecurityElement elObject;
- if (encodableObj != null) {
- elObject = encodableObj.ToXml();
- if (!elObject.Tag.Equals(tag))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
- }
- MemoryStream stream = new MemoryStream();
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(stream, obj);
- byte[] array = stream.ToArray();
-
- elObject = new SecurityElement(tag);
- elObject.AddAttribute("Data", Hex.EncodeHexString(array));
- return elObject;
- }
-
- private static Object ObjectFromXml (SecurityElement elObject) {
- BCLDebug.Assert(elObject != null, "You need to pass in a security element");
-
- if (elObject.Attribute("class") != null) {
- ISecurityEncodable encodableObj = XMLUtil.CreateCodeGroup(elObject) as ISecurityEncodable;
- if (encodableObj != null) {
- encodableObj.FromXml(elObject);
- return encodableObj;
- }
- }
-
- string objectData = elObject.Attribute("Data");
- MemoryStream stream = new MemoryStream(Hex.DecodeHexString(objectData));
- BinaryFormatter formatter = new BinaryFormatter();
- return formatter.Deserialize(stream);
- }
-#endif // FEATURE_CLICKONCE
-#endif // FEATURE_CAS_POLICY
-
-#pragma warning disable 618
- [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
-#pragma warning restore 618
- [SecuritySafeCritical]
public override EvidenceBase Clone()
{
return base.Clone();
}
}
-
-#if FEATURE_CLICKONCE
- [System.Security.SecurityCritical] // auto-generated_required
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ApplicationTrustCollection : ICollection {
- private const string ApplicationTrustProperty = "ApplicationTrust";
- private const string InstallerIdentifier = "{60051b8f-4f12-400a-8e50-dd05ebd438d1}";
- private static Guid ClrPropertySet = new Guid("c989bb7a-8385-4715-98cf-a741a8edb823");
-
- // The CLR specific constant install reference.
- private static object s_installReference = null;
- private static StoreApplicationReference InstallReference {
- get {
- if (s_installReference == null) {
- Interlocked.CompareExchange(ref s_installReference,
- new StoreApplicationReference(
- IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING,
- InstallerIdentifier,
- null),
- null);
- }
- return (StoreApplicationReference) s_installReference;
- }
- }
-
- private object m_appTrusts = null;
- private ArrayList AppTrusts {
- [System.Security.SecurityCritical] // auto-generated
- get {
- if (m_appTrusts == null) {
- ArrayList appTrusts = new ArrayList();
- if (m_storeBounded) {
- RefreshStorePointer();
- // enumerate the user store and populate the collection
- StoreDeploymentMetadataEnumeration deplEnum = m_pStore.EnumInstallerDeployments(IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, InstallerIdentifier, ApplicationTrustProperty, null);
- foreach (IDefinitionAppId defAppId in deplEnum) {
- StoreDeploymentMetadataPropertyEnumeration metadataEnum = m_pStore.EnumInstallerDeploymentProperties(IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, InstallerIdentifier, ApplicationTrustProperty, defAppId);
- foreach (StoreOperationMetadataProperty appTrustProperty in metadataEnum) {
- string appTrustXml = appTrustProperty.Value;
- if (appTrustXml != null && appTrustXml.Length > 0) {
- SecurityElement seTrust = SecurityElement.FromString(appTrustXml);
- ApplicationTrust appTrust = new ApplicationTrust();
- appTrust.FromXml(seTrust);
- appTrusts.Add(appTrust);
- }
- }
- }
- }
- Interlocked.CompareExchange(ref m_appTrusts, appTrusts, null);
- }
- return m_appTrusts as ArrayList;
- }
- }
-
- private bool m_storeBounded = false;
- private Store m_pStore = null; // Component store interface pointer.
-
- // Only internal constructors are exposed.
- [System.Security.SecurityCritical] // auto-generated
- internal ApplicationTrustCollection () : this(false) {}
- internal ApplicationTrustCollection (bool storeBounded) {
- m_storeBounded = storeBounded;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private void RefreshStorePointer () {
- // Refresh store pointer.
- if (m_pStore != null)
- Marshal.ReleaseComObject(m_pStore.InternalStore);
- m_pStore = IsolationInterop.GetUserStore();
- }
-
- public int Count
- {
- [System.Security.SecuritySafeCritical] // overrides public transparent member
- get {
- return AppTrusts.Count;
- }
- }
-
- public ApplicationTrust this[int index] {
- [System.Security.SecurityCritical] // auto-generated
- get {
- return AppTrusts[index] as ApplicationTrust;
- }
- }
-
- public ApplicationTrust this[string appFullName] {
- [System.Security.SecurityCritical] // auto-generated
- get {
- ApplicationIdentity identity = new ApplicationIdentity(appFullName);
- ApplicationTrustCollection appTrusts = Find(identity, ApplicationVersionMatch.MatchExactVersion);
- if (appTrusts.Count > 0)
- return appTrusts[0];
- return null;
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private void CommitApplicationTrust(ApplicationIdentity applicationIdentity, string trustXml) {
- StoreOperationMetadataProperty[] properties = new StoreOperationMetadataProperty[] {
- new StoreOperationMetadataProperty(ClrPropertySet, ApplicationTrustProperty, trustXml)
- };
-
- IEnumDefinitionIdentity idenum = applicationIdentity.Identity.EnumAppPath();
- IDefinitionIdentity[] asbId = new IDefinitionIdentity[1];
- IDefinitionIdentity deplId = null;
- if (idenum.Next(1, asbId) == 1)
- deplId = asbId[0];
-
- IDefinitionAppId defAppId = IsolationInterop.AppIdAuthority.CreateDefinition();
- defAppId.SetAppPath(1, new IDefinitionIdentity[] {deplId});
- defAppId.put_Codebase(applicationIdentity.CodeBase);
-
- using (StoreTransaction storeTxn = new StoreTransaction()) {
- storeTxn.Add(new StoreOperationSetDeploymentMetadata(defAppId, InstallReference, properties));
- RefreshStorePointer();
- m_pStore.Transact(storeTxn.Operations);
- }
-
- m_appTrusts = null; // reset the app trusts in the collection.
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public int Add (ApplicationTrust trust) {
- if (trust == null)
- throw new ArgumentNullException("trust");
- if (trust.ApplicationIdentity == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity"));
- Contract.EndContractBlock();
-
- // Add the trust decision of the application to the fusion store.
- if (m_storeBounded) {
- CommitApplicationTrust(trust.ApplicationIdentity, trust.ToXml().ToString());
- return -1;
- } else {
- return AppTrusts.Add(trust);
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public void AddRange (ApplicationTrust[] trusts) {
- if (trusts == null)
- throw new ArgumentNullException("trusts");
- Contract.EndContractBlock();
-
- int i=0;
- try {
- for (; i<trusts.Length; i++) {
- Add(trusts[i]);
- }
- } catch {
- for (int j=0; j<i; j++) {
- Remove(trusts[j]);
- }
- throw;
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public void AddRange (ApplicationTrustCollection trusts) {
- if (trusts == null)
- throw new ArgumentNullException("trusts");
- Contract.EndContractBlock();
-
- int i = 0;
- try {
- foreach (ApplicationTrust trust in trusts) {
- Add(trust);
- i++;
- }
- } catch {
- for (int j=0; j<i; j++) {
- Remove(trusts[j]);
- }
- throw;
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public ApplicationTrustCollection Find (ApplicationIdentity applicationIdentity, ApplicationVersionMatch versionMatch) {
- ApplicationTrustCollection collection = new ApplicationTrustCollection(false);
- foreach (ApplicationTrust trust in this) {
- if (CmsUtils.CompareIdentities(trust.ApplicationIdentity, applicationIdentity, versionMatch))
- collection.Add(trust);
- }
- return collection;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public void Remove (ApplicationIdentity applicationIdentity, ApplicationVersionMatch versionMatch) {
- ApplicationTrustCollection collection = Find(applicationIdentity, versionMatch);
- RemoveRange(collection);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public void Remove (ApplicationTrust trust) {
- if (trust == null)
- throw new ArgumentNullException("trust");
- if (trust.ApplicationIdentity == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity"));
- Contract.EndContractBlock();
-
- // Remove the trust decision of the application from the fusion store.
- if (m_storeBounded) {
- CommitApplicationTrust(trust.ApplicationIdentity, null);
- } else {
- AppTrusts.Remove(trust);
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public void RemoveRange (ApplicationTrust[] trusts) {
- if (trusts == null)
- throw new ArgumentNullException("trusts");
- Contract.EndContractBlock();
-
- int i=0;
- try {
- for (; i<trusts.Length; i++) {
- Remove(trusts[i]);
- }
- } catch {
- for (int j=0; j<i; j++) {
- Add(trusts[j]);
- }
- throw;
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public void RemoveRange (ApplicationTrustCollection trusts) {
- if (trusts == null)
- throw new ArgumentNullException("trusts");
- Contract.EndContractBlock();
-
- int i = 0;
- try {
- foreach (ApplicationTrust trust in trusts) {
- Remove(trust);
- i++;
- }
- } catch {
- for (int j=0; j<i; j++) {
- Add(trusts[j]);
- }
- throw;
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public void Clear() {
- // remove all trust decisions in the collection.
- ArrayList trusts = this.AppTrusts;
- if (m_storeBounded) {
- foreach (ApplicationTrust trust in trusts) {
- if (trust.ApplicationIdentity == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity"));
-
- // Remove the trust decision of the application from the fusion store.
- CommitApplicationTrust(trust.ApplicationIdentity, null);
- }
- }
- trusts.Clear();
- }
-
- public ApplicationTrustEnumerator GetEnumerator() {
- return new ApplicationTrustEnumerator(this);
- }
-
- /// <internalonly/>
- [System.Security.SecuritySafeCritical] // overrides public transparent member
- IEnumerator IEnumerable.GetEnumerator()
- {
- return new ApplicationTrustEnumerator(this);
- }
-
- /// <internalonly/>
- [System.Security.SecuritySafeCritical] // overrides public transparent member
- void ICollection.CopyTo(Array array, int index) {
- if (array == null)
- throw new ArgumentNullException("array");
- if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- if (index < 0 || index >= array.Length)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (array.Length - index < this.Count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
- Contract.EndContractBlock();
-
- for (int i=0; i < this.Count; i++) {
- array.SetValue(this[i], index++);
- }
- }
-
- public void CopyTo (ApplicationTrust[] array, int index) {
- ((ICollection)this).CopyTo(array, index);
- }
-
- public bool IsSynchronized {
- [System.Security.SecuritySafeCritical] // overrides public transparent member
- get
- {
- return false;
- }
- }
-
- public object SyncRoot {
- [System.Security.SecuritySafeCritical] // overrides public transparent member
- get
- {
- return this;
- }
- }
- }
-
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ApplicationTrustEnumerator : IEnumerator {
- [System.Security.SecurityCritical] // auto-generated
- private ApplicationTrustCollection m_trusts;
- private int m_current;
-
- private ApplicationTrustEnumerator() {}
- [System.Security.SecurityCritical] // auto-generated
- internal ApplicationTrustEnumerator(ApplicationTrustCollection trusts) {
- m_trusts = trusts;
- m_current = -1;
- }
-
- public ApplicationTrust Current {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- return m_trusts[m_current];
- }
- }
-
- /// <internalonly/>
- object IEnumerator.Current {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- return (object) m_trusts[m_current];
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public bool MoveNext() {
- if (m_current == ((int) m_trusts.Count - 1))
- return false;
- m_current++;
- return true;
- }
-
- public void Reset() {
- m_current = -1;
- }
- }
-#endif // FEATURE_CLICKONCE
}
diff --git a/src/mscorlib/src/System/Security/Policy/Evidence.cs b/src/mscorlib/src/System/Security/Policy/Evidence.cs
index 8bf8aa7e92..22479dff6c 100644
--- a/src/mscorlib/src/System/Security/Policy/Evidence.cs
+++ b/src/mscorlib/src/System/Security/Policy/Evidence.cs
@@ -2,28 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
namespace System.Security.Policy
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Configuration.Assemblies;
- using System.Diagnostics.Contracts;
- using System.IO;
- using System.Reflection;
- using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
#endif // FEATURE_SERIALIZATION
- using System.Security.Permissions;
- using System.Security.Util;
- using System.Threading;
- using Microsoft.Win32.SafeHandles;
/// <summary>
/// The Evidence class keeps track of information that can be used to make security decisions about
@@ -48,1856 +33,6 @@ namespace System.Security.Policy
#endif
[ComVisible(true)]
public sealed class Evidence
-#if FEATURE_CAS_POLICY
- : ICollection
-#endif // FEATURE_CAS_POLICY
{
-#if !FEATURE_CORECLR && FEATURE_RWLOCK
-#if FEATURE_SERIALIZATION
- [OptionalField(VersionAdded = 4)]
- private Dictionary<Type, EvidenceTypeDescriptor> m_evidence;
-
- [OptionalField(VersionAdded = 4)]
- private bool m_deserializedTargetEvidence;
-
- // These fields are only used to deserialize v2.0 serialized versions of Evidence. It will be null
- // after the seriailzation process is complete, and should not be used.
-#pragma warning disable 414
- private volatile ArrayList m_hostList;
- private volatile ArrayList m_assemblyList;
-#pragma warning restore 414
-#else // !FEATURE_SERIALIZATION
- private Dictionary<Type, EvidenceTypeDescriptor> m_evidence;
-#endif // FEATURE_SERIALIZATION
-
- [NonSerialized]
- private ReaderWriterLock m_evidenceLock;
-
- [NonSerialized]
- private uint m_version;
-
- [NonSerialized]
- private IRuntimeEvidenceFactory m_target;
-
- private bool m_locked;
-
- // If this evidence collection is a clone where we may need to backpatch to the original, this will
- // reference the collection it was cloned from. See
- // code:System.Security.Policy.Evidence#BackpatchGeneratedEvidence
- [NonSerialized]
- private WeakReference m_cloneOrigin;
-
- private static volatile Type[] s_runtimeEvidenceTypes;
-
- /// <summary>
- /// Set of actions that we could perform if we detect that we are attempting to add evidence
- /// when we already have evidence of that type stored.
- /// </summary>
- private enum DuplicateEvidenceAction
- {
- Throw, // Throw an exception
- Merge, // Create a list of all the evidence objects
- SelectNewObject // The newly added object wins
- }
-
-#if FEATURE_CAS_POLICY
- public Evidence()
- {
- m_evidence = new Dictionary<Type, EvidenceTypeDescriptor>();
- m_evidenceLock = new ReaderWriterLock();
- }
-#endif // FEATURE_CAS_POLICY
-
- /// <summary>
- /// Create a deep copy of an evidence object
- /// </summary>
- public Evidence(Evidence evidence)
- {
- m_evidence = new Dictionary<Type, EvidenceTypeDescriptor>();
-
- if (evidence != null)
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(evidence, EvidenceLockHolder.LockType.Reader))
- {
- foreach (KeyValuePair<Type, EvidenceTypeDescriptor> evidenceType in evidence.m_evidence)
- {
- EvidenceTypeDescriptor cloneDescriptor = evidenceType.Value;
- if (cloneDescriptor != null)
- {
- cloneDescriptor = cloneDescriptor.Clone();
- }
-
- m_evidence[evidenceType.Key] = cloneDescriptor;
- }
-
- m_target = evidence.m_target;
- m_locked = evidence.m_locked;
-#if FEATURE_SERIALIZATION
- m_deserializedTargetEvidence = evidence.m_deserializedTargetEvidence;
-#endif // FEATURE_SERIALIZATION
-
- // see code:System.Security.Policy.Evidence#BackpatchGeneratedEvidence
- if (evidence.Target != null)
- {
- m_cloneOrigin = new WeakReference(evidence);
- }
- }
- }
-
- // see code:System.Security.Policy.Evidence#EvidenceLock
- m_evidenceLock = new ReaderWriterLock();
- }
-
- [Obsolete("This constructor is obsolete. Please use the constructor which takes arrays of EvidenceBase instead.")]
- public Evidence(object[] hostEvidence, object[] assemblyEvidence)
- {
- m_evidence = new Dictionary<Type, EvidenceTypeDescriptor>();
-
- // This is a legacy evidence entry point, so we add through the legacy add APIs in order to get
- // proper legacy wrapping and merge behavior.
-#pragma warning disable 618
- if (hostEvidence != null)
- {
- foreach (object hostEvidenceObject in hostEvidence)
- {
- AddHost(hostEvidenceObject);
- }
- }
-
- if (assemblyEvidence != null)
- {
- foreach (object assemblyEvidenceObject in assemblyEvidence)
- {
- AddAssembly(assemblyEvidenceObject);
- }
- }
-#pragma warning restore 618
-
- // see code:System.Security.Policy.Evidence#EvidenceLock
- m_evidenceLock = new ReaderWriterLock();
- }
-
- public Evidence(EvidenceBase[] hostEvidence, EvidenceBase[] assemblyEvidence)
- {
- m_evidence = new Dictionary<Type, EvidenceTypeDescriptor>();
-
- if (hostEvidence != null)
- {
- foreach (EvidenceBase hostEvidenceObject in hostEvidence)
- {
- AddHostEvidence(hostEvidenceObject, GetEvidenceIndexType(hostEvidenceObject), DuplicateEvidenceAction.Throw);
- }
- }
-
- if (assemblyEvidence != null)
- {
- foreach (EvidenceBase assemblyEvidenceObject in assemblyEvidence)
- {
- AddAssemblyEvidence(assemblyEvidenceObject, GetEvidenceIndexType(assemblyEvidenceObject), DuplicateEvidenceAction.Throw);
- }
- }
-
- // see code:System.Security.Policy.Evidence#EvidenceLock
- m_evidenceLock = new ReaderWriterLock();
- }
-
- /// <summary>
- /// Create an empty evidence collection which will contain evidence for a specific assembly or
- /// AppDomain
- /// </summary>
- [SecuritySafeCritical]
- internal Evidence(IRuntimeEvidenceFactory target)
- {
- Contract.Assert(target != null);
-
- m_evidence = new Dictionary<Type, EvidenceTypeDescriptor>();
- m_target = target;
-
- // Setup the types of evidence that the CLR can generate for a target as keys in the dictionary
- foreach (Type runtimeEvidenceType in RuntimeEvidenceTypes)
- {
- BCLDebug.Assert(typeof(EvidenceBase).IsAssignableFrom(runtimeEvidenceType), "All runtime evidence types should be EvidenceBases");
- m_evidence[runtimeEvidenceType] = null;
- }
-
- QueryHostForPossibleEvidenceTypes();
-
- // see code:System.Security.Policy.Evidence#EvidenceLock
- m_evidenceLock = new ReaderWriterLock();
- }
-
- internal static Type[] RuntimeEvidenceTypes
- {
- get
- {
- if (s_runtimeEvidenceTypes == null)
- {
- Type[] runtimeEvidenceTypes = new Type[]
- {
-#if FEATURE_CLICKONCE
- typeof(System.Runtime.Hosting.ActivationArguments),
-#endif // FEATURE_CLICKONCE
-#if FEATURE_CAS_POLICY
- typeof(ApplicationDirectory),
-#endif // FEATURE_CAS_POLICY
- typeof(ApplicationTrust),
-#if FEATURE_CAS_POLICY
- typeof(GacInstalled),
- typeof(Hash),
- typeof(Publisher),
-#endif // FEATURE_CAS_POLICY
- typeof(Site),
- typeof(StrongName),
- typeof(Url),
- typeof(Zone)
- };
-
-#if FEATURE_CAS_POLICY
- // We only supply permission request evidence in legacy CAS mode
- if (AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
-#pragma warning disable 618 // We need to generate PermissionRequestEvidence in compatibility mode
- int l = runtimeEvidenceTypes.Length;
- Array.Resize(ref runtimeEvidenceTypes, l+1);
- runtimeEvidenceTypes[l] = typeof(PermissionRequestEvidence);
-#pragma warning restore 618
- }
-#endif // FEATURE_CAS_POLICY
-
- s_runtimeEvidenceTypes = runtimeEvidenceTypes;
- }
-
- return s_runtimeEvidenceTypes;
- }
- }
-
- //
- // #EvidenceLock
- //
- // Evidence synchronization locking wrappers. In the case where the lock has not yet been created,
- // we know that we're in the process of constructing the evidence collection and therefore we can
- // act as though the evidence is locked. If there is a lock in place, then just delegate back to it.
- //
- // The nested EvidenceLockHolder and EvidenceUpgradeLockHolder utility classes can be used to wrap
- // these methods when acquiring and releasing the evidence lock.
- //
-
- // Millisecond timeout when waiting to acquire the evidence lock
- private const int LockTimeout = 5000;
-
- private bool IsReaderLockHeld
- {
- get { return m_evidenceLock == null || m_evidenceLock.IsReaderLockHeld; }
- }
-
- private bool IsWriterLockHeld
- {
- get { return m_evidenceLock == null || m_evidenceLock.IsWriterLockHeld; }
- }
-
- private void AcquireReaderLock()
- {
- Contract.Assert(m_evidenceLock == null || !IsReaderLockHeld);
-
- if (m_evidenceLock != null)
- {
- m_evidenceLock.AcquireReaderLock(LockTimeout);
- }
- }
-
- private void AcquireWriterlock()
- {
- Contract.Assert(m_evidenceLock == null || !IsWriterLockHeld);
-
- if (m_evidenceLock != null)
- {
- m_evidenceLock.AcquireWriterLock(LockTimeout);
- }
- }
-
- private void DowngradeFromWriterLock(ref LockCookie lockCookie)
- {
- Contract.Assert(IsWriterLockHeld);
- if (m_evidenceLock != null)
- {
- m_evidenceLock.DowngradeFromWriterLock(ref lockCookie);
- }
- }
-
- private LockCookie UpgradeToWriterLock()
- {
- Contract.Assert(IsReaderLockHeld);
- return m_evidenceLock != null ? m_evidenceLock.UpgradeToWriterLock(LockTimeout) : new LockCookie();
- }
-
- private void ReleaseReaderLock()
- {
- Contract.Assert(IsReaderLockHeld);
-
- if (m_evidenceLock != null)
- {
- m_evidenceLock.ReleaseReaderLock();
- }
- }
-
- private void ReleaseWriterLock()
- {
- Contract.Assert(IsWriterLockHeld);
-
- if (m_evidenceLock != null)
- {
- m_evidenceLock.ReleaseWriterLock();
- }
- }
-
- [Obsolete("This method is obsolete. Please use AddHostEvidence instead.")]
- [SecuritySafeCritical]
- public void AddHost(object id)
- {
- if (id == null)
- throw new ArgumentNullException("id");
- if (!id.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Policy_EvidenceMustBeSerializable"), "id");
- Contract.EndContractBlock();
-
- if (m_locked)
- {
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
- }
-
- EvidenceBase evidence = WrapLegacyEvidence(id);
- Type evidenceIndex = GetEvidenceIndexType(evidence);
-
- // Whidbey allowed for multiple types of the same evidence, so if we're being called via the Whidbey
- // APIs, then allow the evidences to merge together.
- AddHostEvidence(evidence, evidenceIndex, DuplicateEvidenceAction.Merge);
- }
-
- [Obsolete("This method is obsolete. Please use AddAssemblyEvidence instead.")]
- public void AddAssembly(object id)
- {
- if (id == null)
- throw new ArgumentNullException("id");
- if (!id.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Policy_EvidenceMustBeSerializable"), "id");
- Contract.EndContractBlock();
-
- EvidenceBase evidence = WrapLegacyEvidence(id);
- Type evidenceIndex = GetEvidenceIndexType(evidence);
-
- // Whidbey allowed for multiple types of the same evidence, so if we're being called via the Whidbey
- // APIs, then allow the evidences to merge together.
- AddAssemblyEvidence(evidence, evidenceIndex, DuplicateEvidenceAction.Merge);
- }
-
- /// <summary>
- /// Add a piece of evidence to the assembly supplied evidence list. This method will disallow adding
- /// evidence if there is already evidence of that type in the assembly list.
- /// </summary>
- [ComVisible(false)]
- public void AddAssemblyEvidence<T>(T evidence) where T : EvidenceBase
- {
- if (evidence == null)
- throw new ArgumentNullException("evidence");
- Contract.EndContractBlock();
-
- // Index the evidence under the type that the Add function was called with, unless we were given
- // a plain EvidenceBase or a wrapped legacy evidence. In that case, we need to index under a
- // more specific type.
- Type evidenceType = typeof(T);
- if (typeof(T) == typeof(EvidenceBase) || evidence is ILegacyEvidenceAdapter)
- {
- evidenceType = GetEvidenceIndexType(evidence);
- }
-
- AddAssemblyEvidence(evidence, evidenceType, DuplicateEvidenceAction.Throw);
- }
-
- private void AddAssemblyEvidence(EvidenceBase evidence, Type evidenceType, DuplicateEvidenceAction duplicateAction)
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer))
- {
- AddAssemblyEvidenceNoLock(evidence, evidenceType, duplicateAction);
- }
- }
-
- private void AddAssemblyEvidenceNoLock(EvidenceBase evidence, Type evidenceType, DuplicateEvidenceAction duplicateAction)
- {
- Contract.Assert(IsWriterLockHeld);
- Contract.Assert(evidence != null);
- Contract.Assert(evidenceType != null);
-
- // We need to make sure that any target supplied evidence is deserialized before adding to the
- // Assembly collection in order to preserve the semantics that the evidence objects supplied by
- // the target are the original versions and evidence objects added via the APIs are the duplicates.
- DeserializeTargetEvidence();
-
- EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(evidenceType, true);
-
- ++m_version;
- if (descriptor.AssemblyEvidence == null)
- {
- descriptor.AssemblyEvidence = evidence;
- }
- else
- {
- descriptor.AssemblyEvidence = HandleDuplicateEvidence(descriptor.AssemblyEvidence,
- evidence,
- duplicateAction);
- }
- }
-
- /// <summary>
- /// Add a piece of evidence to the host supplied evidence list. This method will disallow adding
- /// evidence if there is already evidence of that type in the host list.
- /// </summary>
- [ComVisible(false)]
- public void AddHostEvidence<T>(T evidence) where T : EvidenceBase
- {
- if (evidence == null)
- throw new ArgumentNullException("evidence");
- Contract.EndContractBlock();
-
- // Index the evidence under the type that the Add function was called with, unless we were given
- // a plain EvidenceBase or a wrapped legacy evidence. In that case, we need to index under a
- // more specific type.
- Type evidenceType = typeof(T);
- if (typeof(T) == typeof(EvidenceBase) || evidence is ILegacyEvidenceAdapter)
- {
- evidenceType = GetEvidenceIndexType(evidence);
- }
-
- AddHostEvidence(evidence, evidenceType, DuplicateEvidenceAction.Throw);
- }
-
- [SecuritySafeCritical]
- private void AddHostEvidence(EvidenceBase evidence, Type evidenceType, DuplicateEvidenceAction duplicateAction)
- {
- Contract.Assert(evidence != null);
- Contract.Assert(evidenceType != null);
-
- if (Locked)
- {
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
- }
-
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer))
- {
- AddHostEvidenceNoLock(evidence, evidenceType, duplicateAction);
- }
- }
-
- /// <summary>
- /// Add evidence to the host supplied evidence collection without acquiring the evidence lock or
- /// checking to make sure that the caller has permission to bypass locked evidence.
- /// </summary>
- private void AddHostEvidenceNoLock(EvidenceBase evidence, Type evidenceType, DuplicateEvidenceAction duplicateAction)
- {
- Contract.Assert(IsWriterLockHeld);
- Contract.Assert(evidence != null);
- Contract.Assert(evidenceType != null);
-
- EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(evidenceType, true);
-
- ++m_version;
- if (descriptor.HostEvidence == null)
- {
- descriptor.HostEvidence = evidence;
- }
- else
- {
- descriptor.HostEvidence = HandleDuplicateEvidence(descriptor.HostEvidence,
- evidence,
- duplicateAction);
- }
- }
-
- /// <summary>
- /// Ask the host for the types of evidence that it might provide if it is asked.
- ///
- /// This should only be called when setting up the Evidence collection to interact with the
- /// host, and should not be used once that connection is established and the evidence has been
- /// made available to user code.
- /// </summary>
- [SecurityCritical]
- private void QueryHostForPossibleEvidenceTypes()
- {
-#if FEATURE_CAS_POLICY
- Contract.Assert(IsWriterLockHeld);
-
- // First check to see if we have a HostSecurityManager
- if (AppDomain.CurrentDomain.DomainManager != null)
- {
- HostSecurityManager hsm = AppDomain.CurrentDomain.DomainManager.HostSecurityManager;
- if (hsm != null)
- {
- Type[] hostSuppliedTypes = null;
-
- AppDomain targetDomain = m_target.Target as AppDomain;
- Assembly targetAssembly = m_target.Target as Assembly;
-
- //
- // If the HostSecurityManager wants to supply evidence for the type of target that we have,
- // then ask it what types of evidence it might supply.
- //
-
- if (targetAssembly != null &&
- (hsm.Flags & HostSecurityManagerOptions.HostAssemblyEvidence) == HostSecurityManagerOptions.HostAssemblyEvidence)
- {
- hostSuppliedTypes = hsm.GetHostSuppliedAssemblyEvidenceTypes(targetAssembly);
- }
- else if (targetDomain != null &&
- (hsm.Flags & HostSecurityManagerOptions.HostAppDomainEvidence) == HostSecurityManagerOptions.HostAppDomainEvidence)
- {
- hostSuppliedTypes = hsm.GetHostSuppliedAppDomainEvidenceTypes();
- }
-
- //
- // Finally, mark the descriptor for each of the types that the host can supply to indicate
- // we should ask the host to generate them if we're asked.
- //
-
- if (hostSuppliedTypes != null)
- {
- foreach (Type hostEvidenceType in hostSuppliedTypes)
- {
- EvidenceTypeDescriptor evidenceDescriptor = GetEvidenceTypeDescriptor(hostEvidenceType, true);
- evidenceDescriptor.HostCanGenerate = true;
- }
- }
- }
- }
-#endif // FEATURE_CAS_POLICY
- }
-
- internal bool IsUnmodified
- {
- get { return m_version == 0; }
- }
-
- /// <summary>
- /// Set or check to see if the evidence is locked. Locked evidence cannot have its host supplied
- /// evidence list be modified without a successful demand for ControlEvidence. Any code can lock
- /// evidence, but only code with ControlEvidence may unlock it.
- ///
- /// This lock is not the same as the synchronization lock that gates access to the evidence collection.
- /// </summary>
- public bool Locked
- {
- get
- {
- return m_locked;
- }
-
- [SecuritySafeCritical]
- set
- {
- if (!value)
- {
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
-
- m_locked = false;
- }
- else
- {
- m_locked = true;
- }
- }
- }
-
- /// <summary>
- /// Target of any delay generated evidence objects
- /// </summary>
- internal IRuntimeEvidenceFactory Target
- {
- get { return m_target; }
-
- //
- // There are two retargeting scenarios supported:
- //
- // 1. A PEFileEvidenceFactory is being upgraded to an AssemblyEvidenceFactory and we don't want
- // to throw away any already generated evidence.
- // 2. A detached evidence collection is being applied to an AppDomain and that domain has a
- // HostSecurityManager. In that case, we want to attach the target to the AppDomain to
- // allow the HostSecurityManager to get callbacks for delay generated evidence.
- //
-
- [SecurityCritical]
- set
- {
-#if FEATURE_CAS_POLICY
- Contract.Assert((m_target != null && m_target is PEFileEvidenceFactory && value != null && value is AssemblyEvidenceFactory) ||
- (m_target == null && value != null && value is AppDomainEvidenceFactory),
- "Evidence retargeting should only be from PEFile -> Assembly or detached -> AppDomain.");
-#endif // FEATURE_CAS_POLICY
-
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer))
- {
- m_target = value;
-
- // Since we've updated what we're pointing at, we need to query the host to determine what
- // types of evidence that it can generate for this new target.
- QueryHostForPossibleEvidenceTypes();
- }
- }
- }
-
- /// <summary>
- /// Get the type that would be used to index into the evidence dictionary for this object
- /// </summary>
- private static Type GetEvidenceIndexType(EvidenceBase evidence)
- {
- Contract.Assert(evidence != null);
-
- //
- // Legacy wrapper evidence types should be indexed via the type of evidence that they're wrapping
- // so check to see if we have one of those; otherwise just return the type itself.
- //
-
- ILegacyEvidenceAdapter adapter = evidence as ILegacyEvidenceAdapter;
- return adapter == null ? evidence.GetType() : adapter.EvidenceType;
- }
-
- /// <summary>
- /// Get the type descriptor for a specific type of evidence. This method should be used instead
- /// of accessing the dictionary directly as it will handle the case where a new descriptor needs
- /// to be created.
- /// </summary>
- internal EvidenceTypeDescriptor GetEvidenceTypeDescriptor(Type evidenceType)
- {
- return GetEvidenceTypeDescriptor(evidenceType, false);
- }
-
- /// <summary>
- /// Get the type descriptor for a specific type of evidence, optionally creating a descriptor if
- /// we did not yet know about this type of evidence. This method should be used instead of
- /// accessing the dictionary directly as it will handle the case where a new descriptor needs
- /// to be created.
- /// </summary>
- private EvidenceTypeDescriptor GetEvidenceTypeDescriptor(Type evidenceType, bool addIfNotExist)
- {
- Contract.Assert(IsReaderLockHeld || IsWriterLockHeld);
- Contract.Assert(evidenceType != null);
-
- // If we don't know about the type being indexed and we don't want to add it then exit out
- EvidenceTypeDescriptor descriptor = null;
- if (!m_evidence.TryGetValue(evidenceType, out descriptor) && !addIfNotExist)
- {
- return null;
- }
-
- // If we haven't yet created a descriptor for this type then create one now
- if (descriptor == null)
- {
- descriptor = new EvidenceTypeDescriptor();
-#if _DEBUG
- descriptor.SetEvidenceType(evidenceType);
-#endif // _DEBUG
-
- bool upgradedLock = false;
- LockCookie upgradeCookie = new LockCookie();
- try
- {
- if (!IsWriterLockHeld)
- {
- upgradeCookie = UpgradeToWriterLock();
- upgradedLock = true;
- }
-
- m_evidence[evidenceType] = descriptor;
- }
- finally
- {
- if (upgradedLock)
- DowngradeFromWriterLock(ref upgradeCookie);
- }
- }
-
- return descriptor;
- }
-
- /// <summary>
- /// This method is called if a piece of evidence is added but another piece of evidence of the same
- /// type already existed. We have different strategies depending on compatibility concerns of the
- /// calling code.
- /// </summary>
- private static EvidenceBase HandleDuplicateEvidence(EvidenceBase original,
- EvidenceBase duplicate,
- DuplicateEvidenceAction action)
- {
- Contract.Assert(original != null);
- Contract.Assert(duplicate != null);
- Contract.Assert(original.GetType() == duplicate.GetType() || original.GetType() == typeof(LegacyEvidenceList));
-
- switch (action)
- {
- // Throw - duplicate evidence is not allowed (Arrowhead behavior), so throw an exception
- case DuplicateEvidenceAction.Throw:
- throw new InvalidOperationException(Environment.GetResourceString("Policy_DuplicateEvidence", duplicate.GetType().FullName));
-
- // SelectNewObject - MergeWithNoDuplicates behavior - the duplicate object wins
- case DuplicateEvidenceAction.SelectNewObject:
- return duplicate;
-
- // Merge - compat behavior. Merge the old and new evidence into a list so that both may exist
- case DuplicateEvidenceAction.Merge:
-
- LegacyEvidenceList list = original as LegacyEvidenceList;
- if (list == null)
- {
- list = new LegacyEvidenceList();
- list.Add(original);
- }
-
- list.Add(duplicate);
- return list;
-
- default:
- BCLDebug.Assert(false, "Uknown DuplicateEvidenceAction");
- return null;
- }
- }
-
- /// <summary>
- /// Wrap evidence we recieved through a legacy API to ensure that it is stored in an EvidenceBase
- /// </summary>
- private static EvidenceBase WrapLegacyEvidence(object evidence)
- {
- Contract.Assert(evidence != null);
-
- EvidenceBase wrappedEvidence = evidence as EvidenceBase;
- if (wrappedEvidence == null)
- {
- wrappedEvidence = new LegacyEvidenceWrapper(evidence);
- }
-
- return wrappedEvidence;
- }
-
- /// <summary>
- /// Upwrap evidence stored in a legacy adapter.
- ///
- /// This is only necessary for the case where multiple objects derived from EvidenceBase is
- /// are added via the legacy APIs and are then retrieved via GetHostEvidence. This may occur if
- /// a legacy application adds CLR supplied evidence types via the old APIs and a new application
- /// consumes the resulting evidence.
- /// </summary>
- private static object UnwrapEvidence(EvidenceBase evidence)
- {
- ILegacyEvidenceAdapter adapter = evidence as ILegacyEvidenceAdapter;
- return adapter == null ? evidence : adapter.EvidenceObject;
- }
-
- /// <summary>
- /// Merge two evidence collections together. Note that this will cause all of the lazily
- /// generated evidence for the input collection to be generated, as well as causing any lazily
- /// generated evidence that both collections share to be generated in the target.
- /// </summary>
- [SecuritySafeCritical]
- public void Merge(Evidence evidence)
- {
- if (evidence == null)
- {
- return;
- }
-
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer))
- {
- bool checkedLock = false;
- IEnumerator hostEnumerator = evidence.GetHostEnumerator();
- while (hostEnumerator.MoveNext())
- {
- if (Locked && !checkedLock)
- {
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
- checkedLock = true;
- }
-
- // If we could potentially have evidence of the type about to be merged into our host list,
- // then make sure that we generate that evidence before merging. This will prevent the
- // newly merged evidence from masking the value that we would have generated on our own.
- Type hostEvidenceType = hostEnumerator.Current.GetType();
- if (m_evidence.ContainsKey(hostEvidenceType))
- {
- GetHostEvidenceNoLock(hostEvidenceType);
- }
-
- EvidenceBase hostEvidence = WrapLegacyEvidence(hostEnumerator.Current);
- AddHostEvidenceNoLock(hostEvidence,
- GetEvidenceIndexType(hostEvidence),
- DuplicateEvidenceAction.Merge);
- }
-
- // Add each piece of assembly evidence. We don't need to deserialize our copy of the
- // evidence because AddAssemblyEvidenceNoLock will do this for us.
- IEnumerator assemblyEnumerator = evidence.GetAssemblyEnumerator();
- while (assemblyEnumerator.MoveNext())
- {
- EvidenceBase assemblyEvidence = WrapLegacyEvidence(assemblyEnumerator.Current);
- AddAssemblyEvidenceNoLock(assemblyEvidence,
- GetEvidenceIndexType(assemblyEvidence),
- DuplicateEvidenceAction.Merge);
- }
- }
- }
-
- /// <summary>
- /// Same as merge, except only one instance of any one evidence type is allowed. When duplicates
- /// are found, the evidence in the input argument will have priority. Note this will force the
- /// entire input evidence to be generated, and does not check for locked evidence
- /// </summary>
- internal void MergeWithNoDuplicates(Evidence evidence)
- {
- if (evidence == null)
- {
- return;
- }
-
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer))
- {
- IEnumerator hostEnumerator = evidence.GetHostEnumerator();
- while (hostEnumerator.MoveNext())
- {
- EvidenceBase hostEvidence = WrapLegacyEvidence(hostEnumerator.Current);
- AddHostEvidenceNoLock(hostEvidence,
- GetEvidenceIndexType(hostEvidence),
- DuplicateEvidenceAction.SelectNewObject);
- }
-
- IEnumerator assemblyEnumerator = evidence.GetAssemblyEnumerator();
- while (assemblyEnumerator.MoveNext())
- {
- EvidenceBase assemblyEvidence = WrapLegacyEvidence(assemblyEnumerator.Current);
- AddAssemblyEvidenceNoLock(assemblyEvidence,
- GetEvidenceIndexType(assemblyEvidence),
- DuplicateEvidenceAction.SelectNewObject);
- }
- }
- }
-
-#if FEATURE_SERIALIZATION
- /// <summary>
- /// Do a full serialization of the evidence, which requires that we generate all of the evidence
- /// we can and disconnect ourselves from the host and source assembly.
- /// </summary>
- [ComVisible(false)]
- [OnSerializing]
- [SecurityCritical]
- [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
- private void OnSerializing(StreamingContext context)
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- // First, force all of the host evidence that might be lazily generated to be created
- foreach (Type evidenceType in new List<Type>(m_evidence.Keys))
- {
- GetHostEvidenceNoLock(evidenceType);
- }
-
- // Also ensure that all serialized assembly evidence has been created
- DeserializeTargetEvidence();
- }
-
- // Fill in legacy evidence lists. We can't guarantee thread-safety here using locks
- // because we can't put a lock in the serialization code that will read the lists.
- // The best we can do is prevent another thread from seeing a half-populated list.
- // Therefore, we assign the lists after we've populated them fully (and declare them volatile.)
- ArrayList hostList = new ArrayList();
- IEnumerator hostEnumerator = GetHostEnumerator();
- while (hostEnumerator.MoveNext())
- {
- hostList.Add(hostEnumerator.Current);
- }
- m_hostList = hostList;
-
- ArrayList assemblyList = new ArrayList();
- IEnumerator assemblyEnumerator = GetAssemblyEnumerator();
- while (assemblyEnumerator.MoveNext())
- {
- assemblyList.Add(assemblyEnumerator.Current);
- }
- m_assemblyList = assemblyList;
- }
-
- /// <summary>
- /// Finish deserializing legacy evidence
- /// </summary>
- [ComVisible(false)]
- [OnDeserialized]
- [SecurityCritical]
- private void OnDeserialized(StreamingContext context)
- {
- // Look at host and assembly evidence lists only if we serialized using Whidbey.
- if (m_evidence == null)
- {
- m_evidence = new Dictionary<Type, EvidenceTypeDescriptor>();
-
- // Whidbey evidence may need to be wrapped or added to a LegacyEvidenceList, so we go
- // through the legacy APIs to add them.
-#pragma warning disable 618
- if (m_hostList != null)
- {
- foreach (object evidenceObject in m_hostList)
- {
- if (evidenceObject != null)
- {
- AddHost(evidenceObject);
- }
- }
-
- m_hostList = null;
- }
-
- if (m_assemblyList != null)
- {
- foreach (object evidenceObject in m_assemblyList)
- {
- if (evidenceObject != null)
- {
- AddAssembly(evidenceObject);
- }
- }
-
- m_assemblyList = null;
- }
-#pragma warning restore 618
- }
-
- // see code:System.Security.Policy.Evidence#EvidenceLock
- m_evidenceLock = new ReaderWriterLock();
- }
-#endif // FEATURE_SERIALIZATION
-
- /// <summary>
- /// Load any serialized evidence out of the target assembly into our evidence collection.
- ///
- /// We allow entry to this method with only a reader lock held, since most of the time we will
- /// not need to write to the evidence dictionary. If we haven't yet deserialized the target
- /// evidence, then we will upgrade to a writer lock at that point.
- /// </summary>
- private void DeserializeTargetEvidence()
- {
-#if FEATURE_SERIALIZATION
- Contract.Assert(IsReaderLockHeld || IsWriterLockHeld);
-
- if (m_target != null && !m_deserializedTargetEvidence)
- {
- bool upgradedLock = false;
- LockCookie lockCookie = new LockCookie();
- try
- {
- if (!IsWriterLockHeld)
- {
- lockCookie = UpgradeToWriterLock();
- upgradedLock = true;
- }
-
- // Set this to true here because AddAssemblyEvidenceNoLock will attempt to reenter this
- // method creating possible infinite recursion.
- m_deserializedTargetEvidence = true;
-
- foreach (EvidenceBase targetEvidence in m_target.GetFactorySuppliedEvidence())
- {
- AddAssemblyEvidenceNoLock(targetEvidence, GetEvidenceIndexType(targetEvidence), DuplicateEvidenceAction.Throw);
- }
- }
- finally
- {
- if (upgradedLock)
- DowngradeFromWriterLock(ref lockCookie);
- }
- }
-#endif // FEATURE_SERIALIZATION
- }
-
-#if FEATURE_SERIALIZATION
- /// <summary>
- /// Serialize out raw evidence objects which have already been generated, ignoring any evidence
- /// which might be present but has not yet been created for this assembly.
- ///
- /// This is used for indexing into the security policy cache, since we know that once policy is
- /// resolved, the relevent membership conditions will have checked for any applicable evidence
- /// and therefore after poliyc resolution this evidence collection will contain any evidence
- /// objects necessary to arrive at its grant set.
- /// </summary>
- [SecurityCritical]
- internal byte[] RawSerialize()
- {
- try
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- // Filter out any evidence which is not yet generated
- Dictionary<Type, EvidenceBase> generatedEvidence = new Dictionary<Type, EvidenceBase>();
- foreach (KeyValuePair<Type, EvidenceTypeDescriptor> evidenceType in m_evidence)
- {
- if (evidenceType.Value != null && evidenceType.Value.HostEvidence != null)
- {
- generatedEvidence[evidenceType.Key] = evidenceType.Value.HostEvidence;
- }
- }
-
- using (MemoryStream serializationStream = new MemoryStream())
- {
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(serializationStream, generatedEvidence);
- return serializationStream.ToArray();
- }
- }
- }
- catch (SecurityException)
- {
- // We're running in a context where it's not safe to serialize the evidence out. In this case
- // Simply decline to cache the result of the policy evaluation
- return null;
- }
- }
-#endif // FEATURE_SERIALIZATION
-
- //
- // ICollection implementation. All ICollection interface members are potentially much more
- // expensive in Arrowhead then they were downlevel. They should not be used if the standard Get and
- // Add methods will work instead.
- //
-
- [Obsolete("Evidence should not be treated as an ICollection. Please use the GetHostEnumerator and GetAssemblyEnumerator methods rather than using CopyTo.")]
- public void CopyTo(Array array, int index)
- {
- if (array == null)
- throw new ArgumentNullException("array");
- if (index < 0 || index > array.Length - Count)
- throw new ArgumentOutOfRangeException("index");
- Contract.EndContractBlock();
-
- int currentIndex = index;
-
- IEnumerator hostEnumerator = GetHostEnumerator();
- while (hostEnumerator.MoveNext())
- {
- array.SetValue(hostEnumerator.Current, currentIndex);
- ++currentIndex;
- }
-
- IEnumerator assemblyEnumerator = GetAssemblyEnumerator();
- while (assemblyEnumerator.MoveNext())
- {
- array.SetValue(assemblyEnumerator.Current, currentIndex);
- ++currentIndex;
- }
- }
-
- public IEnumerator GetHostEnumerator()
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- return new EvidenceEnumerator(this, EvidenceEnumerator.Category.Host);
- }
- }
-
- public IEnumerator GetAssemblyEnumerator()
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- DeserializeTargetEvidence();
- return new EvidenceEnumerator(this, EvidenceEnumerator.Category.Assembly);
- }
- }
-
- /// <summary>
- /// Get an enumerator that can iterate over the raw evidence objects stored for the assembly
- /// </summary>
- internal RawEvidenceEnumerator GetRawAssemblyEvidenceEnumerator()
- {
- Contract.Assert(IsReaderLockHeld);
- DeserializeTargetEvidence();
- return new RawEvidenceEnumerator(this, new List<Type>(m_evidence.Keys), false);
- }
-
- /// <summary>
- /// Get an enumerator that can iterate over the raw evidence objects stored for the host
- /// </summary>
- /// <returns></returns>
- internal RawEvidenceEnumerator GetRawHostEvidenceEnumerator()
- {
- Contract.Assert(IsReaderLockHeld);
- return new RawEvidenceEnumerator(this, new List<Type>(m_evidence.Keys), true);
- }
-
- [Obsolete("GetEnumerator is obsolete. Please use GetAssemblyEnumerator and GetHostEnumerator instead.")]
- public IEnumerator GetEnumerator()
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- return new EvidenceEnumerator(this, EvidenceEnumerator.Category.Host | EvidenceEnumerator.Category.Assembly);
- }
- }
-
- /// <summary>
- /// Get a specific type of assembly supplied evidence
- /// </summary>
- [ComVisible(false)]
- public T GetAssemblyEvidence<T>() where T : EvidenceBase
- {
- return UnwrapEvidence(GetAssemblyEvidence(typeof(T))) as T;
- }
-
- internal EvidenceBase GetAssemblyEvidence(Type type)
- {
- Contract.Assert(type != null);
-
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- return GetAssemblyEvidenceNoLock(type);
- }
- }
-
- private EvidenceBase GetAssemblyEvidenceNoLock(Type type)
- {
- Contract.Assert(IsReaderLockHeld || IsWriterLockHeld);
- Contract.Assert(type != null);
-
- DeserializeTargetEvidence();
- EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(type);
- if (descriptor != null)
- {
- return descriptor.AssemblyEvidence;
- }
-
- return null;
- }
-
- /// <summary>
- /// Get a specific type of host supplied evidence
- /// </summary>
- [ComVisible(false)]
- public T GetHostEvidence<T>() where T : EvidenceBase
- {
- return UnwrapEvidence(GetHostEvidence(typeof(T))) as T;
- }
-
- /// <summary>
- /// Get a specific type of evidence from the host which may not have been verified yet. If the
- /// evidence was not verified, then don't mark it as being used yet.
- /// </summary>
- internal T GetDelayEvaluatedHostEvidence<T>() where T : EvidenceBase, IDelayEvaluatedEvidence
- {
- return UnwrapEvidence(GetHostEvidence(typeof(T), false)) as T;
- }
-
- internal EvidenceBase GetHostEvidence(Type type)
- {
- Contract.Assert(type != null);
-
- return GetHostEvidence(type, true);
- }
-
- [SecuritySafeCritical]
- private EvidenceBase GetHostEvidence(Type type, bool markDelayEvaluatedEvidenceUsed)
- {
- Contract.Assert(type != null);
-
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- EvidenceBase evidence = GetHostEvidenceNoLock(type);
-
- if (markDelayEvaluatedEvidenceUsed)
- {
- IDelayEvaluatedEvidence delayEvidence = evidence as IDelayEvaluatedEvidence;
- if (delayEvidence != null)
- {
- delayEvidence.MarkUsed();
- }
- }
-
- return evidence;
- }
- }
-
- /// <summary>
- /// Get host supplied evidence from the collection
- ///
- /// We attempt to find host evdience in the following order:
- ///
- /// 1. Already generated or explicitly supplied evidence
- /// 2. Evidence supplied by the CLR host
- /// 3. Evidence supplied by the CLR itself
- /// </summary>
- [SecurityCritical]
- private EvidenceBase GetHostEvidenceNoLock(Type type)
- {
- Contract.Assert(IsReaderLockHeld || IsWriterLockHeld);
- Contract.Assert(type != null);
-
- EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(type);
-
- // If the evidence descriptor doesn't exist for the host evidence type than the evidence doesn't
- // exist and neither the host nor the runtime can produce it.
- if (descriptor == null)
- {
- return null;
- }
-
- // If the evidence has already been generated or if it was explicitly provided then return that
- if (descriptor.HostEvidence != null)
- {
- return descriptor.HostEvidence;
- }
-
- // If we have a target, then the host or the runtime might be able to generate this type of
- // evidence on demand.
- if (m_target != null && !descriptor.Generated)
- {
- using (EvidenceUpgradeLockHolder lockHolder = new EvidenceUpgradeLockHolder(this))
- {
- // Make sure that we don't attempt to generate this type of evidencea again if we fail to
- // generate it now.
- descriptor.Generated = true;
-
- EvidenceBase generatedEvidence = GenerateHostEvidence(type, descriptor.HostCanGenerate);
- if (generatedEvidence != null)
- {
- descriptor.HostEvidence = generatedEvidence;
-
- //
- // #BackpatchGeneratedEvidence
- //
- // If we were cloned from another evidence collection propigate any generated evidence
- // back to the original collection. Since Assembly and AppDomain both clone their
- // evidence before giving it to users, this prevents us from having to regenerate
- // evidence types on each clone that gets created. Note that we do not want to do this
- // backpatching if the origin already has evidence of this type or if it has had
- // this type of evidence removed from its collection.
- //
-
- Evidence cloneOrigin = m_cloneOrigin != null ? m_cloneOrigin.Target as Evidence : null;
- if (cloneOrigin != null)
- {
- BCLDebug.Assert(cloneOrigin.Target != null && cloneOrigin.Target == Target,
- "Attempt to backpatch evidence to a collection with a different target.");
-
- using (EvidenceLockHolder cloneLockHolder = new EvidenceLockHolder(cloneOrigin, EvidenceLockHolder.LockType.Writer))
- {
- EvidenceTypeDescriptor cloneDescriptor = cloneOrigin.GetEvidenceTypeDescriptor(type);
- if (cloneDescriptor != null && cloneDescriptor.HostEvidence == null)
- {
- cloneDescriptor.HostEvidence = generatedEvidence.Clone() as EvidenceBase;
- }
- }
- }
-
- }
-
- return generatedEvidence;
- }
- }
-
- // The evidence could not be generated and was not found
- return null;
- }
-
- /// <summary>
- /// Attempt to generate host evidence on demand via calls to the runtime host or the evidence facotry
- /// </summary>
- [SecurityCritical]
- private EvidenceBase GenerateHostEvidence(Type type, bool hostCanGenerate)
- {
- Contract.Assert(type != null);
- Contract.Assert(IsWriterLockHeld);
-
-#if FEATURE_CAS_POLICY
- // First let the host generate the evidence if it can.
- if (hostCanGenerate)
- {
- AppDomain targetDomain = m_target.Target as AppDomain;
- Assembly targetAssembly = m_target.Target as Assembly;
-
- EvidenceBase hostEvidence = null;
- if (targetDomain != null)
- {
- hostEvidence = AppDomain.CurrentDomain.HostSecurityManager.GenerateAppDomainEvidence(type);
- }
- else if (targetAssembly != null)
- {
- hostEvidence = AppDomain.CurrentDomain.HostSecurityManager.GenerateAssemblyEvidence(type, targetAssembly);
- }
-
- // If the host generated the evidence, verify that it generated the evidence we expected
- // and use that.
- if (hostEvidence != null)
- {
- if (!type.IsAssignableFrom(hostEvidence.GetType()))
- {
- string hostType = AppDomain.CurrentDomain.HostSecurityManager.GetType().FullName;
- string recievedType = hostEvidence.GetType().FullName;
- string requestedType = type.FullName;
-
- throw new InvalidOperationException(Environment.GetResourceString("Policy_IncorrectHostEvidence", hostType, recievedType, requestedType));
- }
-
- return hostEvidence;
- }
- }
-#endif // FEATURE_CAS_POLICY
-
- // Finally, check to see if the CLR can generate the evidence
- return m_target.GenerateEvidence(type);
- }
-
- [Obsolete("Evidence should not be treated as an ICollection. Please use GetHostEnumerator and GetAssemblyEnumerator to iterate over the evidence to collect a count.")]
- public int Count
- {
- get
- {
- int count = 0;
-
- IEnumerator hostEvidence = GetHostEnumerator();
- while (hostEvidence.MoveNext())
- {
- ++count;
- }
-
- IEnumerator assemblyEvidence = GetAssemblyEnumerator();
- while (assemblyEvidence.MoveNext())
- {
- ++count;
- }
-
- return count;
- }
- }
-
- /// <summary>
- /// Get the number of pieces of evidence which are currently generated, without causing any
- /// lazily generated evidence to be created.
- /// </summary>
- [ComVisible(false)]
- internal int RawCount
- {
- get
- {
- int count = 0;
-
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- foreach (Type evidenceType in new List<Type>(m_evidence.Keys))
- {
- EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(evidenceType);
-
- if (descriptor != null)
- {
- if (descriptor.AssemblyEvidence != null)
- {
- ++count;
- }
- if (descriptor.HostEvidence != null)
- {
- ++count;
- }
- }
- }
- }
-
- return count;
- }
- }
-
- public Object SyncRoot
- {
- get { return this; }
- }
-
- public bool IsSynchronized
- {
- get { return true; }
- }
-
- public bool IsReadOnly
- {
- get { return false; }
- }
-
-#if FEATURE_CAS_POLICY
- [ComVisible(false)]
- public Evidence Clone()
- {
- return new Evidence(this);
- }
-#endif // FEATURE_CAS_POLICY
-
- [ComVisible(false)]
- [SecuritySafeCritical]
- public void Clear()
- {
- if (Locked)
- {
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
- }
-
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer))
- {
- ++m_version;
- m_evidence.Clear();
- }
- }
-
- [ComVisible(false)]
- [SecuritySafeCritical]
- public void RemoveType(Type t)
- {
- if (t == null)
- throw new ArgumentNullException("t");
- Contract.EndContractBlock();
-
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer))
- {
- EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(t);
- if (descriptor != null)
- {
- ++m_version;
-
- // If we've locked this evidence collection, we need to do the lock check in the case that
- // either we have host evidence, or that the host might generate it, since removing the
- // evidence will cause us to bypass the host's ability to ever generate the evidence.
- if (Locked && (descriptor.HostEvidence != null || descriptor.HostCanGenerate))
- {
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
- }
-
- m_evidence.Remove(t);
- }
- }
- }
-
- /// <summary>
- /// Mark all of the already generated evidence in the collection as having been used during a
- /// policy evaluation.
- /// </summary>
- internal void MarkAllEvidenceAsUsed()
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- foreach (KeyValuePair<Type, EvidenceTypeDescriptor> evidenceType in m_evidence)
- {
- if (evidenceType.Value != null)
- {
- IDelayEvaluatedEvidence hostEvidence = evidenceType.Value.HostEvidence as IDelayEvaluatedEvidence;
- if (hostEvidence != null)
- {
- hostEvidence.MarkUsed();
- }
-
- IDelayEvaluatedEvidence assemblyEvidence = evidenceType.Value.AssemblyEvidence as IDelayEvaluatedEvidence;
- if (assemblyEvidence != null)
- {
- assemblyEvidence.MarkUsed();
- }
- }
- }
- }
- }
-
-#if FEATURE_CAS_POLICY
- /// <summary>
- /// Determine if delay evaluated strong name evidence is contained in this collection, and if so
- /// if it was used during policy evaluation.
- ///
- /// This method is called from the VM in SecurityPolicy::WasStrongNameEvidenceUsed
- /// This class should be used as an adapter layer to allow the public facing EvidenceEnumerator to
- /// be able to get the evidence values out of an Evidence class. It is tightly coupled with the
- /// internal data structures holding the evidence objects in the Evidence class.
- /// </summary>
- private bool WasStrongNameEvidenceUsed()
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader))
- {
- EvidenceTypeDescriptor snTypeDescriptor = GetEvidenceTypeDescriptor(typeof(StrongName));
- if (snTypeDescriptor != null)
- {
- IDelayEvaluatedEvidence snEvidence = snTypeDescriptor.HostEvidence as IDelayEvaluatedEvidence;
- return snEvidence != null && snEvidence.WasUsed;
- }
-
- return false;
- }
- }
-#endif // FEATURE_CAS_POLICY
-
- /// <summary>
- /// Utility class to wrap acquiring a lock onto the evidence collection
- /// </summary>
- private class EvidenceLockHolder : IDisposable
- {
- private Evidence m_target;
- private LockType m_lockType;
-
- public enum LockType
- {
- Reader,
- Writer
- }
-
- public EvidenceLockHolder(Evidence target, LockType lockType)
- {
- Contract.Assert(target != null);
- Contract.Assert(lockType == LockType.Reader || lockType == LockType.Writer);
-
- m_target = target;
- m_lockType = lockType;
-
- if (m_lockType == LockType.Reader)
- {
- m_target.AcquireReaderLock();
- }
- else
- {
- m_target.AcquireWriterlock();
- }
- }
-
- public void Dispose()
- {
- if (m_lockType == LockType.Reader && m_target.IsReaderLockHeld)
- {
- m_target.ReleaseReaderLock();
- }
- else if (m_lockType == LockType.Writer && m_target.IsWriterLockHeld)
- {
- m_target.ReleaseWriterLock();
- }
- }
- }
-
- /// <summary>
- /// Utility class to wrap upgrading an acquired reader lock to a writer lock and then
- /// downgrading it back to a reader lock.
- /// </summary>
- private class EvidenceUpgradeLockHolder : IDisposable
- {
- private Evidence m_target;
- private LockCookie m_cookie;
-
- public EvidenceUpgradeLockHolder(Evidence target)
- {
- Contract.Assert(target != null);
-
- m_target = target;
- m_cookie = m_target.UpgradeToWriterLock();
- }
-
- public void Dispose()
- {
- if (m_target.IsWriterLockHeld)
- {
- m_target.DowngradeFromWriterLock(ref m_cookie);
- }
- }
- }
-
- /// <summary>
- /// Enumerator that iterates directly over the evidence type map, returning back the evidence objects
- /// that are contained in it. This enumerator will generate any lazy evaluated evidence it finds,
- /// but it does not attempt to deal with legacy evidence adapters.
- ///
- /// This class should be used as an adapter layer to allow the public facing EvidenceEnumerator to
- /// be able to get the evidence values out of an Evidence class. It is tightly coupled with the
- /// internal data structures holding the evidence objects in the Evidence class.
- /// </summary>
- internal sealed class RawEvidenceEnumerator : IEnumerator<EvidenceBase>
- {
- private Evidence m_evidence;
- private bool m_hostEnumerator; // true to enumerate host evidence, false to enumerate assembly evidence
- private uint m_evidenceVersion;
-
- private Type[] m_evidenceTypes;
- private int m_typeIndex;
- private EvidenceBase m_currentEvidence;
-
- private static volatile List<Type> s_expensiveEvidence;
-
- public RawEvidenceEnumerator(Evidence evidence, IEnumerable<Type> evidenceTypes, bool hostEnumerator)
- {
- Contract.Assert(evidence != null);
- Contract.Assert(evidenceTypes != null);
-
- m_evidence = evidence;
- m_hostEnumerator = hostEnumerator;
- m_evidenceTypes = GenerateEvidenceTypes(evidence, evidenceTypes, hostEnumerator);
- m_evidenceVersion = evidence.m_version;
-
- Reset();
- }
-
- public EvidenceBase Current
- {
- get
- {
- if (m_evidence.m_version != m_evidenceVersion)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
-
- return m_currentEvidence;
- }
- }
-
- object IEnumerator.Current
- {
- get
- {
- if (m_evidence.m_version != m_evidenceVersion)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
-
- return m_currentEvidence;
- }
- }
-
- /// <summary>
- /// List of types of evidence that we would like to avoid generating if possible
- /// </summary>
- private static List<Type> ExpensiveEvidence
- {
- get
- {
- if (s_expensiveEvidence == null)
- {
- List<Type> expensiveEvidence = new List<Type>();
-#if FEATURE_CAS_POLICY
- expensiveEvidence.Add(typeof(Hash));
- expensiveEvidence.Add(typeof(Publisher));
-#endif // FEATURE_CAS_POLICY
- s_expensiveEvidence = expensiveEvidence;
-
-#if _DEBUG
- List<Type> runtimeTypes = new List<Type>(Evidence.RuntimeEvidenceTypes);
- foreach (Type expensiveType in s_expensiveEvidence)
- {
- BCLDebug.Assert(runtimeTypes.Contains(expensiveType),
- "Evidence type not generated by the runtime found in expensive evidence type list");
- }
-#endif // _DEBUG
- }
-
- return s_expensiveEvidence;
- }
- }
-
- public void Dispose()
- {
- return;
- }
-
- /// <summary>
- /// Generate the array of types of evidence that could have values for
- /// </summary>
- private static Type[] GenerateEvidenceTypes(Evidence evidence,
- IEnumerable<Type> evidenceTypes,
- bool hostEvidence)
- {
- Contract.Assert(evidence != null);
- Contract.Assert(evidenceTypes != null);
-
- //
- // Sort the evidence being generated into three categories, which we enumerate in order:
- // 1. Evidence which has already been generated
- // 2. Evidence which is relatively inexpensive to generate
- // 3. Evidence which is expensive to generate.
- //
- // This allows us to be as efficient as possible in case the user of the enumerator stops the
- // enumeration before we step up to the next more expensive category.
- //
-
- List<Type> alreadyGeneratedList = new List<Type>();
- List<Type> inexpensiveList = new List<Type>();
- List<Type> expensiveList = new List<Type>(ExpensiveEvidence.Count);
-
- // Iterate over the evidence types classifying into the three groups. We need to copy the list
- // here since GetEvidenceTypeDescriptor will potentially update the evidence dictionary, which
- // evidenceTypes iterates over.
- foreach (Type evidenceType in evidenceTypes)
- {
- EvidenceTypeDescriptor descriptor = evidence.GetEvidenceTypeDescriptor(evidenceType);
- BCLDebug.Assert(descriptor != null, "descriptor != null");
-
- bool alreadyGenerated = (hostEvidence && descriptor.HostEvidence != null) ||
- (!hostEvidence && descriptor.AssemblyEvidence != null);
-
- if (alreadyGenerated)
- {
- alreadyGeneratedList.Add(evidenceType);
- }
- else if (ExpensiveEvidence.Contains(evidenceType))
- {
- expensiveList.Add(evidenceType);
- }
- else
- {
- inexpensiveList.Add(evidenceType);
- }
- }
-
- Type[] enumerationTypes = new Type[alreadyGeneratedList.Count + inexpensiveList.Count + expensiveList.Count];
- alreadyGeneratedList.CopyTo(enumerationTypes, 0);
- inexpensiveList.CopyTo(enumerationTypes, alreadyGeneratedList.Count);
- expensiveList.CopyTo(enumerationTypes, alreadyGeneratedList.Count + inexpensiveList.Count);
-
- return enumerationTypes;
- }
-
- [SecuritySafeCritical]
- public bool MoveNext()
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(m_evidence, EvidenceLockHolder.LockType.Reader))
- {
- if (m_evidence.m_version != m_evidenceVersion)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
-
- m_currentEvidence = null;
-
- // Iterate over the possible types of evidence that we could have until we find one that
- // really exists, or we run out of posibilities.
- do
- {
- ++m_typeIndex;
-
- if (m_typeIndex < m_evidenceTypes.Length)
- {
- if (m_hostEnumerator)
- {
- m_currentEvidence = m_evidence.GetHostEvidenceNoLock(m_evidenceTypes[m_typeIndex]);
- }
- else
- {
- m_currentEvidence = m_evidence.GetAssemblyEvidenceNoLock(m_evidenceTypes[m_typeIndex]);
- }
- }
- }
- while (m_typeIndex < m_evidenceTypes.Length && m_currentEvidence == null);
- }
-
- return m_currentEvidence != null;
- }
-
- public void Reset()
- {
- if (m_evidence.m_version != m_evidenceVersion)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
-
- m_typeIndex = -1;
- m_currentEvidence = null;
- }
- }
-
- private sealed class EvidenceEnumerator : IEnumerator
- {
- private Evidence m_evidence;
- private Category m_category;
- private Stack m_enumerators;
-
- private object m_currentEvidence;
-
- [Flags]
- internal enum Category
- {
- Host = 0x1, // Enumerate only host supplied evidence
- Assembly = 0x2 // Enumerate only assembly supplied evidence
- }
-
- internal EvidenceEnumerator(Evidence evidence, Category category)
- {
- Contract.Assert(evidence != null);
- Contract.Assert(evidence.IsReaderLockHeld);
-
- m_evidence = evidence;
- m_category = category;
- ResetNoLock();
- }
-
- public bool MoveNext()
- {
- IEnumerator currentEnumerator = CurrentEnumerator;
-
- // No more enumerators means we can't go any further
- if (currentEnumerator == null)
- {
- m_currentEvidence = null;
- return false;
- }
-
- // See if the current enumerator can continue
- if (currentEnumerator.MoveNext())
- {
- //
- // If we've found an adapter for legacy evidence, we need to unwrap it for it to be the
- // current enumerator's value. For wrapped evidence, this is a simple unwrap, for a list of
- // evidence, we need to make that the current enumerator and get its first value.
- //
-
- LegacyEvidenceWrapper legacyWrapper = currentEnumerator.Current as LegacyEvidenceWrapper;
- LegacyEvidenceList legacyList = currentEnumerator.Current as LegacyEvidenceList;
-
- if (legacyWrapper != null)
- {
- m_currentEvidence = legacyWrapper.EvidenceObject;
- }
- else if (legacyList != null)
- {
- IEnumerator legacyListEnumerator = legacyList.GetEnumerator();
- m_enumerators.Push(legacyListEnumerator);
- MoveNext();
- }
- else
- {
- m_currentEvidence = currentEnumerator.Current;
- }
-
- BCLDebug.Assert(m_currentEvidence != null, "m_currentEvidence != null");
- return true;
- }
- else
- {
- // If we've reached the end of the current enumerator, move to the next one and try again
- m_enumerators.Pop();
- return MoveNext();
- }
- }
-
- public object Current
- {
- get { return m_currentEvidence; }
- }
-
- private IEnumerator CurrentEnumerator
- {
- get
- {
- return m_enumerators.Count > 0 ? m_enumerators.Peek() as IEnumerator : null;
- }
- }
-
- public void Reset()
- {
- using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(m_evidence, EvidenceLockHolder.LockType.Reader))
- {
- ResetNoLock();
- }
- }
-
- private void ResetNoLock()
- {
- Contract.Assert(m_evidence != null);
- Contract.Assert(m_evidence.IsReaderLockHeld);
-
- m_currentEvidence = null;
- m_enumerators = new Stack();
-
- if ((m_category & Category.Host) == Category.Host)
- {
- m_enumerators.Push(m_evidence.GetRawHostEvidenceEnumerator());
- }
- if ((m_category & Category.Assembly) == Category.Assembly)
- {
- m_enumerators.Push(m_evidence.GetRawAssemblyEvidenceEnumerator());
- }
- }
- }
-#endif //!FEATURE_CORECLR && FEATURE_RWLOCK
}
}
diff --git a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs b/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs
index f142ebea2a..7fef1ded3c 100644
--- a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs
+++ b/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs
@@ -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();
diff --git a/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs b/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs
index bccf39218b..8deb145102 100644
--- a/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs
+++ b/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs
@@ -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;
}
diff --git a/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs b/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs
index 5bd36485db..8f8c07c9e4 100644
--- a/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs
+++ b/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs
@@ -18,7 +18,6 @@ namespace System.Security.Policy {
/// </summary>
bool IsVerified
{
- [System.Security.SecurityCritical]
get;
}
diff --git a/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs b/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs
index 72c07d1246..9b58ece9f1 100644
--- a/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs
+++ b/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs
@@ -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( "et" );
-
- if (!et.Tag.Equals( "PolicyStatement" ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ), "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( "doc" );
- Contract.EndContractBlock();
-
- if (!doc.GetTagForElement( position ).Equals( "PolicyStatement" ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ), "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 )
{
diff --git a/src/mscorlib/src/System/Security/Policy/Site.cs b/src/mscorlib/src/System/Security/Policy/Site.cs
index e7c6cd3d83..14a95e1666 100644
--- a/src/mscorlib/src/System/Security/Policy/Site.cs
+++ b/src/mscorlib/src/System/Security/Policy/Site.cs
@@ -10,6 +10,7 @@
//
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Security.Permissions;
@@ -26,7 +27,7 @@ namespace System.Security.Policy
public Site(String name)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
m_name = new SiteString( name );
@@ -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()
diff --git a/src/mscorlib/src/System/Security/Policy/StrongName.cs b/src/mscorlib/src/System/Security/Policy/StrongName.cs
index c49f2b0674..999b478ba7 100644
--- a/src/mscorlib/src/System/Security/Policy/StrongName.cs
+++ b/src/mscorlib/src/System/Security/Policy/StrongName.cs
@@ -42,20 +42,20 @@ namespace System.Security.Policy {
internal StrongName(StrongNamePublicKeyBlob blob, String name, Version version, Assembly assembly)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (String.IsNullOrEmpty(name))
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyStrongName"));
if (blob == null)
- throw new ArgumentNullException("blob");
+ throw new ArgumentNullException(nameof(blob));
if (version == null)
- throw new ArgumentNullException("version");
+ throw new ArgumentNullException(nameof(version));
Contract.EndContractBlock();
RuntimeAssembly rtAssembly = assembly as RuntimeAssembly;
if (assembly != null && rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "assembly");
+ throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(assembly));
m_publicKeyBlob = blob;
m_name = name;
@@ -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("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);
diff --git a/src/mscorlib/src/System/Security/Policy/URL.cs b/src/mscorlib/src/System/Security/Policy/URL.cs
index d3ad4f8724..3541124ac6 100644
--- a/src/mscorlib/src/System/Security/Policy/URL.cs
+++ b/src/mscorlib/src/System/Security/Policy/URL.cs
@@ -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]
@@ -25,7 +26,7 @@ namespace System.Security.Policy {
internal Url( String name, bool parsed )
{
if (name == null)
- throw new ArgumentNullException( "name" );
+ throw new ArgumentNullException( nameof(name) );
Contract.EndContractBlock();
m_url = new URLString( name, parsed );
@@ -34,7 +35,7 @@ namespace System.Security.Policy {
public Url( String name )
{
if (name == null)
- throw new ArgumentNullException( "name" );
+ throw new ArgumentNullException( nameof(name) );
Contract.EndContractBlock();
m_url = new URLString( name );
@@ -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()
diff --git a/src/mscorlib/src/System/Security/Policy/Zone.cs b/src/mscorlib/src/System/Security/Policy/Zone.cs
index c999abe340..a9f5d84aeb 100644
--- a/src/mscorlib/src/System/Security/Policy/Zone.cs
+++ b/src/mscorlib/src/System/Security/Policy/Zone.cs
@@ -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( "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()
diff --git a/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs b/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs
index fa77ac50f9..9eec46f774 100644
--- a/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs
+++ b/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs
@@ -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,
diff --git a/src/mscorlib/src/System/Security/SafeSecurityHandles.cs b/src/mscorlib/src/System/Security/SafeSecurityHandles.cs
index ea9cd4be0f..9a84164460 100644
--- a/src/mscorlib/src/System/Security/SafeSecurityHandles.cs
+++ b/src/mscorlib/src/System/Security/SafeSecurityHandles.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Security/SecurityContext.cs b/src/mscorlib/src/System/Security/SecurityContext.cs
index e422a312df..674c04196f 100644
--- a/src/mscorlib/src/System/Security/SecurityContext.cs
+++ b/src/mscorlib/src/System/Security/SecurityContext.cs
@@ -12,14 +12,11 @@
**
===========================================================*/
namespace System.Security
-{
+{
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Threading;
using System.Runtime.Remoting;
-#if FEATURE_IMPERSONATION
- using System.Security.Principal;
-#endif
using System.Collections;
using System.Runtime.Serialization;
using System.Security.Permissions;
@@ -30,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
@@ -46,15 +44,6 @@ namespace System.Security
All = 0x3FFF
}
-#if FEATURE_IMPERSONATION
- internal enum WindowsImpersonationFlowMode {
- IMP_FASTFLOW = 0,
- IMP_NOFLOW = 1,
- IMP_ALWAYSFLOW = 2,
- IMP_DEFAULT = IMP_FASTFLOW
- }
-#endif
-
#if FEATURE_COMPRESSEDSTACK
internal struct SecurityContextSwitcher: IDisposable
{
@@ -62,17 +51,12 @@ namespace System.Security
internal SecurityContext currSC; //current SC - SetSecurityContext that created the switcher set this on the Thread
internal ExecutionContext currEC; // current ExecutionContext on Thread
internal CompressedStackSwitcher cssw;
-#if FEATURE_IMPERSONATION
- internal WindowsImpersonationContext wic;
-#endif
- [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]
@@ -90,7 +74,6 @@ namespace System.Security
return true;
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
@@ -104,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();
@@ -113,26 +96,13 @@ 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
bool bNoException = true;
-#if FEATURE_IMPERSONATION
- try
- {
- if (wic != null)
- bNoException &= wic.UndoNoThrow();
- }
- catch
- {
- // Failfast since we can't continue safely...
- bNoException &= cssw.UndoNoThrow();
- System.Environment.FailFast(Environment.GetResourceString("ExecutionContext_UndoFailed"));
-
- }
-#endif
+
bNoException &= cssw.UndoNoThrow();
@@ -144,15 +114,9 @@ namespace System.Security
}
}
-
public sealed class SecurityContext : IDisposable
{
-#if FEATURE_IMPERSONATION
- // Note that only one of the following variables will be true. The way we set up the flow mode in the g_pConfig guarantees this.
- static bool _LegacyImpersonationPolicy = (GetImpersonationFlowMode() == WindowsImpersonationFlowMode.IMP_NOFLOW);
- static bool _alwaysFlowImpersonationPolicy = (GetImpersonationFlowMode() == WindowsImpersonationFlowMode.IMP_ALWAYSFLOW);
-#endif
/*=========================================================================
** Data accessed from managed code that needs to be defined in
** SecurityContextObject to maintain alignment between the two classes.
@@ -160,9 +124,6 @@ namespace System.Security
=========================================================================*/
private ExecutionContext _executionContext;
-#if FEATURE_IMPERSONATION
- private volatile WindowsIdentity _windowsIdentity;
-#endif
private volatile CompressedStack _compressedStack;
static private volatile SecurityContext _fullTrustSC;
@@ -204,7 +165,6 @@ namespace System.Security
static internal SecurityContext FullTrustSecurityContext
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (_fullTrustSC == null)
@@ -222,27 +182,7 @@ namespace System.Security
_executionContext = value;
}
}
-
-#if FEATURE_IMPERSONATION
-
-
- internal WindowsIdentity WindowsIdentity
- {
- get
- {
- return _windowsIdentity;
- }
- set
- {
- // Note, we do not dispose of the existing windows identity, since some code such as remoting
- // relies on reusing that identity. If you are not going to reuse the existing identity, then
- // you should dispose of the existing identity before resetting it.
- _windowsIdentity = value;
- }
- }
-#endif // FEATURE_IMPERSONATION
-
internal CompressedStack CompressedStack
{
get
@@ -258,25 +198,18 @@ namespace System.Security
public void Dispose()
{
-#if FEATURE_IMPERSONATION
- if (_windowsIdentity != null)
- _windowsIdentity.Dispose();
-#endif // FEATURE_IMPERSONATION
}
- [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))
@@ -292,7 +225,6 @@ namespace System.Security
return afc;
}
- [SecuritySafeCritical]
public static void RestoreFlow()
{
SecurityContext sc = Thread.CurrentThread.GetMutableExecutionContext().SecurityContext;
@@ -307,13 +239,7 @@ namespace System.Security
{
return SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.All);
}
-#if FEATURE_IMPERSONATION
- public static bool IsWindowsIdentityFlowSuppressed()
- {
- return (_LegacyImpersonationPolicy|| SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.WI));
- }
-#endif
- [SecuritySafeCritical]
+
internal static bool IsFlowSuppressed(SecurityContextDisableFlow flags)
{
return Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsFlowSuppressed(flags);
@@ -323,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)
@@ -360,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
@@ -369,7 +294,6 @@ namespace System.Security
}
}
- [System.Security.SecurityCritical] // auto-generated
internal static void RunInternal(SecurityContext securityContext, ContextCallback callBack, Object state)
{
if (cleanupCode == null)
@@ -397,7 +321,6 @@ namespace System.Security
}
}
- [System.Security.SecurityCritical] // auto-generated
static internal void runTryCode(Object userData)
{
SecurityContextRunData rData = (SecurityContextRunData) userData;
@@ -406,7 +329,6 @@ namespace System.Security
}
- [System.Security.SecurityCritical] // auto-generated
[PrePrepareMethod]
static internal void runFinallyCode(Object userData, bool exceptionThrown)
{
@@ -421,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)
@@ -430,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
@@ -458,22 +378,6 @@ namespace System.Security
RuntimeHelpers.PrepareConstrainedRegions();
try
{
-#if FEATURE_IMPERSONATION
- scsw.wic = null;
- if (!_LegacyImpersonationPolicy)
- {
- if (sc.WindowsIdentity != null)
- {
- scsw.wic = sc.WindowsIdentity.Impersonate(ref stackMark);
- }
- else if ( ((_capturedFlowState & SecurityContextDisableFlow.WI) == 0)
- && prevSecurityContext.WindowsIdentity != null)
- {
- // revert impersonation if there was no WI flow supression at capture and we're currently impersonating
- scsw.wic = WindowsIdentity.SafeRevertToSelf(ref stackMark);
- }
- }
-#endif
scsw.cssw = CompressedStack.SetCompressedStack(sc.CompressedStack, prevSecurityContext.CompressedStack);
}
catch
@@ -486,7 +390,6 @@ namespace System.Security
}
/// <internalonly/>
- [System.Security.SecuritySafeCritical] // auto-generated
public SecurityContext CreateCopy()
{
if (!isNewCapture)
@@ -498,11 +401,6 @@ namespace System.Security
sc.isNewCapture = true;
sc._disableFlow = _disableFlow;
-#if FEATURE_IMPERSONATION
- if (WindowsIdentity != null)
- sc._windowsIdentity = new WindowsIdentity(WindowsIdentity.AccessToken);
-#endif //FEATURE_IMPERSONATION
-
if (_compressedStack != null)
sc._compressedStack = _compressedStack.CreateCopy();
@@ -510,26 +408,19 @@ 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;
-#if FEATURE_IMPERSONATION
- if (this.WindowsIdentity != null)
- sc._windowsIdentity = new WindowsIdentity(this.WindowsIdentity.AccessToken);
-#endif //FEATURE_IMPERSONATION
-
if (this._compressedStack != null)
sc._compressedStack = this._compressedStack.CreateCopy();
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( )
{
@@ -545,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)
{
@@ -560,125 +450,26 @@ 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();
sc.isNewCapture = true;
-#if FEATURE_IMPERSONATION
- // Force create WindowsIdentity
- if (!IsWindowsIdentityFlowSuppressed())
- {
- WindowsIdentity currentIdentity = GetCurrentWI(currThreadEC);
- if (currentIdentity != null)
- sc._windowsIdentity = new WindowsIdentity(currentIdentity.AccessToken);
- }
- else
- {
- sc._disableFlow = SecurityContextDisableFlow.WI;
- }
-#endif // FEATURE_IMPERSONATION
-
// Force create CompressedStack
sc.CompressedStack = CompressedStack.GetCompressedStack(ref stackMark);
return sc;
}
- [System.Security.SecurityCritical] // auto-generated
+
static internal SecurityContext CreateFullTrustSecurityContext()
{
SecurityContext sc = new SecurityContext();
sc.isNewCapture = true;
-
-#if FEATURE_IMPERSONATION
- if (IsWindowsIdentityFlowSuppressed())
- {
- sc._disableFlow = SecurityContextDisableFlow.WI;
- }
-#endif // FEATURE_IMPERSONATION
-
// Force create CompressedStack
sc.CompressedStack = new CompressedStack(null);
return sc;
}
-#if FEATURE_IMPERSONATION
-
- static internal bool AlwaysFlowImpersonationPolicy { get { return _alwaysFlowImpersonationPolicy; } }
-
- // Check to see if we have a WI on the thread and return if we do
- [System.Security.SecurityCritical] // auto-generated
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static internal WindowsIdentity GetCurrentWI(ExecutionContext.Reader threadEC)
- {
- return GetCurrentWI(threadEC, _alwaysFlowImpersonationPolicy);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static internal WindowsIdentity GetCurrentWI(ExecutionContext.Reader threadEC, bool cachedAlwaysFlowImpersonationPolicy)
- {
- Contract.Assert(cachedAlwaysFlowImpersonationPolicy == _alwaysFlowImpersonationPolicy);
- if (cachedAlwaysFlowImpersonationPolicy)
- {
- // Examine the threadtoken at the cost of a kernel call if the user has set the IMP_ALWAYSFLOW mode
- return WindowsIdentity.GetCurrentInternal(TokenAccessLevels.MaximumAllowed, true);
- }
-
- return threadEC.SecurityContext.WindowsIdentity;
- }
-
- [System.Security.SecurityCritical]
- static internal void RestoreCurrentWI(ExecutionContext.Reader currentEC, ExecutionContext.Reader prevEC, WindowsIdentity targetWI, bool cachedAlwaysFlowImpersonationPolicy)
- {
- Contract.Assert(currentEC.IsSame(Thread.CurrentThread.GetExecutionContextReader()));
- Contract.Assert(cachedAlwaysFlowImpersonationPolicy == _alwaysFlowImpersonationPolicy);
-
- // NOTE: cachedAlwaysFlowImpersonationPolicy is a perf optimization to avoid always having to access a static variable here.
- if (cachedAlwaysFlowImpersonationPolicy || prevEC.SecurityContext.WindowsIdentity != targetWI)
- {
- //
- // Either we're always flowing, or the target WI was obtained from the current EC in the first place.
- //
- Contract.Assert(_alwaysFlowImpersonationPolicy || currentEC.SecurityContext.WindowsIdentity == targetWI);
-
- RestoreCurrentWIInternal(targetWI);
- }
- }
-
- [System.Security.SecurityCritical]
- static private void RestoreCurrentWIInternal(WindowsIdentity targetWI)
- {
- int hr = Win32.RevertToSelf();
- if (hr < 0)
- Environment.FailFast(Win32Native.GetMessage(hr));
-
- if (targetWI != null)
- {
- SafeAccessTokenHandle tokenHandle = targetWI.AccessToken;
- if (tokenHandle != null && !tokenHandle.IsInvalid)
- {
- hr = Win32.ImpersonateLoggedOnUser(tokenHandle);
- if (hr < 0)
- Environment.FailFast(Win32Native.GetMessage(hr));
- }
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal bool IsDefaultFTSecurityContext()
- {
- return (WindowsIdentity == null && (CompressedStack == null || CompressedStack.CompressedStackHandle == null));
- }
- [System.Security.SecurityCritical] // auto-generated
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static internal bool CurrentlyInDefaultFTSecurityContext(ExecutionContext.Reader threadEC)
- {
- return (IsDefaultThreadSecurityInfo() && GetCurrentWI(threadEC) == null);
- }
-#else
-
internal bool IsDefaultFTSecurityContext()
{
return (CompressedStack == null || CompressedStack.CompressedStackHandle == null);
@@ -687,16 +478,9 @@ namespace System.Security
{
return (IsDefaultThreadSecurityInfo());
}
-#endif
-#if FEATURE_IMPERSONATION
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal extern static WindowsImpersonationFlowMode GetImpersonationFlowMode();
-#endif
- [System.Security.SecurityCritical] // auto-generated
+
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern static bool IsDefaultThreadSecurityInfo();
-
}
#endif // FEATURE_COMPRESSEDSTACK
}
diff --git a/src/mscorlib/src/System/Security/SecurityElement.cs b/src/mscorlib/src/System/Security/SecurityElement.cs
index aa63029422..f57665b278 100644
--- a/src/mscorlib/src/System/Security/SecurityElement.cs
+++ b/src/mscorlib/src/System/Security/SecurityElement.cs
@@ -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,23 +94,10 @@ namespace System.Security
return ((SecurityElement)this).Attribute( attributeName );
}
-//////////////
-
-#if FEATURE_CAS_POLICY
- public static SecurityElement FromString( String xml )
- {
- if (xml == null)
- throw new ArgumentNullException( "xml" );
- Contract.EndContractBlock();
-
- return new Parser( xml ).GetTopElement();
- }
-#endif // FEATURE_CAS_POLICY
-
public SecurityElement( String tag )
{
if (tag == null)
- throw new ArgumentNullException( "tag" );
+ throw new ArgumentNullException( nameof(tag) );
if (!IsValidTag( tag ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
@@ -122,7 +110,7 @@ namespace System.Security
public SecurityElement( String tag, String text )
{
if (tag == null)
- throw new ArgumentNullException( "tag" );
+ throw new ArgumentNullException( nameof(tag) );
if (!IsValidTag( tag ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
@@ -148,7 +136,7 @@ namespace System.Security
set
{
if (value == null)
- throw new ArgumentNullException( "Tag" );
+ throw new ArgumentNullException( nameof(Tag) );
if (!IsValidTag( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) );
@@ -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)
{
@@ -314,10 +302,10 @@ namespace System.Security
public void AddAttribute( String name, String value )
{
if (name == null)
- throw new ArgumentNullException( "name" );
+ throw new ArgumentNullException( nameof(name) );
if (value == null)
- throw new ArgumentNullException( "value" );
+ throw new ArgumentNullException( nameof(value) );
if (!IsValidAttributeName( name ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), name ) );
@@ -332,7 +320,7 @@ namespace System.Security
public void AddChild( SecurityElement child )
{
if (child == null)
- throw new ArgumentNullException( "child" );
+ throw new ArgumentNullException( nameof(child) );
Contract.EndContractBlock();
if (m_lChildren == null)
@@ -344,7 +332,7 @@ namespace System.Security
internal void AddChild( ISecurityElementFactory child )
{
if (child == null)
- throw new ArgumentNullException( "child" );
+ throw new ArgumentNullException( nameof(child) );
Contract.EndContractBlock();
if (m_lChildren == null)
@@ -356,7 +344,7 @@ namespace System.Security
internal void AddChildNoDuplicates( ISecurityElementFactory child )
{
if (child == null)
- throw new ArgumentNullException( "child" );
+ throw new ArgumentNullException( nameof(child) );
Contract.EndContractBlock();
if (m_lChildren == null)
@@ -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;
}
@@ -626,11 +614,6 @@ namespace System.Security
{
((StringBuilder)obj).Append( str );
}
-
- private static void ToStringHelperStreamWriter( Object obj, String str )
- {
- ((StreamWriter)obj).Write( str );
- }
public override String ToString ()
{
@@ -641,16 +624,11 @@ namespace System.Security
return sb.ToString();
}
- internal void ToWriter( StreamWriter writer )
- {
- ToString( "", writer, new ToStringHelperFunc( ToStringHelperStreamWriter ) );
- }
-
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.
@@ -679,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)
{
@@ -770,7 +748,7 @@ namespace System.Security
public String Attribute( String name )
{
if (name == null)
- throw new ArgumentNullException( "name" );
+ throw new ArgumentNullException( nameof(name) );
Contract.EndContractBlock();
// Note: we don't check for validity here because an
@@ -783,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)
{
@@ -808,7 +786,7 @@ namespace System.Security
// find the one are are asked for (matching tags)
if (tag == null)
- throw new ArgumentNullException( "tag" );
+ throw new ArgumentNullException( nameof(tag) );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
@@ -829,45 +807,13 @@ 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
// child's child, depth-first
if (strLocalName == null)
- throw new ArgumentNullException( "strLocalName" );
+ throw new ArgumentNullException( nameof(strLocalName) );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
@@ -899,7 +845,7 @@ namespace System.Security
// child's child, depth-first
if (tag == null)
- throw new ArgumentNullException( "tag" );
+ throw new ArgumentNullException( nameof(tag) );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
diff --git a/src/mscorlib/src/System/Security/SecurityException.cs b/src/mscorlib/src/System/Security/SecurityException.cs
index 9fbd8023d2..c76674cdb9 100644
--- a/src/mscorlib/src/System/Security/SecurityException.cs
+++ b/src/mscorlib/src/System/Security/SecurityException.cs
@@ -34,589 +34,60 @@ 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()
+ public SecurityException()
: base(GetResString("Arg_SecurityException"))
{
SetErrorCode(System.__HResults.COR_E_SECURITY);
}
-
- public SecurityException(String message)
- : base(message)
- {
- // This is the constructor that gets called if you Assert but don't have permission to Assert. (So don't assert in here.)
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- }
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- public SecurityException(String message, Type type )
+ public SecurityException(String message)
: 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();
+ // This is the constructor that gets called if you Assert but don't have permission to Assert. (So don't assert in here.)
SetErrorCode(System.__HResults.COR_E_SECURITY);
- m_typeOfPermissionThatFailed = type;
- m_demanded = state;
}
-#endif //FEATURE_CAS_POLICY
- public SecurityException(String message, Exception inner)
+ 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("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 )
+ internal SecurityException(PermissionSet grantedSetObj, PermissionSet refusedSetObj)
: this(){}
#pragma warning disable 618
internal SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence)
#pragma warning restore 618
: this(){}
-
+
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)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
}
- public override String ToString()
- {
- return base.ToString();
- }
-
-#endif // FEATURE_CAS_POLICY
+ public override String ToString()
+ {
+ return base.ToString();
+ }
- [System.Security.SecurityCritical] // auto-generated
private bool CanAccessSensitiveInfo()
{
bool retVal = false;
@@ -627,41 +98,46 @@ namespace System.Security
#pragma warning restore 618
retVal = true;
}
- catch(SecurityException)
+ catch (SecurityException)
{
}
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)
- throw new ArgumentNullException("info");
+ if (info == null)
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
- base.GetObjectData( info, context );
-#if FEATURE_CAS_POLICY
+ base.GetObjectData(info, context);
+ }
- 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
+ // Stubs for surface area compatibility only
+ public SecurityException(String message, Type type)
+ : base(message)
+ {
+ SetErrorCode(System.__HResults.COR_E_SECURITY);
+ PermissionType = type;
}
+
+ public SecurityException(string message, System.Type type, string state)
+ : base(message)
+ {
+ SetErrorCode(System.__HResults.COR_E_SECURITY);
+ PermissionType = type;
+ PermissionState = state;
+ }
+
+ public object Demanded { get; set; }
+ public object DenySetInstance { get; set; }
+ public System.Reflection.AssemblyName FailedAssemblyInfo { get; set; }
+ public string GrantedSet { get; set; }
+ public System.Reflection.MethodInfo Method { get; set; }
+ public string PermissionState { get; set; }
+ public System.Type PermissionType { get; set; }
+ public object PermitOnlySetInstance { get; set; }
+ public string RefusedSet { get; set; }
+ public string Url { get; set; }
}
}
diff --git a/src/mscorlib/src/System/Security/SecurityManager.cs b/src/mscorlib/src/System/Security/SecurityManager.cs
index 5c46dfcbfc..933fe0be3d 100644
--- a/src/mscorlib/src/System/Security/SecurityManager.cs
+++ b/src/mscorlib/src/System/Security/SecurityManager.cs
@@ -2,32 +2,17 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-//
//
// The SecurityManager class provides a general purpose API for interacting
// with the security system.
//
-namespace System.Security {
+namespace System.Security
+{
using System;
- using System.Security.Util;
- using System.Security.Policy;
using System.Security.Permissions;
- using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-#if FEATURE_CLICKONCE
- using System.Runtime.Hosting;
-#endif // FEATURE_CLICKONCE
- using System.Text;
- using System.Threading;
- using System.Reflection;
- using System.IO;
- using System.Globalization;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
@@ -40,504 +25,8 @@ namespace System.Security {
}
[System.Runtime.InteropServices.ComVisible(true)]
- static public class SecurityManager {
-#if FEATURE_CAS_POLICY
- private static volatile SecurityPermission executionSecurityPermission = null;
-
- private static PolicyManager polmgr = new PolicyManager();
- internal static PolicyManager PolicyManager {
- get {
- return polmgr;
- }
- }
-
- //
- // Public APIs
- //
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- [Obsolete("IsGranted is obsolete and will be removed in a future release of the .NET Framework. Please use the PermissionSet property of either AppDomain or Assembly instead.")]
- public static bool IsGranted( IPermission perm )
- {
- if (perm == null)
- return true;
-
- PermissionSet granted = null, denied = null;
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- GetGrantedPermissions( JitHelpers.GetObjectHandleOnStack(ref granted),
- JitHelpers.GetObjectHandleOnStack(ref denied),
- JitHelpers.GetStackCrawlMarkHandle(ref stackMark) );
- return granted.Contains( perm ) && (denied == null || !denied.Contains( perm ));
- }
-
- // Get a sandbox permission set that the CLR considers safe to grant an application with the given
- // evidence. Note that this API is not a policy API, but rather a host helper API so that a host can
- // determine if an application's requested permission set is reasonable. This is esentially just a
- // hard coded mapping of Zone -> Sandbox and is not configurable in any way.
- public static PermissionSet GetStandardSandbox(Evidence evidence)
- {
- if (evidence == null)
- throw new ArgumentNullException("evidence");
- Contract.EndContractBlock();
-
- //
- // The top-level switch for grant set is based upon Zone
- // MyComputer -> FullTrust
- // Intranet -> LocalIntranet
- // Trusted -> Internet
- // Internet -> Internet
- // All else -> Nothing
- //
- // Both the Internet and LocalIntranet zones can have permission set extensions applied to them
- // if there is Activation.
- //
-
- Zone zone = evidence.GetHostEvidence<Zone>();
- if (zone == null)
- {
- return new PermissionSet(PermissionState.None);
- }
-#if FEATURE_CAS_POLICY
- else if (zone.SecurityZone == SecurityZone.MyComputer)
- {
- return new PermissionSet(PermissionState.Unrestricted);
- }
- else if (zone.SecurityZone == SecurityZone.Intranet)
- {
- PermissionSet intranetGrantSet = BuiltInPermissionSets.LocalIntranet;
-
- // We also need to add in same site web and file IO permission
- PolicyStatement webPolicy =
- new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);
- PolicyStatement filePolicy =
- new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery).Resolve(evidence);
-
- if (webPolicy != null)
- {
- intranetGrantSet.InplaceUnion(webPolicy.PermissionSet);
- }
- if (filePolicy != null)
- {
- intranetGrantSet.InplaceUnion(filePolicy.PermissionSet);
- }
-
- return intranetGrantSet;
- }
- else if (zone.SecurityZone == SecurityZone.Internet ||
- zone.SecurityZone == SecurityZone.Trusted)
- {
- PermissionSet internetGrantSet = BuiltInPermissionSets.Internet;
-
- // We also need to add in same site web permission
- PolicyStatement webPolicy =
- new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);
-
- if (webPolicy != null)
- {
- internetGrantSet.InplaceUnion(webPolicy.PermissionSet);
- }
-
- return internetGrantSet;
- }
-#endif // FEATURE_CAS_POLICY
- else
- {
- return new PermissionSet(PermissionState.None);
- }
- }
-
- /// <internalonly/>
- [System.Security.SecurityCritical] // auto-generated_required
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- static public void GetZoneAndOrigin( out ArrayList zone, out ArrayList origin )
- {
- StackCrawlMark mark = StackCrawlMark.LookForMyCaller;
- CodeAccessSecurityEngine.GetZoneAndOrigin( ref mark, out zone, out origin );
- }
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )]
- [Obsolete("This method 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.")]
- static public PolicyLevel LoadPolicyLevelFromFile(string path, PolicyLevelType type)
- {
- if (path == null)
- throw new ArgumentNullException( "path" );
- Contract.EndContractBlock();
-
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- // We need to retain V1.x compatibility by throwing the same exception type.
- if (!File.InternalExists(path))
- throw new ArgumentException( Environment.GetResourceString("Argument_PolicyFileDoesNotExist"));
-
- String fullPath = Path.GetFullPath( path );
-
- FileIOPermission perm = new FileIOPermission( PermissionState.None );
- perm.AddPathList( FileIOPermissionAccess.Read, fullPath );
- perm.AddPathList( FileIOPermissionAccess.Write, fullPath );
- perm.Demand();
-
- using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
- using (StreamReader reader = new StreamReader(stream)) {
- return LoadPolicyLevelFromStringHelper(reader.ReadToEnd(), path, type);
- }
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )]
- [Obsolete("This method 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.")]
- static public PolicyLevel LoadPolicyLevelFromString(string str, PolicyLevelType type)
- {
- return LoadPolicyLevelFromStringHelper(str, null, type);
- }
-
- private static PolicyLevel LoadPolicyLevelFromStringHelper (string str, string path, PolicyLevelType type)
- {
- if (str == null)
- throw new ArgumentNullException( "str" );
- Contract.EndContractBlock();
-
- PolicyLevel level = new PolicyLevel(type, path);
-
- Parser parser = new Parser( str );
- SecurityElement elRoot = parser.GetTopElement();
- if (elRoot == null)
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "configuration" ) );
-
- SecurityElement elMscorlib = elRoot.SearchForChildByTag( "mscorlib" );
- if (elMscorlib == null)
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "mscorlib" ) );
-
- SecurityElement elSecurity = elMscorlib.SearchForChildByTag( "security" );
- if (elSecurity == null)
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "security" ) );
-
- SecurityElement elPolicy = elSecurity.SearchForChildByTag( "policy" );
- if (elPolicy == null)
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "policy" ) );
-
- SecurityElement elPolicyLevel = elPolicy.SearchForChildByTag( "PolicyLevel" );
- if (elPolicyLevel != null)
- level.FromXml( elPolicyLevel );
- else
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "PolicyLevel" ) );
-
- return level;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )]
- [Obsolete("This method 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.")]
- static public void SavePolicyLevel( PolicyLevel level )
- {
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- PolicyManager.EncodeLevel( level );
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [Obsolete("This method 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.")]
- static public PermissionSet ResolvePolicy(Evidence evidence,
- PermissionSet reqdPset,
- PermissionSet optPset,
- PermissionSet denyPset,
- out PermissionSet denied)
- {
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- return ResolvePolicy(evidence, reqdPset, optPset, denyPset, out denied, true);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [Obsolete("This method 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.")]
- static public PermissionSet ResolvePolicy(Evidence evidence)
- {
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- // If we aren't passed any evidence, just make an empty object
- if (evidence == null)
- {
- evidence = new Evidence();
- }
-
- return polmgr.Resolve(evidence);
- }
-
- [Obsolete("This method 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.")]
- static public PermissionSet ResolvePolicy( Evidence[] evidences )
- {
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- if (evidences == null || evidences.Length == 0)
- evidences = new Evidence[] { null };
-
- PermissionSet retval = ResolvePolicy( evidences[0] );
- if (retval == null)
- return null;
-
- for (int i = 1; i < evidences.Length; ++i)
- {
- retval = retval.Intersect( ResolvePolicy( evidences[i] ) );
- if (retval == null || retval.IsEmpty())
- return retval;
- }
-
- return retval;
- }
-
-#if FEATURE_CAS_POLICY
- // Determine if the current thread would require a security context capture if the security state of
- // the thread needs to be re-created at a later point in time. This can be used, for instance, if
- // sensitive data is being obtained after security demands succeed, and that data is to be cached.
- // If there is an Assert up the stack, then we wouldn't want to cache the data without capturing the
- // corresponding security context to go along with it - otherwise we risk leaking data obtained
- // under an assert to code which may no longer be running with that assert in place.
- //
- // A return value of false indicates that the CLR guarantees all of the following conditions are true:
- // 1. No partial trust AppDomains are on the stack
- // 2. No partial trust assemblies are on the stack
- // 3. There are no currently active PermitOnly or Deny modifiers on the stack
- //
- // A return value of true means only that the CLR cannot guarantee that all of the conditions are
- // true, and not that one of the conditions really is false.
- //
- // IMPORTANT: The above means is only reliable in the false return case. If we say that the thread
- // does not require a context capture, then that answer is guaranteed to be correct. However, we may
- // say that the thread does require a capture when it does not actually strictly need to capture the
- // state. This is fine, as being overly conservative when capturing context will not lead to
- // security holes; being overly agresssive in avoding the capture could lead to holes however.
- //
- // This API is SecurityCritical because its main use is to optimize away unnecessary security
- // context captures, which means that the code using it is security sensitive and needs to be audited.
- [SecurityCritical]
- public static bool CurrentThreadRequiresSecurityContextCapture()
- {
- // If we know that the thread is not made up of entirely full trust code, and that there are no
- // security stack modifiers on the thread, then there is no need to capture a security context.
- return !CodeAccessSecurityEngine.QuickCheckForAllDemands();
- }
-#endif // FEATURE_CAS_POLICY
-
- //
- // This method resolves the policy for the specified evidence, but it
- // ignores the AppDomain level even when one is available in the current policy.
- //
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [Obsolete("This method 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 PermissionSet ResolveSystemPolicy (Evidence evidence)
- {
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- if (PolicyManager.IsGacAssembly(evidence))
- {
- return new PermissionSet(PermissionState.Unrestricted);
- }
-
- return polmgr.CodeGroupResolve(evidence, true);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [Obsolete("This method 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.")]
- static public IEnumerator ResolvePolicyGroups(Evidence evidence)
- {
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- return polmgr.ResolveCodeGroups(evidence);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [Obsolete("This method 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 IEnumerator PolicyHierarchy()
- {
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- return polmgr.PolicyHierarchy();
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )]
- [Obsolete("This method 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 SavePolicy()
- {
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- polmgr.Save();
- }
-
-
- [System.Security.SecurityCritical] // auto-generated
- private static PermissionSet ResolveCasPolicy(Evidence evidence,
- PermissionSet reqdPset,
- PermissionSet optPset,
- PermissionSet denyPset,
- out PermissionSet denied,
- out int securitySpecialFlags,
- bool checkExecutionPermission)
- {
- Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled);
-
- CodeAccessPermission.Assert(true);
-
- PermissionSet granted = ResolvePolicy(evidence,
- reqdPset,
- optPset,
- denyPset,
- out denied,
- checkExecutionPermission);
-
- securitySpecialFlags = SecurityManager.GetSpecialFlags(granted, denied);
- return granted;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- static private PermissionSet ResolvePolicy(Evidence evidence,
- PermissionSet reqdPset,
- PermissionSet optPset,
- PermissionSet denyPset,
- out PermissionSet denied,
- bool checkExecutionPermission)
- {
- Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled);
-
- if (executionSecurityPermission == null)
- executionSecurityPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
-
- PermissionSet requested = null;
- PermissionSet optional;
- PermissionSet allowed;
-
- Exception savedException = null;
-
- // We don't want to recurse back into here as a result of a
- // stackwalk during resolution. So simply assert full trust (this
- // implies that custom permissions cannot use any permissions that
- // don't implement IUnrestrictedPermission.
- // PermissionSet.s_fullTrust.Assert();
-
- // The requested set is the union of the minimal request and the
- // optional request. Minimal request defaults to empty, optional
- // is "AllPossible" (includes any permission that can be defined)
- // which is symbolized by null.
- optional = optPset;
-
- if (reqdPset == null)
- requested = optional;
- else
- // If optional is null, the requested set becomes null/"AllPossible".
- requested = optional == null ? null : reqdPset.Union(optional);
-
- // Make sure that the right to execute is requested (if this feature is
- // enabled).
-
- if (requested != null && !requested.IsUnrestricted())
- requested.AddPermission( executionSecurityPermission );
-
- // If we aren't passed any evidence, just make an empty object
- if (evidence == null)
- {
- evidence = new Evidence();
- }
-
- allowed = polmgr.Resolve(evidence);
- // Intersect the grant with the RequestOptional
- if (requested != null)
- allowed.InplaceIntersect(requested);
-
- // Check that we were granted the right to execute.
- if (checkExecutionPermission)
- {
- if (!allowed.Contains(executionSecurityPermission) ||
- (denyPset != null && denyPset.Contains(executionSecurityPermission)))
- {
- throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"),
- System.__HResults.CORSEC_E_NO_EXEC_PERM,
- savedException);
- }
- }
-
- // Check that we were granted at least the minimal set we asked for. Do
- // this before pruning away any overlap with the refused set so that
- // users have the flexability of defining minimal permissions that are
- // only expressable as set differences (e.g. allow access to "C:\" but
- // disallow "C:\Windows").
- if (reqdPset != null && !reqdPset.IsSubsetOf(allowed))
- {
- BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled");
- throw new PolicyException(Environment.GetResourceString( "Policy_NoRequiredPermission" ),
- System.__HResults.CORSEC_E_MIN_GRANT_FAIL,
- savedException );
- }
-
- // Remove any granted permissions that are safe subsets of some denied
- // permission. The remaining denied permissions (if any) are returned
- // along with the modified grant set for use in checks.
- if (denyPset != null)
- {
- BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled");
- denied = denyPset.Copy();
- allowed.MergeDeniedSet(denied);
- if (denied.IsEmpty())
- denied = null;
- }
- else
- denied = null;
-
- allowed.IgnoreTypeLoadFailures = true;
-
- return allowed;
- }
-
- [Obsolete("Because execution permission checks can no longer be turned off, the CheckExecutionRights property no longer has any effect.")]
- static public bool CheckExecutionRights
- {
- get { return true; }
-
- set
- {
- // The setter for this property is a no-op since execution checking can no longer be turned off
- }
- }
-
- [Obsolete("Because security can no longer be turned off, the SecurityEnabled property no longer has any effect.")]
- public static bool SecurityEnabled
- {
- get { return true; }
-
- set
- {
- // The setter for this property is a no-op since security cannot be turned off
- }
- }
-#endif // #if FEATURE_CAS_POLICY
-
+ static public class SecurityManager
+ {
private static int[][] s_BuiltInPermissionIndexMap = {
new int[] { BuiltInPermissionIndex.EnvironmentPermissionIndex, (int) PermissionType.EnvironmentPermission },
new int[] { BuiltInPermissionIndex.FileDialogPermissionIndex, (int) PermissionType.FileDialogPermission },
@@ -653,17 +142,14 @@ namespace System.Security {
return flags;
}
#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);
diff --git a/src/mscorlib/src/System/Security/SecurityRuntime.cs b/src/mscorlib/src/System/Security/SecurityRuntime.cs
index 9d776affd3..d037fe939d 100644
--- a/src/mscorlib/src/System/Security/SecurityRuntime.cs
+++ b/src/mscorlib/src/System/Security/SecurityRuntime.cs
@@ -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
}
}
}
diff --git a/src/mscorlib/src/System/Security/SecurityState.cs b/src/mscorlib/src/System/Security/SecurityState.cs
index bd23acd813..3c7f8bf49f 100644
--- a/src/mscorlib/src/System/Security/SecurityState.cs
+++ b/src/mscorlib/src/System/Security/SecurityState.cs
@@ -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();
diff --git a/src/mscorlib/src/System/Security/Util/Config.cs b/src/mscorlib/src/System/Security/Util/Config.cs
index 988a39a9d6..afc9b8c336 100644
--- a/src/mscorlib/src/System/Security/Util/Config.cs
+++ b/src/mscorlib/src/System/Security/Util/Config.cs
@@ -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);
}
diff --git a/src/mscorlib/src/System/Security/Util/Hex.cs b/src/mscorlib/src/System/Security/Util/Hex.cs
index 709744f2a2..4ca1cf678b 100644
--- a/src/mscorlib/src/System/Security/Util/Hex.cs
+++ b/src/mscorlib/src/System/Security/Util/Hex.cs
@@ -73,7 +73,7 @@ namespace System.Security.Util
public static byte[] DecodeHexString(String hexString)
{
if (hexString == null)
- throw new ArgumentNullException( "hexString" );
+ throw new ArgumentNullException( nameof(hexString) );
Contract.EndContractBlock();
bool spaceSkippingMode = false;
diff --git a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs b/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs
index 19937f5ae6..8a12235106 100644
--- a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs
+++ b/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs
@@ -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,11 +114,10 @@ namespace System.Security.Util {
return StaticProcessSingleString(str);
}
- [System.Security.SecurityCritical] // auto-generated
public void AddExpressions( String str )
{
if (str == null)
- throw new ArgumentNullException( "str" );
+ throw new ArgumentNullException( nameof(str) );
Contract.EndContractBlock();
if (str.Length == 0)
return;
@@ -165,7 +160,7 @@ namespace System.Security.Util {
{
if (m_throwOnRelative)
{
- if (Path.IsRelative(temp))
+ if (PathInternal.IsPartiallyQualified(temp))
{
throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
}
@@ -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,19 +198,18 @@ namespace System.Security.Util {
}
- [System.Security.SecurityCritical] // auto-generated
internal static ArrayList CreateListFromExpressions(String[] str, bool needFullPath)
{
if (str == null)
{
- throw new ArgumentNullException( "str" );
+ throw new ArgumentNullException( nameof(str) );
}
Contract.EndContractBlock();
ArrayList retArrayList = new ArrayList();
for (int index = 0; index < str.Length; ++index)
{
if (str[index] == null)
- throw new ArgumentNullException( "str" );
+ throw new ArgumentNullException( nameof(str) );
// Replace alternate directory separators
String oneString = StaticProcessWholeString( str[index] );
@@ -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 );
@@ -325,7 +315,7 @@ namespace System.Security.Util {
{
if (m_throwOnRelative)
{
- if (Path.IsRelative(temp))
+ if (PathInternal.IsPartiallyQualified(temp))
{
throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
}
@@ -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,23 +704,20 @@ 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)
{
- string newPath = Path.GetFullPathInternal(path);
+ string newPath = Path.GetFullPath(path);
if (path.EndsWith(m_directorySeparator + ".", StringComparison.Ordinal))
{
if (newPath.EndsWith(m_directorySeparator))
diff --git a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs b/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs
index 590a909662..8589fa7c42 100644
--- a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs
+++ b/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Security/Util/URLString.cs b/src/mscorlib/src/System/Security/Util/URLString.cs
index 51ae24cf4a..83f9ce483f 100644
--- a/src/mscorlib/src/System/Security/Util/URLString.cs
+++ b/src/mscorlib/src/System/Security/Util/URLString.cs
@@ -484,10 +484,11 @@ namespace System.Security.Util {
private static void CheckPathTooLong(StringBuilder path)
{
if (path.Length >= (
-#if FEATURE_PATHCOMPAT
- AppContextSwitches.BlockLongPaths ? PathInternal.MaxShortPath :
-#endif
+#if PLATFORM_UNIX
+ Interop.Sys.MaxPath))
+#else
PathInternal.MaxLongPath))
+#endif
{
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
}
@@ -513,7 +514,7 @@ namespace System.Security.Util {
// file:/home/johndoe/here
// file:../johndoe/here
// file:~/johndoe/here
- String temp = url;
+ String temp = url;
int nbSlashes = 0;
while(nbSlashes<temp.Length && '/'==temp[nbSlashes])
nbSlashes++;
@@ -533,7 +534,7 @@ namespace System.Security.Util {
{
String temp = url;
-#if !PLATFORM_UNIX
+#if !PLATFORM_UNIX
int index = temp.IndexOf( '/');
if (index != -1 &&
@@ -651,7 +652,7 @@ namespace System.Security.Util {
}
else
{
-#if !PLATFORM_UNIX
+#if !PLATFORM_UNIX
String site = temp.Substring( 0, index );
m_localSite = null;
m_siteString = new SiteString( site );
@@ -680,7 +681,7 @@ namespace System.Security.Util {
{
if (url == null)
{
- throw new ArgumentNullException( "url" );
+ throw new ArgumentNullException( nameof(url) );
}
Contract.EndContractBlock();
@@ -1127,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
@@ -1177,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 );
diff --git a/src/mscorlib/src/System/Security/Util/XMLUtil.cs b/src/mscorlib/src/System/Security/Util/XMLUtil.cs
index df8f0c4670..3a1aaa3b09 100644
--- a/src/mscorlib/src/System/Security/Util/XMLUtil.cs
+++ b/src/mscorlib/src/System/Security/Util/XMLUtil.cs
@@ -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
diff --git a/src/mscorlib/src/System/Security/securestring.cs b/src/mscorlib/src/System/Security/securestring.cs
index b53d0db5b4..548126f4d0 100644
--- a/src/mscorlib/src/System/Security/securestring.cs
+++ b/src/mscorlib/src/System/Security/securestring.cs
@@ -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 {
@@ -105,15 +106,15 @@ namespace System.Security {
[CLSCompliant(false)]
public unsafe SecureString(char* value, int length) {
if( value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
if( length < 0) {
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if( length > MaxLength) {
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_Length"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Length"));
}
Contract.EndContractBlock();
@@ -192,7 +193,7 @@ namespace System.Security {
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void InsertAt( int index, char c ) {
if( index < 0 || index > m_length) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
Contract.EndContractBlock();
@@ -251,7 +252,7 @@ namespace System.Security {
EnsureNotReadOnly();
if( index < 0 || index >= m_length) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
unsafe
@@ -290,10 +291,10 @@ namespace System.Security {
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void SetAt( int index, char c ) {
if( index < 0 || index >= m_length) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
+ 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;
}
}
@@ -341,7 +342,7 @@ namespace System.Security {
[System.Security.SecurityCritical] // auto-generated
private void EnsureCapacity(int capacity) {
if( capacity > MaxLength) {
- throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
+ throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
}
Contract.EndContractBlock();
@@ -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);
}
diff --git a/src/mscorlib/src/System/SharedStatics.cs b/src/mscorlib/src/System/SharedStatics.cs
index ec63a0ec25..cbc5c354a1 100644
--- a/src/mscorlib/src/System/SharedStatics.cs
+++ b/src/mscorlib/src/System/SharedStatics.cs
@@ -11,18 +11,16 @@
**
=============================================================================*/
-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);
}
}
diff --git a/src/mscorlib/src/System/Single.cs b/src/mscorlib/src/System/Single.cs
index 6a77f086b5..481c088617 100644
--- a/src/mscorlib/src/System/Single.cs
+++ b/src/mscorlib/src/System/Single.cs
@@ -37,22 +37,21 @@ namespace System {
public const float NegativeInfinity = (float)-1.0 / (float)0.0;
public const float NaN = (float)0.0 / (float)0.0;
+ 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);
@@ -60,11 +59,15 @@ 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]
+ internal unsafe static bool IsNegative(float f) {
+ return (*(uint*)(&f) & 0x80000000) == 0x80000000;
+ }
// Compares this object to another object, returning an integer that
// indicates the relationship.
@@ -155,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) {
@@ -166,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));
diff --git a/src/mscorlib/src/System/Span.cs b/src/mscorlib/src/System/Span.cs
new file mode 100644
index 0000000000..9fa55c63d7
--- /dev/null
+++ b/src/mscorlib/src/System/Span.cs
@@ -0,0 +1,477 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+
+#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
+
+namespace System
+{
+ /// <summary>
+ /// Span represents contiguous region of arbitrary memory, with performance
+ /// characteristics on par with T[]. Unlike arrays, it can point to either managed
+ /// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
+ /// </summary>
+ public struct Span<T>
+ {
+ /// <summary>A byref or a native ptr.</summary>
+ private readonly ByReference<T> _pointer;
+ /// <summary>The number of elements this Span contains.</summary>
+ private readonly int _length;
+
+ /// <summary>
+ /// Creates a new span over the entirety of the target array.
+ /// </summary>
+ /// <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 and array's type is not exactly T[].</exception>
+ public Span(T[] array)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (default(T) == null) { // Arrays of valuetypes are never covariant
+ if (array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException();
+ }
+
+ _pointer = new ByReference<T>(ref JitHelpers.GetArrayData(array));
+ _length = array.Length;
+ }
+
+ /// <summary>
+ /// Creates a new span over the portion of the target array beginning
+ /// at 'start' index and covering the remainder of the array.
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <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 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>
+ public Span(T[] array, int start)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (default(T) == null) { // Arrays of valuetypes are never covariant
+ if (array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException();
+ }
+ if ((uint)start > (uint)array.Length)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _pointer = new ByReference<T>(ref Unsafe.Add(ref JitHelpers.GetArrayData(array), start));
+ _length = array.Length - start;
+ }
+
+ /// <summary>
+ /// Creates a new span over the portion of the target array beginning
+ /// at 'start' index and ending at 'end' index (exclusive).
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <param name="start">The index at which to begin the span.</param>
+ /// <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 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>
+ public Span(T[] array, int start, int length)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (default(T) == null) { // Arrays of valuetypes are never covariant
+ if (array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException();
+ }
+ if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _pointer = new ByReference<T>(ref Unsafe.Add(ref JitHelpers.GetArrayData(array), start));
+ _length = length;
+ }
+
+ /// <summary>
+ /// Creates a new span over the target unmanaged buffer. Clearly this
+ /// is quite dangerous, because we are creating arbitrarily typed T's
+ /// 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="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.
+ /// </exception>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="length"/> is negative.
+ /// </exception>
+ [CLSCompliant(false)]
+ public unsafe Span(void* pointer, int length)
+ {
+ if (JitHelpers.ContainsReferences<T>())
+ ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
+ if (length < 0)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
+ _length = length;
+ }
+
+ /// <summary>
+ /// Create a new span over a portion of a regular managed object. This can be useful
+ /// if part of a managed object represents a "fixed array." This is dangerous because
+ /// "length" is not checked, nor is the fact that "rawPointer" actually lies within the object.
+ /// </summary>
+ /// <param name="obj">The managed object that contains the data to span over.</param>
+ /// <param name="objectData">A reference to data within that object.</param>
+ /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
+ /// <exception cref="System.ArgumentNullException">
+ /// Thrown when the specified object is null.
+ /// </exception>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="length"/> is negative.
+ /// </exception>
+ public static Span<T> DangerousCreate(object obj, ref T objectData, int length)
+ {
+ if (obj == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
+ if (length < 0)
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
+
+ return new Span<T>(ref objectData, length);
+ }
+
+
+ /// <summary>
+ /// An internal helper for creating spans.
+ /// </summary>
+ internal Span(ref T ptr, int length)
+ {
+ _pointer = new ByReference<T>(ref ptr);
+ _length = length;
+ }
+
+ /// <summary>
+ /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
+ /// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
+ /// </summary>
+ public ref T DangerousGetPinnableReference()
+ {
+ return ref _pointer.Value;
+ }
+
+ /// <summary>
+ /// Gets the number of elements contained in the <see cref="Span{T}"/>
+ /// </summary>
+ public int Length => _length;
+
+ /// <summary>
+ /// Returns whether the <see cref="Span{T}"/> is empty.
+ /// </summary>
+ public bool IsEmpty => _length == 0;
+
+ /// <summary>
+ /// Fetches the element at the specified index.
+ /// </summary>
+ /// <exception cref="System.IndexOutOfRangeException">
+ /// Thrown when the specified <paramref name="index"/> is not in range (&lt;0 or &gt;&eq;Length).
+ /// </exception>
+ public T this[int index]
+ {
+ get
+ {
+ if ((uint)index >= (uint)_length)
+ ThrowHelper.ThrowIndexOutOfRangeException();
+
+ return Unsafe.Add(ref DangerousGetPinnableReference(), index);
+ }
+ set
+ {
+ if ((uint)index >= (uint)_length)
+ ThrowHelper.ThrowIndexOutOfRangeException();
+
+ Unsafe.Add(ref DangerousGetPinnableReference(), index) = value;
+ }
+ }
+
+ /// <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>
+ /// <exception cref="System.ArgumentException">
+ /// Thrown when the destination Span is shorter than the source Span.
+ /// </exception>
+ public void CopyTo(Span<T> destination)
+ {
+ if (!TryCopyTo(destination))
+ ThrowHelper.ThrowArgumentException_DestinationTooShort();
+ }
+
+ /// <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)
+ {
+ return left._length == right._length && Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
+ }
+
+ /// <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 == right);
+
+ /// <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>
+ /// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
+ /// </summary>
+ public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span.DangerousGetPinnableReference(), span._length);
+
+ /// <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>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.NoOptimization)] // TODO-SPAN: Workaround for https://github.com/dotnet/coreclr/issues/7894
+ public Span<T> Slice(int start)
+ {
+ if ((uint)start > (uint)_length)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ return new Span<T>(ref Unsafe.Add(ref DangerousGetPinnableReference(), start), _length - start);
+ }
+
+ /// <summary>
+ /// 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="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>
+ [MethodImpl(MethodImplOptions.NoOptimization)] // TODO-SPAN: Workaround for https://github.com/dotnet/coreclr/issues/7894
+ public Span<T> Slice(int start, int length)
+ {
+ if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ return new Span<T>(ref Unsafe.Add(ref DangerousGetPinnableReference(), start), length);
+ }
+
+ /// <summary>
+ /// 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>
+ public T[] ToArray()
+ {
+ if (_length == 0)
+ return Array.Empty<T>();
+
+ var destination = new T[_length];
+ SpanHelper.CopyTo<T>(ref JitHelpers.GetArrayData(destination), ref DangerousGetPinnableReference(), _length);
+ return destination;
+ }
+
+ // <summary>
+ /// Returns an empty <see cref="Span{T}"/>
+ /// </summary>
+ public static Span<T> Empty => default(Span<T>);
+ }
+
+ public static class SpanExtensions
+ {
+ /// <summary>
+ /// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes.
+ /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
+ /// </summary>
+ /// <param name="source">The source slice, of type <typeparamref name="T"/>.</param>
+ /// <exception cref="System.ArgumentException">
+ /// Thrown when <typeparamref name="T"/> contains pointers.
+ /// </exception>
+ public static Span<byte> AsBytes<T>(this Span<T> source)
+ where T : struct
+ {
+ if (JitHelpers.ContainsReferences<T>())
+ ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
+
+ return new Span<byte>(
+ ref Unsafe.As<T, byte>(ref source.DangerousGetPinnableReference()),
+ checked(source.Length * Unsafe.SizeOf<T>()));
+ }
+
+ /// <summary>
+ /// Casts a ReadOnlySpan of one primitive type <typeparamref name="T"/> to ReadOnlySpan of bytes.
+ /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
+ /// </summary>
+ /// <param name="source">The source slice, of type <typeparamref name="T"/>.</param>
+ /// <exception cref="System.ArgumentException">
+ /// Thrown when <typeparamref name="T"/> contains pointers.
+ /// </exception>
+ public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source)
+ where T : struct
+ {
+ if (JitHelpers.ContainsReferences<T>())
+ ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
+
+ return new ReadOnlySpan<byte>(
+ ref Unsafe.As<T, byte>(ref source.DangerousGetPinnableReference()),
+ checked(source.Length * Unsafe.SizeOf<T>()));
+ }
+
+ /// <summary>
+ /// Casts a Span of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
+ /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
+ /// </summary>
+ /// <remarks>
+ /// Supported only for platforms that support misaligned memory access.
+ /// </remarks>
+ /// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param>
+ /// <exception cref="System.ArgumentException">
+ /// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
+ /// </exception>
+ public static Span<TTo> NonPortableCast<TFrom, TTo>(this Span<TFrom> source)
+ where TFrom : struct
+ where TTo : struct
+ {
+ if (JitHelpers.ContainsReferences<TFrom>())
+ ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom));
+ if (JitHelpers.ContainsReferences<TTo>())
+ ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo));
+
+ return new Span<TTo>(
+ ref Unsafe.As<TFrom, TTo>(ref source.DangerousGetPinnableReference()),
+ checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>())));
+ }
+
+ /// <summary>
+ /// Casts a ReadOnlySpan of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
+ /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
+ /// </summary>
+ /// <remarks>
+ /// Supported only for platforms that support misaligned memory access.
+ /// </remarks>
+ /// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param>
+ /// <exception cref="System.ArgumentException">
+ /// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
+ /// </exception>
+ public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source)
+ where TFrom : struct
+ where TTo : struct
+ {
+ if (JitHelpers.ContainsReferences<TFrom>())
+ ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom));
+ if (JitHelpers.ContainsReferences<TTo>())
+ ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo));
+
+ return new ReadOnlySpan<TTo>(
+ ref Unsafe.As<TFrom, TTo>(ref source.DangerousGetPinnableReference()),
+ checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>())));
+ }
+ }
+
+ internal static class SpanHelper
+ {
+ internal static unsafe void CopyTo<T>(ref T destination, ref T source, int elementsCount)
+ {
+ if (elementsCount == 0)
+ return;
+
+ if (Unsafe.AreSame(ref destination, ref source))
+ return;
+
+ if (!JitHelpers.ContainsReferences<T>())
+ {
+ fixed (byte* pDestination = &Unsafe.As<T, byte>(ref destination))
+ {
+ fixed (byte* pSource = &Unsafe.As<T, byte>(ref source))
+ {
+#if BIT64
+ Buffer.Memmove(pDestination, pSource, (ulong)elementsCount * (ulong)Unsafe.SizeOf<T>());
+#else
+ Buffer.Memmove(pDestination, pSource, (uint)elementsCount * (uint)Unsafe.SizeOf<T>());
+#endif
+ }
+ }
+ }
+ else
+ {
+ if (JitHelpers.ByRefLessThan(ref destination, ref source)) // copy forward
+ {
+ for (int i = 0; i < elementsCount; i++)
+ Unsafe.Add(ref destination, i) = Unsafe.Add(ref source, i);
+ }
+ else // copy backward to avoid overlapping issues
+ {
+ for (int i = elementsCount - 1; i >= 0; i--)
+ Unsafe.Add(ref destination, i) = Unsafe.Add(ref source, i);
+ }
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/String.Comparison.cs b/src/mscorlib/src/System/String.Comparison.cs
index a05f9f201a..07f2f9de22 100644
--- a/src/mscorlib/src/System/String.Comparison.cs
+++ b/src/mscorlib/src/System/String.Comparison.cs
@@ -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,13 +337,12 @@ 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]
if ((uint)(comparisonType - StringComparison.CurrentCulture) > (uint)(StringComparison.OrdinalIgnoreCase - StringComparison.CurrentCulture))
{
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
Contract.EndContractBlock();
@@ -417,7 +411,7 @@ namespace System
public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options) {
if (culture == null)
{
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
}
Contract.EndContractBlock();
@@ -511,7 +505,7 @@ namespace System
{
if (culture == null)
{
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
}
Contract.EndContractBlock();
@@ -532,10 +526,9 @@ 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"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
Contract.EndContractBlock();
@@ -552,18 +545,18 @@ namespace System
if (length < 0)
{
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (indexA < 0 || indexB < 0)
{
- string paramName = indexA < 0 ? "indexA" : "indexB";
+ string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
{
- string paramName = strA.Length - indexA < 0 ? "indexA" : "indexB";
+ string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
@@ -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)
@@ -657,12 +649,12 @@ namespace System
if (length < 0)
{
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
}
if (indexA < 0 || indexB < 0)
{
- string paramName = indexA < 0 ? "indexA" : "indexB";
+ string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
@@ -671,7 +663,7 @@ namespace System
if (lengthA < 0 || lengthB < 0)
{
- string paramName = lengthA < 0 ? "indexA" : "indexB";
+ string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
@@ -724,15 +716,14 @@ namespace System
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public Boolean EndsWith(String value, StringComparison comparisonType) {
if( (Object)value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
if( comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) {
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
Contract.EndContractBlock();
@@ -767,14 +758,14 @@ namespace System
return this.Length < value.Length ? false : (TextInfo.CompareOrdinalIgnoreCaseEx(this, this.Length - value.Length, value, 0, value.Length, value.Length) == 0);
#endif
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
}
[Pure]
public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture) {
if (null==value) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -846,10 +837,9 @@ 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"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
Contract.EndContractBlock();
if ((Object)this == (Object)value) {
@@ -895,7 +885,7 @@ namespace System
#endif
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
}
@@ -915,10 +905,9 @@ 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"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
Contract.EndContractBlock();
if ((Object)a==(Object)b) {
@@ -966,7 +955,7 @@ namespace System
}
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
+ 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()
{
@@ -1012,15 +997,19 @@ namespace System
return GetLegacyNonRandomizedHashCode();
}
+ // Gets a hash code for this string and this comparison. If strings A and B and comparition C are such
+ // that String.Equals(A, B, C), then they will return the same hash code with this comparison C.
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
+ public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this);
+
// 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)
@@ -1073,22 +1062,21 @@ namespace System
[Pure]
public Boolean StartsWith(String value) {
if ((Object)value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return StartsWith(value, StringComparison.CurrentCulture);
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public Boolean StartsWith(String value, StringComparison comparisonType) {
if( (Object)value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
if( comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) {
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
Contract.EndContractBlock();
@@ -1133,14 +1121,14 @@ namespace System
#endif
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
}
[Pure]
public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture) {
if (null==value) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/String.Manipulation.cs b/src/mscorlib/src/System/String.Manipulation.cs
index e9568a6d03..194b4f8c59 100644
--- a/src/mscorlib/src/System/String.Manipulation.cs
+++ b/src/mscorlib/src/System/String.Manipulation.cs
@@ -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,12 +109,11 @@ namespace System
return Concat(objArgs);
}
- [System.Security.SecuritySafeCritical]
public static string Concat(params object[] args)
{
if (args == null)
{
- throw new ArgumentNullException("args");
+ throw new ArgumentNullException(nameof(args));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -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;
@@ -181,7 +180,7 @@ namespace System
public static string Concat<T>(IEnumerable<T> values)
{
if (values == null)
- throw new ArgumentNullException("values");
+ throw new ArgumentNullException(nameof(values));
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -232,7 +231,7 @@ namespace System
public static string Concat(IEnumerable<string> values)
{
if (values == null)
- throw new ArgumentNullException("values");
+ throw new ArgumentNullException(nameof(values));
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -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,10 +362,9 @@ namespace System
return result;
}
- [System.Security.SecuritySafeCritical]
public static String Concat(params String[] values) {
if (values == null)
- throw new ArgumentNullException("values");
+ throw new ArgumentNullException(nameof(values));
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -456,7 +451,7 @@ namespace System
{
// To preserve the original exception behavior, throw an exception about format if both
// args and format are null. The actual null check for format is in FormatHelper.
- throw new ArgumentNullException((format == null) ? "format" : "args");
+ throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -484,7 +479,7 @@ namespace System
{
// To preserve the original exception behavior, throw an exception about format if both
// args and format are null. The actual null check for format is in FormatHelper.
- throw new ArgumentNullException((format == null) ? "format" : "args");
+ throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -494,7 +489,7 @@ namespace System
private static String FormatHelper(IFormatProvider provider, String format, ParamsArray args) {
if (format == null)
- throw new ArgumentNullException("format");
+ throw new ArgumentNullException(nameof(format));
return StringBuilderCache.GetStringAndRelease(
StringBuilderCache
@@ -502,13 +497,12 @@ namespace System
.AppendFormatHelper(provider, format, args));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String Insert(int startIndex, String value)
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
if (startIndex < 0 || startIndex > this.Length)
- throw new ArgumentOutOfRangeException("startIndex");
+ throw new ArgumentOutOfRangeException(nameof(startIndex));
Contract.Ensures(Contract.Result<String>() != null);
Contract.Ensures(Contract.Result<String>().Length == this.Length + value.Length);
Contract.EndContractBlock();
@@ -541,27 +535,131 @@ namespace System
}
return result;
}
+
+ public static string Join(char separator, params string[] value)
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
+
+ return Join(separator, value, 0, value.Length);
+ }
+
+ public unsafe static string Join(char separator, params object[] values)
+ {
+ // Defer argument validation to the internal function
+ return JoinCore(&separator, 1, values);
+ }
+
+ public unsafe static string Join<T>(char separator, IEnumerable<T> values)
+ {
+ // Defer argument validation to the internal function
+ return JoinCore(&separator, 1, values);
+ }
+
+ public unsafe static string Join(char separator, string[] value, int startIndex, int count)
+ {
+ // Defer argument validation to the internal function
+ return JoinCore(&separator, 1, value, startIndex, count);
+ }
// Joins an array of strings together as one string with a separator between each original string.
//
- public static String Join(String separator, params String[] value) {
- if (value==null)
- throw new ArgumentNullException("value");
- Contract.EndContractBlock();
+ public static string Join(string separator, params string[] value)
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
return Join(separator, value, 0, value.Length);
}
[ComVisible(false)]
- public static string Join(string separator, params object[] values)
+ public unsafe static string Join(string separator, params object[] values)
+ {
+ separator = separator ?? string.Empty;
+ fixed (char* pSeparator = &separator.m_firstChar)
+ {
+ // Defer argument validation to the internal function
+ return JoinCore(pSeparator, separator.Length, values);
+ }
+ }
+
+ [ComVisible(false)]
+ public unsafe static string Join<T>(string separator, IEnumerable<T> values)
+ {
+ separator = separator ?? string.Empty;
+ fixed (char* pSeparator = &separator.m_firstChar)
+ {
+ // Defer argument validation to the internal function
+ return JoinCore(pSeparator, separator.Length, values);
+ }
+ }
+
+ [ComVisible(false)]
+ public static string Join(string separator, IEnumerable<string> values)
{
if (values == null)
- throw new ArgumentNullException("values");
- Contract.EndContractBlock();
+ {
+ throw new ArgumentNullException(nameof(values));
+ }
+
+ using (IEnumerator<string> en = values.GetEnumerator())
+ {
+ if (!en.MoveNext())
+ {
+ return string.Empty;
+ }
+
+ string firstValue = en.Current;
- if (values.Length == 0 || values[0] == null)
+ if (!en.MoveNext())
+ {
+ // Only one value available
+ return firstValue ?? string.Empty;
+ }
+
+ // Null separator and values are handled by the StringBuilder
+ StringBuilder result = StringBuilderCache.Acquire();
+ result.Append(firstValue);
+
+ do
+ {
+ result.Append(separator);
+ result.Append(en.Current);
+ }
+ while (en.MoveNext());
+
+ return StringBuilderCache.GetStringAndRelease(result);
+ }
+ }
+
+ // Joins an array of strings together as one string with a separator between each original string.
+ //
+ public unsafe static string Join(string separator, string[] value, int startIndex, int count)
+ {
+ separator = separator ?? string.Empty;
+ fixed (char* pSeparator = &separator.m_firstChar)
+ {
+ // Defer argument validation to the internal function
+ return JoinCore(pSeparator, separator.Length, value, startIndex, count);
+ }
+ }
+
+ private unsafe static string JoinCore(char* separator, int separatorLength, object[] values)
+ {
+ if (values == null)
+ {
+ throw new ArgumentNullException(nameof(values));
+ }
+
+ if (values.Length == 0)
+ {
return string.Empty;
+ }
- string firstString = values[0].ToString();
+ string firstString = values[0]?.ToString();
if (values.Length == 1)
{
@@ -573,7 +671,7 @@ namespace System
for (int i = 1; i < values.Length; i++)
{
- result.Append(separator);
+ result.Append(separator, separatorLength);
object value = values[i];
if (value != null)
{
@@ -584,18 +682,19 @@ namespace System
return StringBuilderCache.GetStringAndRelease(result);
}
- [ComVisible(false)]
- public static String Join<T>(String separator, IEnumerable<T> values)
+ private unsafe static string JoinCore<T>(char* separator, int separatorLength, IEnumerable<T> values)
{
if (values == null)
- throw new ArgumentNullException("values");
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
+ {
+ throw new ArgumentNullException(nameof(values));
+ }
using (IEnumerator<T> en = values.GetEnumerator())
{
if (!en.MoveNext())
+ {
return string.Empty;
+ }
// We called MoveNext once, so this will be the first item
T currentValue = en.Current;
@@ -616,14 +715,14 @@ namespace System
}
StringBuilder result = StringBuilderCache.Acquire();
-
+
result.Append(firstString);
do
{
currentValue = en.Current;
- result.Append(separator);
+ result.Append(separator, separatorLength);
if (currentValue != null)
{
result.Append(currentValue.ToString());
@@ -635,107 +734,113 @@ namespace System
}
}
- [ComVisible(false)]
- public static String Join(String separator, IEnumerable<String> values) {
- if (values == null)
- throw new ArgumentNullException("values");
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
-
- using(IEnumerator<String> en = values.GetEnumerator()) {
- if (!en.MoveNext())
- return String.Empty;
-
- String firstValue = en.Current;
-
- if (!en.MoveNext()) {
- // Only one value available
- return firstValue ?? String.Empty;
- }
-
- // Null separator and values are handled by the StringBuilder
- StringBuilder result = StringBuilderCache.Acquire();
- result.Append(firstValue);
-
- do {
- result.Append(separator);
- result.Append(en.Current);
- } while (en.MoveNext());
- return StringBuilderCache.GetStringAndRelease(result);
- }
- }
+ private unsafe static string JoinCore(char* separator, int separatorLength, string[] value, int startIndex, int count)
+ {
+ // 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).
+ Debug.Assert(separator != null);
+ Debug.Assert(separatorLength >= 0);
- // 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) {
- //Range check the array
if (value == null)
- throw new ArgumentNullException("value");
-
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
if (startIndex < 0)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ }
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
-
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ }
if (startIndex > value.Length - count)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
- Contract.EndContractBlock();
-
- //Treat null as empty string.
- if (separator == null) {
- separator = String.Empty;
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
}
-
- //If count is 0, that skews a whole bunch of the calculations below, so just special case that.
- if (count == 0) {
- return String.Empty;
+
+ if (count <= 1)
+ {
+ return count == 0 ?
+ string.Empty :
+ value[startIndex] ?? string.Empty;
}
- if (count == 1) {
- return value[startIndex] ?? String.Empty;
+ long totalSeparatorsLength = (long)(count - 1) * separatorLength;
+ if (totalSeparatorsLength > int.MaxValue)
+ {
+ throw new OutOfMemoryException();
}
+ int totalLength = (int)totalSeparatorsLength;
- int jointLength = 0;
- //Figure out the total length of the strings in value
- int endIndex = startIndex + count - 1;
- for (int stringToJoinIndex = startIndex; stringToJoinIndex <= endIndex; stringToJoinIndex++) {
- string currentValue = value[stringToJoinIndex];
-
- if (currentValue != null) {
- jointLength += currentValue.Length;
+ // Calculate the length of the resultant string so we know how much space to allocate.
+ for (int i = startIndex, end = startIndex + count; i < end; i++)
+ {
+ string currentValue = value[i];
+ if (currentValue != null)
+ {
+ totalLength += currentValue.Length;
+ if (totalLength < 0) // Check for overflow
+ {
+ throw new OutOfMemoryException();
+ }
}
}
-
- //Add enough room for the separator.
- jointLength += (count - 1) * separator.Length;
- // Note that we may not catch all overflows with this check (since we could have wrapped around the 4gb range any number of times
- // and landed back in the positive range.) The input array might be modifed from other threads,
- // so we have to do an overflow check before each append below anyway. Those overflows will get caught down there.
- if ((jointLength < 0) || ((jointLength + 1) < 0) ) {
- throw new OutOfMemoryException();
- }
+ // Copy each of the strings into the resultant buffer, interleaving with the separator.
+ string result = FastAllocateString(totalLength);
+ int copiedLength = 0;
- //If this is an empty string, just return.
- if (jointLength == 0) {
- return String.Empty;
- }
+ for (int i = startIndex, end = startIndex + count; i < end; i++)
+ {
+ // It's possible that another thread may have mutated the input array
+ // such that our second read of an index will not be the same string
+ // we got during the first read.
- string jointString = FastAllocateString( jointLength );
- fixed (char * pointerToJointString = &jointString.m_firstChar) {
- UnSafeCharBuffer charBuffer = new UnSafeCharBuffer( pointerToJointString, jointLength);
-
- // Append the first string first and then append each following string prefixed by the separator.
- charBuffer.AppendString( value[startIndex] );
- for (int stringToJoinIndex = startIndex + 1; stringToJoinIndex <= endIndex; stringToJoinIndex++) {
- charBuffer.AppendString( separator );
- charBuffer.AppendString( value[stringToJoinIndex] );
+ // We range check again to avoid buffer overflows if this happens.
+
+ string currentValue = value[i];
+ if (currentValue != null)
+ {
+ int valueLen = currentValue.Length;
+ if (valueLen > totalLength - copiedLength)
+ {
+ copiedLength = -1;
+ break;
+ }
+
+ // Fill in the value.
+ FillStringChecked(result, copiedLength, currentValue);
+ copiedLength += valueLen;
+ }
+
+ if (i < end - 1)
+ {
+ // Fill in the separator.
+ fixed (char* pResult = &result.m_firstChar)
+ {
+ // If we are called from the char-based overload, we will not
+ // want to call MemoryCopy each time we fill in the separator. So
+ // specialize for 1-length separators.
+ if (separatorLength == 1)
+ {
+ pResult[copiedLength] = *separator;
+ }
+ else
+ {
+ wstrcpy(pResult + copiedLength, separator, separatorLength);
+ }
+ }
+ copiedLength += separatorLength;
}
- Contract.Assert(*(pointerToJointString + charBuffer.Length) == '\0', "String must be null-terminated!");
}
- return jointString;
+ // If we copied exactly the right amount, return the new string. Otherwise,
+ // something changed concurrently to mutate the input array: fall back to
+ // doing the concatenation again, but this time with a defensive copy. This
+ // fall back should be extremely rare.
+ return copiedLength == totalLength ?
+ result :
+ JoinCore(separator, separatorLength, (string[])value.Clone(), startIndex, count);
}
//
@@ -746,10 +851,9 @@ namespace System
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public String PadLeft(int totalWidth, char paddingChar) {
if (totalWidth < 0)
- throw new ArgumentOutOfRangeException("totalWidth", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(totalWidth), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
int oldLength = Length;
int count = totalWidth - oldLength;
if (count <= 0)
@@ -776,10 +880,9 @@ namespace System
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public String PadRight(int totalWidth, char paddingChar) {
if (totalWidth < 0)
- throw new ArgumentOutOfRangeException("totalWidth", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(totalWidth), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
int oldLength = Length;
int count = totalWidth - oldLength;
if (count <= 0)
@@ -800,17 +903,16 @@ namespace System
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String Remove(int startIndex, int count)
{
if (startIndex < 0)
- throw new ArgumentOutOfRangeException("startIndex",
+ throw new ArgumentOutOfRangeException(nameof(startIndex),
Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
if (count > Length - startIndex)
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
Contract.Ensures(Contract.Result<String>() != null);
Contract.Ensures(Contract.Result<String>().Length == this.Length - count);
@@ -840,12 +942,12 @@ namespace System
// a remove that just takes a startindex.
public string Remove( int startIndex ) {
if (startIndex < 0) {
- throw new ArgumentOutOfRangeException("startIndex",
+ throw new ArgumentOutOfRangeException(nameof(startIndex),
Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (startIndex >= Length) {
- throw new ArgumentOutOfRangeException("startIndex",
+ throw new ArgumentOutOfRangeException(nameof(startIndex),
Environment.GetResourceString("ArgumentOutOfRange_StartIndexLessThanLength"));
}
@@ -857,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);
@@ -928,14 +1029,13 @@ 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);
public String Replace(String oldValue, String newValue)
{
if (oldValue == null)
- throw new ArgumentNullException("oldValue");
+ throw new ArgumentNullException(nameof(oldValue));
// Note that if newValue is null, we treat it like String.Empty.
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -944,19 +1044,13 @@ namespace System
}
[ComVisible(false)]
- public String[] Split(char separator) {
- Contract.Ensures(Contract.Result<String[]>() != null);
- return SplitInternal(separator, Int32.MaxValue, StringSplitOptions.None);
- }
-
- [ComVisible(false)]
- public String[] Split(char separator, StringSplitOptions options) {
+ public String[] Split(char separator, StringSplitOptions options = StringSplitOptions.None) {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, Int32.MaxValue, options);
}
[ComVisible(false)]
- public String[] Split(char separator, int count, StringSplitOptions options) {
+ public String[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None) {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, count, options);
}
@@ -1004,33 +1098,24 @@ namespace System
return SplitInternal(separator, count, options);
}
- [System.Security.SecuritySafeCritical]
private unsafe String[] SplitInternal(char separator, int count, StringSplitOptions options)
{
- char* pSeparators = stackalloc char[1];
- pSeparators[0] = separator;
- return SplitInternal(pSeparators, /*separatorsLength*/ 1, count, options);
+ return SplitInternal(&separator, 1, count, options);
}
- [ComVisible(false)]
- [System.Security.SecuritySafeCritical]
- internal String[] SplitInternal(char[] separator, int count, StringSplitOptions options)
+ private unsafe String[] SplitInternal(char[] separator, int count, StringSplitOptions options)
{
- unsafe
+ fixed (char* pSeparators = separator)
{
- fixed (char* pSeparators = separator)
- {
- int separatorsLength = separator == null ? 0 : separator.Length;
- return SplitInternal(pSeparators, separatorsLength, count, options);
- }
+ int separatorsLength = separator == null ? 0 : separator.Length;
+ return SplitInternal(pSeparators, separatorsLength, count, options);
}
}
- [System.Security.SecurityCritical]
private unsafe String[] SplitInternal(char* separators, int separatorsLength, int count, StringSplitOptions options)
{
if (count < 0)
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
@@ -1041,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)
@@ -1056,38 +1135,32 @@ 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)
{
- return InternalSplitOmitEmptyEntries(sepList, null, 1, numReplaces, count);
+ return SplitOmitEmptyEntries(sepList, null, 1, numReplaces, count);
}
else
{
- return InternalSplitKeepEmptyEntries(sepList, null, 1, numReplaces, count);
- }
- }
-
- [ComVisible(false)]
- public String[] Split(String separator) {
- Contract.Ensures(Contract.Result<String[]>() != null);
- return SplitInternal(separator ?? String.Empty, null, Int32.MaxValue, StringSplitOptions.None);
+ return SplitKeepEmptyEntries(sepList, null, 1, numReplaces, count);
+ }
}
[ComVisible(false)]
- public String[] Split(String separator, StringSplitOptions options) {
+ public String[] Split(String separator, StringSplitOptions options = StringSplitOptions.None) {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator ?? String.Empty, null, Int32.MaxValue, options);
}
[ComVisible(false)]
- public String[] Split(String separator, Int32 count, StringSplitOptions options) {
+ public String[] Split(String separator, Int32 count, StringSplitOptions options = StringSplitOptions.None) {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator ?? String.Empty, null, count, options);
}
@@ -1107,7 +1180,7 @@ namespace System
private String[] SplitInternal(String separator, String[] separators, Int32 count, StringSplitOptions options)
{
if (count < 0) {
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
}
@@ -1125,23 +1198,13 @@ 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) {
+ if (count == 1 || (singleSeparator && separator.Length == 0)) {
return new String[] { this };
}
- if (singleSeparator && separator.Length == 0) {
- return new[] { this };
- }
-
int[] sepList = new int[Length];
int[] lengthList;
int defaultLength;
@@ -1164,10 +1227,10 @@ namespace System
}
if (omitEmptyEntries) {
- return InternalSplitOmitEmptyEntries(sepList, lengthList, defaultLength, numReplaces, count);
+ return SplitOmitEmptyEntries(sepList, lengthList, defaultLength, numReplaces, count);
}
else {
- return InternalSplitKeepEmptyEntries(sepList, lengthList, defaultLength, numReplaces, count);
+ return SplitKeepEmptyEntries(sepList, lengthList, defaultLength, numReplaces, count);
}
}
@@ -1176,7 +1239,7 @@ namespace System
// the original string will be returned regardless of the count.
//
- private String[] InternalSplitKeepEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count) {
+ private String[] SplitKeepEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count) {
Contract.Requires(numReplaces >= 0);
Contract.Requires(count >= 2);
Contract.Ensures(Contract.Result<String[]>() != null);
@@ -1212,7 +1275,7 @@ namespace System
// This function will not keep the Empty String
- private String[] InternalSplitOmitEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count) {
+ private String[] SplitOmitEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count) {
Contract.Requires(numReplaces >= 0);
Contract.Requires(count >= 2);
Contract.Ensures(Contract.Result<String[]>() != null);
@@ -1242,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) {
@@ -1265,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) {
@@ -1304,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;
@@ -1334,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;
@@ -1374,24 +1434,23 @@ namespace System
// Returns a substring of this string.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public String Substring(int startIndex, int length) {
//Bounds Checking.
if (startIndex < 0) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (startIndex > Length) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"));
}
if (length < 0) {
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (startIndex > Length - length) {
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
}
Contract.EndContractBlock();
@@ -1406,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);
@@ -1434,7 +1492,7 @@ namespace System
public String ToLower(CultureInfo culture) {
if (culture == null)
{
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -1463,7 +1521,7 @@ namespace System
public String ToUpper(CultureInfo culture) {
if (culture == null)
{
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -1517,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
@@ -1541,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
@@ -1579,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) {
diff --git a/src/mscorlib/src/System/String.Searching.cs b/src/mscorlib/src/System/String.Searching.cs
index b972529694..2620cfd0dc 100644
--- a/src/mscorlib/src/System/String.Searching.cs
+++ b/src/mscorlib/src/System/String.Searching.cs
@@ -29,13 +29,12 @@ 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("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count < 0 || count > Length - startIndex)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
fixed (char* pChars = &m_firstChar)
{
@@ -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);
@@ -116,11 +114,11 @@ namespace System
[Pure]
public int IndexOf(String value, int startIndex, int count) {
if (startIndex < 0 || startIndex > this.Length) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (count < 0 || count > this.Length - startIndex) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
}
Contract.EndContractBlock();
@@ -138,17 +136,16 @@ namespace System
}
[Pure]
- [System.Security.SecuritySafeCritical]
public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) {
// Validate inputs
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
if (startIndex < 0 || startIndex > this.Length)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count < 0 || startIndex > this.Length - count)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
Contract.EndContractBlock();
switch (comparisonType) {
@@ -174,7 +171,7 @@ namespace System
return TextInfo.IndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
}
@@ -194,16 +191,15 @@ namespace System
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe int LastIndexOf(char value, int startIndex, int count) {
if (Length == 0)
return -1;
if (startIndex < 0 || startIndex >= Length)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count < 0 || count - 1 > startIndex)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
fixed (char* pChars = &m_firstChar)
{
@@ -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);
@@ -281,7 +276,7 @@ namespace System
[Pure]
public int LastIndexOf(String value, int startIndex, int count) {
if (count<0) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
}
Contract.EndContractBlock();
@@ -299,10 +294,9 @@ namespace System
}
[Pure]
- [System.Security.SecuritySafeCritical]
public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) {
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Special case for 0 length input strings
@@ -311,7 +305,7 @@ namespace System
// Now after handling empty strings, make sure we're not out of range
if (startIndex < 0 || startIndex > this.Length)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
// Make sure that we allow startIndex == this.Length
if (startIndex == this.Length)
@@ -327,7 +321,7 @@ namespace System
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
switch (comparisonType) {
@@ -351,7 +345,7 @@ namespace System
else
return TextInfo.LastIndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
}
}
diff --git a/src/mscorlib/src/System/String.cs b/src/mscorlib/src/System/String.cs
index d406fd09b3..f9162ff528 100644
--- a/src/mscorlib/src/System/String.cs
+++ b/src/mscorlib/src/System/String.cs
@@ -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,19 +110,18 @@ 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)
- throw new ArgumentNullException("destination");
+ throw new ArgumentNullException(nameof(destination));
if (count < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
if (sourceIndex < 0)
- throw new ArgumentOutOfRangeException("sourceIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count > Length - sourceIndex)
- throw new ArgumentOutOfRangeException("sourceIndex", Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
+ throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
if (destinationIndex > destination.Length - count || destinationIndex < 0)
- throw new ArgumentOutOfRangeException("destinationIndex", Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
+ throw new ArgumentOutOfRangeException(nameof(destinationIndex), Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
Contract.EndContractBlock();
// Note: fixed does not like empty arrays
@@ -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,24 +145,19 @@ 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.
if (startIndex < 0 || startIndex > Length || startIndex > Length - length)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (length < 0)
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
if (length > 0)
@@ -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,36 +205,30 @@ 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
if (length < 0)
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (startIndex < 0)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
if ((value + startIndex) < value) {
// overflow check
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
byte [] b = new byte[length];
@@ -258,7 +239,7 @@ namespace System {
catch(NullReferenceException) {
// If we got a NullReferencException. It means the pointer or
// the index is out of range
- throw new ArgumentOutOfRangeException("value",
+ throw new ArgumentOutOfRangeException(nameof(value),
Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
@@ -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,20 +421,19 @@ namespace System {
return String.Empty;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private String CtorCharArrayStartLength(char [] value, int startIndex, int length)
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
if (length < 0)
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
if (startIndex > value.Length - length)
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
if (length > 0) {
@@ -481,7 +450,6 @@ namespace System {
return String.Empty;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private String CtorCharCount(char c, int count)
{
if (count > 0) {
@@ -519,10 +487,9 @@ namespace System {
else if (count == 0)
return String.Empty;
else
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", "count"));
+ 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);
@@ -641,27 +607,26 @@ namespace System {
return result;
}
catch (NullReferenceException) {
- throw new ArgumentOutOfRangeException("ptr", Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
+ throw new ArgumentOutOfRangeException(nameof(ptr), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe String CtorCharPtrStartLength(char *ptr, int startIndex, int length)
{
if (length < 0) {
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (startIndex < 0) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ 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) {
// This means that the pointer operation has had an overflow
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
if (length == 0)
@@ -675,11 +640,10 @@ namespace System {
return result;
}
catch (NullReferenceException) {
- throw new ArgumentOutOfRangeException("ptr", Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
+ throw new ArgumentOutOfRangeException(nameof(ptr), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char c, int count);
@@ -705,10 +669,9 @@ namespace System {
return this;
}
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe public static String Copy (String str) {
if (str==null) {
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -724,10 +687,9 @@ namespace System {
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String Intern(String str) {
if (str==null) {
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>().Length == str.Length);
Contract.Ensures(str.Equals(Contract.Result<String>()));
@@ -737,10 +699,9 @@ namespace System {
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public static String IsInterned(String str) {
if (str==null) {
- throw new ArgumentNullException("str");
+ throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>() == null || Contract.Result<String>().Length == str.Length);
Contract.EndContractBlock();
@@ -834,31 +795,25 @@ 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);
-#if !FEATURE_CORECLR
public CharEnumerator GetEnumerator() {
Contract.Ensures(Contract.Result<CharEnumerator>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
-#endif // !FEATURE_CORECLR
IEnumerator<char> IEnumerable<char>.GetEnumerator() {
Contract.Ensures(Contract.Result<IEnumerator<char>>() != null);
@@ -876,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)
@@ -886,6 +840,12 @@ namespace System {
byte* dstPtr = (byte*) dest;
Buffer.Memcpy(dstPtr, srcPtr, len);
}
- }
+ }
+
+#if FEATURE_SPAN_OF_T
+ internal ref char GetFirstCharRef() {
+ return ref m_firstChar;
+ }
+#endif
}
}
diff --git a/src/mscorlib/src/System/StringComparer.cs b/src/mscorlib/src/System/StringComparer.cs
index 57bdf4c6b2..02e8d71d0e 100644
--- a/src/mscorlib/src/System/StringComparer.cs
+++ b/src/mscorlib/src/System/StringComparer.cs
@@ -62,9 +62,31 @@ namespace System {
}
}
+ // Convert a StringComparison to a StringComparer
+ public static StringComparer FromComparison(StringComparison comparisonType)
+ {
+ switch (comparisonType)
+ {
+ case StringComparison.CurrentCulture:
+ return CurrentCulture;
+ case StringComparison.CurrentCultureIgnoreCase:
+ return CurrentCultureIgnoreCase;
+ case StringComparison.InvariantCulture:
+ return InvariantCulture;
+ case StringComparison.InvariantCultureIgnoreCase:
+ return InvariantCultureIgnoreCase;
+ case StringComparison.Ordinal:
+ return Ordinal;
+ case StringComparison.OrdinalIgnoreCase:
+ return OrdinalIgnoreCase;
+ default:
+ throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
+ }
+ }
+
public static StringComparer Create(CultureInfo culture, bool ignoreCase) {
if( culture == null) {
- throw new ArgumentNullException("culture");
+ throw new ArgumentNullException(nameof(culture));
}
Contract.Ensures(Contract.Result<StringComparer>() != null);
Contract.EndContractBlock();
@@ -110,7 +132,7 @@ namespace System {
public int GetHashCode(object obj) {
if( obj == null) {
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
@@ -161,7 +183,7 @@ namespace System {
public override int GetHashCode(string obj) {
if( obj == null) {
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
@@ -229,7 +251,7 @@ namespace System {
public override int GetHashCode(string obj) {
if( obj == null) {
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
@@ -311,7 +333,7 @@ namespace System {
public override int GetHashCode(string obj) {
if( obj == null) {
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
@@ -385,10 +407,9 @@ namespace System {
return x.Equals(y);
}
- [System.Security.SecuritySafeCritical]
public override int GetHashCode(string obj) {
if( obj == null) {
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/StubHelpers.cs b/src/mscorlib/src/System/StubHelpers.cs
index a9c584e9fc..26a227628a 100644
--- a/src/mscorlib/src/System/StubHelpers.cs
+++ b/src/mscorlib/src/System/StubHelpers.cs
@@ -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,12 +1641,11 @@ 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)
{
- throw new ArgumentNullException("pHandle", Environment.GetResourceString("ArgumentNull_SafeHandle"));
+ throw new ArgumentNullException(nameof(pHandle), Environment.GetResourceString("ArgumentNull_SafeHandle"));
}
Contract.EndContractBlock();
@@ -1790,13 +1655,12 @@ 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)
{
if (pHandle == null)
{
- throw new ArgumentNullException("pHandle", Environment.GetResourceString("ArgumentNull_SafeHandle"));
+ throw new ArgumentNullException(nameof(pHandle), Environment.GetResourceString("ArgumentNull_SafeHandle"));
}
Contract.EndContractBlock();
@@ -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
diff --git a/src/mscorlib/src/System/Text/ASCIIEncoding.cs b/src/mscorlib/src/System/Text/ASCIIEncoding.cs
index bf1a62df55..fc7589f2d8 100644
--- a/src/mscorlib/src/System/Text/ASCIIEncoding.cs
+++ b/src/mscorlib/src/System/Text/ASCIIEncoding.cs
@@ -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);
@@ -708,7 +701,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -721,7 +714,7 @@ namespace System.Text
// 1 to 1 for most characters. Only surrogates with fallbacks have less.
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
@@ -729,7 +722,7 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -741,7 +734,7 @@ namespace System.Text
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
diff --git a/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs b/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs
index 4c9ca6eaaf..0a42237dc1 100644
--- a/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs
+++ b/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Text/CodePageEncoding.cs b/src/mscorlib/src/System/Text/CodePageEncoding.cs
index 9f1b2d2620..7805c6580a 100644
--- a/src/mscorlib/src/System/Text/CodePageEncoding.cs
+++ b/src/mscorlib/src/System/Text/CodePageEncoding.cs
@@ -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==================================
@@ -44,7 +45,7 @@ namespace System.Text
internal CodePageEncoding(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All versions have a code page
@@ -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"));
}
@@ -113,25 +112,23 @@ namespace System.Text
internal Decoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
this.realEncoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
}
// 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"));
}
}
diff --git a/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs b/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs
index c103d7898f..28b85d591e 100644
--- a/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs
+++ b/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs
@@ -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");
@@ -1129,7 +1117,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1143,7 +1131,7 @@ namespace System.Text
byteCount *= 2;
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
@@ -1151,7 +1139,7 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1163,7 +1151,7 @@ namespace System.Text
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
diff --git a/src/mscorlib/src/System/Text/Decoder.cs b/src/mscorlib/src/System/Text/Decoder.cs
index f794dc4dce..0ebbacddcf 100644
--- a/src/mscorlib/src/System/Text/Decoder.cs
+++ b/src/mscorlib/src/System/Text/Decoder.cs
@@ -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,
@@ -49,13 +50,13 @@ namespace System.Text
set
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Can't change fallback if buffer is wrong
if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0)
throw new ArgumentException(
- Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), "value");
+ Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), nameof(value));
m_fallback = value;
m_fallbackBuffer = null;
@@ -124,18 +125,17 @@ 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)
{
// Validate input parameters
if (bytes == null)
- throw new ArgumentNullException("bytes",
+ throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -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,
@@ -197,11 +196,11 @@ namespace System.Text
{
// Validate input parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException(chars == null ? "chars" : "bytes",
+ throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"),
+ throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -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
@@ -256,23 +255,23 @@ namespace System.Text
{
// Validate parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException((bytes == null ? "bytes" : "chars"),
+ throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
+ throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
+ throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - byteIndex < byteCount)
- throw new ArgumentOutOfRangeException("bytes",
+ throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (chars.Length - charIndex < charCount)
- throw new ArgumentOutOfRangeException("chars",
+ throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
@@ -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,
@@ -315,11 +313,11 @@ namespace System.Text
{
// Validate input parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException(chars == null ? "chars" : "bytes",
+ throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"),
+ throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
index 5c1dcd9682..6389b4b141 100644
--- a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
@@ -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];
}
diff --git a/src/mscorlib/src/System/Text/DecoderFallback.cs b/src/mscorlib/src/System/Text/DecoderFallback.cs
index 1698fd37ab..42483a724d 100644
--- a/src/mscorlib/src/System/Text/DecoderFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderFallback.cs
@@ -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)))
@@ -277,7 +272,7 @@ namespace System.Text
// Throw it, using our complete bytes
throw new ArgumentException(
Environment.GetResourceString("Argument_RecursiveFallbackBytes",
- strBytes.ToString()), "bytesUnknown");
+ strBytes.ToString()), nameof(bytesUnknown));
}
}
diff --git a/src/mscorlib/src/System/Text/DecoderNLS.cs b/src/mscorlib/src/System/Text/DecoderNLS.cs
index c2e82dd250..e44c43adef 100644
--- a/src/mscorlib/src/System/Text/DecoderNLS.cs
+++ b/src/mscorlib/src/System/Text/DecoderNLS.cs
@@ -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,20 +76,19 @@ 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
if (bytes == null)
- throw new ArgumentNullException("bytes",
+ throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - index < count)
- throw new ArgumentOutOfRangeException("bytes",
+ throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
@@ -104,16 +102,15 @@ 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
if (bytes == null)
- throw new ArgumentNullException("bytes",
+ throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -131,25 +128,24 @@ 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)
{
// Validate Parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
+ throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ( bytes.Length - byteIndex < byteCount)
- throw new ArgumentOutOfRangeException("bytes",
+ throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (charIndex < 0 || charIndex > chars.Length)
- throw new ArgumentOutOfRangeException("charIndex",
+ throw new ArgumentOutOfRangeException(nameof(charIndex),
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
@@ -170,17 +166,16 @@ 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)
{
// Validate parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"),
+ throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -194,30 +189,29 @@ 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)
{
// Validate parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException((bytes == null ? "bytes" : "chars"),
+ throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
+ throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
+ throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - byteIndex < byteCount)
- throw new ArgumentOutOfRangeException("bytes",
+ throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (chars.Length - charIndex < charCount)
- throw new ArgumentOutOfRangeException("chars",
+ throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
@@ -241,18 +235,17 @@ 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)
{
// Validate input parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException(chars == null ? "chars" : "bytes",
+ throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"),
+ throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
index c732d15816..77c856046d 100644
--- a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
@@ -5,6 +5,7 @@
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
@@ -21,7 +22,7 @@ namespace System.Text
public DecoderReplacementFallback(String replacement)
{
if (replacement == null)
- throw new ArgumentNullException("replacement");
+ throw new ArgumentNullException(nameof(replacement));
Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
@@ -58,7 +59,7 @@ namespace System.Text
break;
}
if (bFoundHigh)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", "replacement"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", nameof(replacement)));
strDefault = replacement;
}
@@ -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*
diff --git a/src/mscorlib/src/System/Text/EUCJPEncoding.cs b/src/mscorlib/src/System/Text/EUCJPEncoding.cs
index 7c90caec0b..44345b22b9 100644
--- a/src/mscorlib/src/System/Text/EUCJPEncoding.cs
+++ b/src/mscorlib/src/System/Text/EUCJPEncoding.cs
@@ -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
diff --git a/src/mscorlib/src/System/Text/Encoder.cs b/src/mscorlib/src/System/Text/Encoder.cs
index d223dd9d46..b9d4581276 100644
--- a/src/mscorlib/src/System/Text/Encoder.cs
+++ b/src/mscorlib/src/System/Text/Encoder.cs
@@ -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,
@@ -49,13 +50,13 @@ namespace System.Text
set
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Can't change fallback if buffer is wrong
if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0)
throw new ArgumentException(
- Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), "value");
+ Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), nameof(value));
m_fallback = value;
m_fallbackBuffer = null;
@@ -120,18 +121,17 @@ 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)
{
// Validate input parameters
if (chars == null)
- throw new ArgumentNullException("chars",
+ throw new ArgumentNullException(nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -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,
@@ -190,11 +189,11 @@ namespace System.Text
{
// Validate input parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
+ throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -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
@@ -248,23 +247,23 @@ namespace System.Text
{
// Validate parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
+ throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
+ throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
- throw new ArgumentOutOfRangeException("chars",
+ throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (bytes.Length - byteIndex < byteCount)
- throw new ArgumentOutOfRangeException("bytes",
+ throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
@@ -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,
@@ -308,10 +306,10 @@ namespace System.Text
{
// Validate input parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
+ throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
index 352e9695cf..c5f82a299b 100644
--- a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
@@ -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);
@@ -117,7 +118,7 @@ namespace System.Text
{
// Double check input surrogate pair
if (!Char.IsHighSurrogate(charUnknownHigh))
- throw new ArgumentOutOfRangeException("charUnknownHigh",
+ throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
@@ -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];
}
diff --git a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
index 5ab51cb6dd..051f50ac7c 100644
--- a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
@@ -62,7 +62,7 @@ namespace System.Text
{
if (!Char.IsHighSurrogate(charUnknownHigh))
{
- throw new ArgumentOutOfRangeException("charUnknownHigh",
+ throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
}
@@ -145,13 +145,13 @@ namespace System.Text
{
if (!Char.IsHighSurrogate(charUnknownHigh))
{
- throw new ArgumentOutOfRangeException("charUnknownHigh",
+ throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
}
if (!Char.IsLowSurrogate(charUnknownLow))
{
- throw new ArgumentOutOfRangeException("CharUnknownLow",
+ throw new ArgumentOutOfRangeException(nameof(CharUnknownLow),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
}
diff --git a/src/mscorlib/src/System/Text/EncoderFallback.cs b/src/mscorlib/src/System/Text/EncoderFallback.cs
index 4b170414d5..db2bf93bdd 100644
--- a/src/mscorlib/src/System/Text/EncoderFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderFallback.cs
@@ -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
diff --git a/src/mscorlib/src/System/Text/EncoderNLS.cs b/src/mscorlib/src/System/Text/EncoderNLS.cs
index d5c52f48d8..2add017d68 100644
--- a/src/mscorlib/src/System/Text/EncoderNLS.cs
+++ b/src/mscorlib/src/System/Text/EncoderNLS.cs
@@ -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,20 +76,19 @@ 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
if (chars == null)
- throw new ArgumentNullException( "chars",
+ throw new ArgumentNullException(nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
+ throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - index < count)
- throw new ArgumentOutOfRangeException("chars",
+ throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
@@ -107,16 +105,15 @@ namespace System.Text
return result;
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe override int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
- throw new ArgumentNullException( "chars",
+ throw new ArgumentNullException(nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -125,25 +122,24 @@ 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)
{
// Validate parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
+ throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
- throw new ArgumentOutOfRangeException("chars",
+ throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (byteIndex < 0 || byteIndex > bytes.Length)
- throw new ArgumentOutOfRangeException("byteIndex",
+ throw new ArgumentOutOfRangeException(nameof(byteIndex),
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
@@ -163,16 +159,15 @@ 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
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"),
+ throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -183,30 +178,29 @@ 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)
{
// Validate parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
+ throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
+ throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
- throw new ArgumentOutOfRangeException("chars",
+ throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (bytes.Length - byteIndex < byteCount)
- throw new ArgumentOutOfRangeException("bytes",
+ throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
@@ -230,17 +224,16 @@ 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)
{
// Validate input parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
+ throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
index 15dfee8912..604cddf9bb 100644
--- a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
@@ -6,6 +6,7 @@ namespace System.Text
{
using System;
using System.Runtime;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
@@ -23,7 +24,7 @@ namespace System.Text
{
// Must not be null
if (replacement == null)
- throw new ArgumentNullException("replacement");
+ throw new ArgumentNullException(nameof(replacement));
Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
@@ -60,7 +61,7 @@ namespace System.Text
break;
}
if (bFoundHigh)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", "replacement"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", nameof(replacement)));
strDefault = replacement;
}
@@ -147,7 +148,7 @@ namespace System.Text
{
// Double check input surrogate pair
if (!Char.IsHighSurrogate(charUnknownHigh))
- throw new ArgumentOutOfRangeException("charUnknownHigh",
+ throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
@@ -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;
diff --git a/src/mscorlib/src/System/Text/Encoding.cs b/src/mscorlib/src/System/Text/Encoding.cs
index 8533016293..658bdbb133 100644
--- a/src/mscorlib/src/System/Text/Encoding.cs
+++ b/src/mscorlib/src/System/Text/Encoding.cs
@@ -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;
@@ -189,7 +190,7 @@ namespace System.Text
// Validate code page
if (codePage < 0)
{
- throw new ArgumentOutOfRangeException("codePage");
+ throw new ArgumentOutOfRangeException(nameof(codePage));
}
Contract.EndContractBlock();
@@ -208,7 +209,7 @@ namespace System.Text
// Validate code page
if (codePage < 0)
{
- throw new ArgumentOutOfRangeException("codePage");
+ throw new ArgumentOutOfRangeException(nameof(codePage));
}
Contract.EndContractBlock();
@@ -275,7 +276,7 @@ namespace System.Text
internal void DeserializeEncoding(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All versions have a code page
@@ -314,7 +315,7 @@ namespace System.Text
internal void SerializeEncoding(SerializationInfo info, StreamingContext context)
{
// Any Info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// These are new V2.0 Whidbey stuff
@@ -344,7 +345,7 @@ namespace System.Text
public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding,
byte[] bytes) {
if (bytes==null)
- throw new ArgumentNullException("bytes");
+ throw new ArgumentNullException(nameof(bytes));
Contract.Ensures(Contract.Result<byte[]>() != null);
return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length);
@@ -359,11 +360,11 @@ namespace System.Text
public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding,
byte[] bytes, int index, int count) {
if (srcEncoding == null || dstEncoding == null) {
- throw new ArgumentNullException((srcEncoding == null ? "srcEncoding" : "dstEncoding"),
+ throw new ArgumentNullException((srcEncoding == null ? nameof(srcEncoding) : nameof(dstEncoding)),
Environment.GetResourceString("ArgumentNull_Array"));
}
if (bytes == null) {
- throw new ArgumentNullException("bytes",
+ throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
}
Contract.Ensures(Contract.Result<byte[]>() != null);
@@ -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);
@@ -416,7 +411,7 @@ namespace System.Text
//
if (codepage < 0 || codepage > 65535) {
throw new ArgumentOutOfRangeException(
- "codepage", Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(codepage), Environment.GetResourceString("ArgumentOutOfRange_Range",
0, 65535));
}
@@ -443,7 +438,7 @@ namespace System.Text
case CodePageNoThread: // 3 CP_THREAD_ACP
case CodePageNoSymbol: // 42 CP_SYMBOL
throw new ArgumentException(Environment.GetResourceString(
- "Argument_CodepageNotSupported", codepage), "codepage");
+ "Argument_CodepageNotSupported", codepage), nameof(codepage));
}
#if FEATURE_CODEPAGES_FILE
@@ -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)
@@ -795,7 +788,7 @@ namespace System.Text
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
encoderFallback = value;
@@ -817,7 +810,7 @@ namespace System.Text
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
decoderFallback = value;
@@ -865,7 +858,7 @@ namespace System.Text
{
if (chars == null)
{
- throw new ArgumentNullException("chars",
+ throw new ArgumentNullException(nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
}
Contract.EndContractBlock();
@@ -876,8 +869,8 @@ namespace System.Text
[Pure]
public virtual int GetByteCount(String s)
{
- if (s==null)
- throw new ArgumentNullException("s");
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
Contract.EndContractBlock();
char[] chars = s.ToCharArray();
@@ -891,23 +884,50 @@ namespace System.Text
[Pure]
public abstract int GetByteCount(char[] chars, int index, int count);
+ // Returns the number of bytes required to encode a string range.
+ //
+ [Pure]
+ public int GetByteCount(string s, int index, int count)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s),
+ Environment.GetResourceString("ArgumentNull_String"));
+ if (index < 0)
+ throw new ArgumentOutOfRangeException(nameof(index),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (count < 0)
+ throw new ArgumentOutOfRangeException(nameof(count),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (index > s.Length - count)
+ throw new ArgumentOutOfRangeException(nameof(index),
+ Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
+ Contract.EndContractBlock();
+
+ unsafe
+ {
+ fixed (char* pChar = s)
+ {
+ return GetByteCount(pChar + index, count);
+ }
+ }
+ }
+
// 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 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)
{
// Validate input parameters
if (chars == null)
- throw new ArgumentNullException("chars",
+ throw new ArgumentNullException(nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -922,7 +942,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);
@@ -939,7 +958,7 @@ namespace System.Text
{
if (chars == null)
{
- throw new ArgumentNullException("chars",
+ throw new ArgumentNullException(nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
}
Contract.EndContractBlock();
@@ -976,29 +995,67 @@ namespace System.Text
public virtual byte[] GetBytes(String s)
{
if (s == null)
- throw new ArgumentNullException("s",
+ throw new ArgumentNullException(nameof(s),
Environment.GetResourceString("ArgumentNull_String"));
Contract.EndContractBlock();
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;
}
+ // Returns a byte array containing the encoded representation of the given
+ // string range.
+ //
+ [Pure]
+ public byte[] GetBytes(string s, int index, int count)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s),
+ Environment.GetResourceString("ArgumentNull_String"));
+ if (index < 0)
+ throw new ArgumentOutOfRangeException(nameof(index),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (count < 0)
+ throw new ArgumentOutOfRangeException(nameof(count),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (index > s.Length - count)
+ throw new ArgumentOutOfRangeException(nameof(index),
+ Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
+ Contract.EndContractBlock();
+
+ unsafe
+ {
+ fixed (char* pChar = s)
+ {
+ int byteCount = GetByteCount(pChar + index, count);
+ if (byteCount == 0)
+ return Array.Empty<byte>();
+
+ byte[] bytes = new byte[byteCount];
+ fixed (byte* pBytes = &bytes[0])
+ {
+ int bytesReceived = GetBytes(pChar + index, count, pBytes, byteCount);
+ Debug.Assert(byteCount == bytesReceived);
+ }
+ return bytes;
+ }
+ }
+ }
+
public virtual int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
- if (s==null)
- throw new ArgumentNullException("s");
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
Contract.EndContractBlock();
return GetBytes(s.ToCharArray(), charIndex, charCount, bytes, byteIndex);
}
// 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 +1079,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,
@@ -1030,11 +1086,11 @@ namespace System.Text
{
// Validate input parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
+ throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1051,7 +1107,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
@@ -1076,7 +1132,7 @@ namespace System.Text
{
if (bytes == null)
{
- throw new ArgumentNullException("bytes",
+ throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
}
Contract.EndContractBlock();
@@ -1092,18 +1148,17 @@ 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)
{
// Validate input parameters
if (bytes == null)
- throw new ArgumentNullException("bytes",
+ throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
- throw new ArgumentOutOfRangeException("count",
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1118,7 +1173,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);
@@ -1132,7 +1186,7 @@ namespace System.Text
{
if (bytes == null)
{
- throw new ArgumentNullException("bytes",
+ throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
}
Contract.EndContractBlock();
@@ -1181,7 +1235,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,
@@ -1189,11 +1242,11 @@ namespace System.Text
{
// Validate input parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException(chars == null ? "chars" : "bytes",
+ throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"),
+ throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1210,7 +1263,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 +1283,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,16 +1290,15 @@ namespace System.Text
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public unsafe string GetString(byte* bytes, int byteCount)
{
if (bytes == null)
- throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return String.CreateStringFromEncoding(bytes, byteCount, this);
@@ -1306,7 +1357,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
@@ -1391,7 +1441,7 @@ namespace System.Text
public virtual String GetString(byte[] bytes)
{
if (bytes == null)
- throw new ArgumentNullException("bytes",
+ throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
Contract.EndContractBlock();
@@ -1482,7 +1532,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 +1556,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)
@@ -1541,7 +1589,7 @@ namespace System.Text
// Constructor called by serialization, have to handle deserializing from Everett
internal DefaultEncoder(SerializationInfo info, StreamingContext context)
{
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All we have is our encoding
@@ -1558,7 +1606,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,11 +1631,10 @@ 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?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All we have is our encoding
@@ -1608,7 +1654,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 +1686,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)
@@ -1667,7 +1711,7 @@ namespace System.Text
internal DefaultDecoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All we have is our encoding
@@ -1684,7 +1728,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,11 +1748,10 @@ 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?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All we have is our encoding
@@ -1733,7 +1775,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 +1811,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 +1822,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 +1854,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 +1877,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 +1896,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 +1903,6 @@ namespace System.Text
internal unsafe bool MoreData
{
- [System.Security.SecurityCritical] // auto-generated
get
{
return bytes < byteEnd;
@@ -1882,7 +1910,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 +1917,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 +1927,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 +1942,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 +1951,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 +1960,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 +1995,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 +2034,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 +2052,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 +2079,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 +2087,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 +2104,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 +2112,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 +2119,6 @@ namespace System.Text
}
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe char GetNextChar()
{
// See if there's something in our fallback buffer
@@ -2133,7 +2136,6 @@ namespace System.Text
internal unsafe int CharsUsed
{
- [System.Security.SecurityCritical] // auto-generated
get
{
return (int)(chars - charStart);
diff --git a/src/mscorlib/src/System/Text/EncodingForwarder.cs b/src/mscorlib/src/System/Text/EncodingForwarder.cs
index d4bcf800e3..9a8dd26627 100644
--- a/src/mscorlib/src/System/Text/EncodingForwarder.cs
+++ b/src/mscorlib/src/System/Text/EncodingForwarder.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
@@ -31,23 +32,22 @@ 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("chars", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
}
if (index < 0 || count < 0)
{
- throw new ArgumentOutOfRangeException(index < 0 ? "index" : "count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (chars.Length - index < count)
{
- throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
}
Contract.EndContractBlock();
@@ -60,13 +60,12 @@ 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" : "s"; // ASCIIEncoding calls the string chars
+ string paramName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the string chars
// UTF8Encoding does this as well, but it originally threw an ArgumentNull for "s" so don't check for that
throw new ArgumentNullException(paramName);
}
@@ -84,17 +83,16 @@ 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("chars", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
}
if (count < 0)
{
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
@@ -102,28 +100,27 @@ 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" : "s"; // ASCIIEncoding calls the first parameter chars
- throw new ArgumentNullException(s == null ? stringName : "bytes", Environment.GetResourceString("ArgumentNull_Array"));
+ string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars
+ throw new ArgumentNullException(s == null ? stringName : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
}
if (charIndex < 0 || charCount < 0)
{
- throw new ArgumentOutOfRangeException(charIndex < 0 ? "charIndex" : "charCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (s.Length - charIndex < charCount)
{
- string stringName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the first parameter chars
+ string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars
// Duplicate the above check since we don't want the overhead of a type check on the general path
throw new ArgumentOutOfRangeException(stringName, Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
}
if (byteIndex < 0 || byteIndex > bytes.Length)
{
- throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(byteIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
@@ -139,25 +136,24 @@ 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 ? "chars" : "bytes", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
}
if (charIndex < 0 || charCount < 0)
{
- throw new ArgumentOutOfRangeException(charIndex < 0 ? "charIndex" : "charCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (chars.Length - charIndex < charCount)
{
- throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
}
if (byteIndex < 0 || byteIndex > bytes.Length)
{
- throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(byteIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
@@ -180,38 +176,36 @@ 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 ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
}
if (charCount < 0 || byteCount < 0)
{
- throw new ArgumentOutOfRangeException(charCount < 0 ? "charCount" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
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("bytes", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
}
if (index < 0 || count < 0)
{
- throw new ArgumentOutOfRangeException(index < 0 ? "index" : "count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (bytes.Length - index < count)
{
- throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
}
Contract.EndContractBlock();
@@ -224,42 +218,40 @@ 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("bytes", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
}
if (count < 0)
{
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
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 ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
}
if (byteIndex < 0 || byteCount < 0)
{
- throw new ArgumentOutOfRangeException(byteIndex < 0 ? "byteIndex" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (bytes.Length - byteIndex < byteCount)
{
- throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
}
if (charIndex < 0 || charIndex > chars.Length)
{
- throw new ArgumentOutOfRangeException("charIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(charIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
@@ -280,42 +272,40 @@ 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 ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
}
if (charCount < 0 || byteCount < 0)
{
- throw new ArgumentOutOfRangeException(charCount < 0 ? "charCount" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
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("bytes", Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
}
if (index < 0 || count < 0)
{
// ASCIIEncoding has different names for its parameters here (byteIndex, byteCount)
bool ascii = encoding is ASCIIEncoding;
- string indexName = ascii ? "byteIndex" : "index";
- string countName = ascii ? "byteCount" : "count";
+ string indexName = ascii ? "byteIndex" : nameof(index);
+ string countName = ascii ? "byteCount" : nameof(count);
throw new ArgumentOutOfRangeException(index < 0 ? indexName : countName, Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (bytes.Length - index < count)
{
- throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Text/EncodingNLS.cs b/src/mscorlib/src/System/Text/EncodingNLS.cs
index d670d6daa7..fbddf37e88 100644
--- a/src/mscorlib/src/System/Text/EncodingNLS.cs
+++ b/src/mscorlib/src/System/Text/EncodingNLS.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Text/EncodingProvider.cs b/src/mscorlib/src/System/Text/EncodingProvider.cs
index b1dea2cd3c..a7f745a753 100644
--- a/src/mscorlib/src/System/Text/EncodingProvider.cs
+++ b/src/mscorlib/src/System/Text/EncodingProvider.cs
@@ -45,7 +45,7 @@ namespace System.Text
internal static void AddProvider(EncodingProvider provider)
{
if (provider == null)
- throw new ArgumentNullException("provider");
+ throw new ArgumentNullException(nameof(provider));
lock (s_InternalSyncObject)
{
diff --git a/src/mscorlib/src/System/Text/GB18030Encoding.cs b/src/mscorlib/src/System/Text/GB18030Encoding.cs
index 98746fcdb0..8ed52a6ab8 100644
--- a/src/mscorlib/src/System/Text/GB18030Encoding.cs
+++ b/src/mscorlib/src/System/Text/GB18030Encoding.cs
@@ -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;
@@ -793,7 +783,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -807,7 +797,7 @@ namespace System.Text
byteCount *= 4;
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
@@ -815,7 +805,7 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -828,7 +818,7 @@ namespace System.Text
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
@@ -852,11 +842,10 @@ 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?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
try
@@ -879,11 +868,10 @@ 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?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Save Whidbey data
diff --git a/src/mscorlib/src/System/Text/ISCIIEncoding.cs b/src/mscorlib/src/System/Text/ISCIIEncoding.cs
index 89d9c9953a..751b8217c0 100644
--- a/src/mscorlib/src/System/Text/ISCIIEncoding.cs
+++ b/src/mscorlib/src/System/Text/ISCIIEncoding.cs
@@ -9,6 +9,7 @@
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.Serialization;
@@ -72,13 +73,13 @@ 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
if (defaultCodePage < CodeDevanagari || defaultCodePage > CodePunjabi)
throw new ArgumentException(Environment.GetResourceString(
- "Argument_CodepageNotSupported", codePage), "codePage");
+ "Argument_CodepageNotSupported", codePage), nameof(codePage));
}
// Constructor called by serialization.
@@ -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);
@@ -111,7 +111,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -125,7 +125,7 @@ namespace System.Text
byteCount *= 4;
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
@@ -135,7 +135,7 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -149,13 +149,12 @@ namespace System.Text
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
// 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;
diff --git a/src/mscorlib/src/System/Text/ISO2022Encoding.cs b/src/mscorlib/src/System/Text/ISO2022Encoding.cs
index fe57e7cc57..fca579fe56 100644
--- a/src/mscorlib/src/System/Text/ISO2022Encoding.cs
+++ b/src/mscorlib/src/System/Text/ISO2022Encoding.cs
@@ -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;
@@ -1754,7 +1742,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1801,7 +1789,7 @@ namespace System.Text
byteCount += extraStart + extraEnd;
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
@@ -1809,7 +1797,7 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1839,7 +1827,7 @@ namespace System.Text
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
diff --git a/src/mscorlib/src/System/Text/Latin1Encoding.cs b/src/mscorlib/src/System/Text/Latin1Encoding.cs
index a24f9c00ae..56a6c1f949 100644
--- a/src/mscorlib/src/System/Text/Latin1Encoding.cs
+++ b/src/mscorlib/src/System/Text/Latin1Encoding.cs
@@ -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)
@@ -446,7 +442,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -459,14 +455,14 @@ namespace System.Text
// 1 to 1 for most characters. Only surrogates with fallbacks have less.
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -478,7 +474,7 @@ namespace System.Text
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
diff --git a/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs b/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs
index 53924a936d..a82db91b98 100644
--- a/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs
+++ b/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs
@@ -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==================================
@@ -46,7 +47,7 @@ namespace System.Text
internal MLangCodePageEncoding(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All versions have a code page
@@ -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"));
}
@@ -115,25 +114,23 @@ namespace System.Text
internal MLangEncoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
this.realEncoding = (Encoding)info.GetValue("m_encoding", typeof(Encoding));
}
// 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"));
}
}
@@ -151,25 +148,23 @@ namespace System.Text
internal MLangDecoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
this.realEncoding = (Encoding)info.GetValue("m_encoding", typeof(Encoding));
}
// 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"));
}
}
diff --git a/src/mscorlib/src/System/Text/Normalization.Unix.cs b/src/mscorlib/src/System/Text/Normalization.Unix.cs
new file mode 100644
index 0000000000..d49bdc6c21
--- /dev/null
+++ b/src/mscorlib/src/System/Text/Normalization.Unix.cs
@@ -0,0 +1,123 @@
+// 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.Security;
+using System.Text;
+
+namespace System.Text
+{
+ static partial class Normalization
+ {
+ public static bool IsNormalized(this string strInput, NormalizationForm normalizationForm)
+ {
+ ValidateArguments(strInput, normalizationForm);
+
+ int ret = Interop.GlobalizationInterop.IsNormalized(normalizationForm, strInput, strInput.Length);
+
+ if (ret == -1)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput));
+ }
+
+ return ret == 1;
+ }
+
+ public static string Normalize(this string strInput, NormalizationForm normalizationForm)
+ {
+ ValidateArguments(strInput, normalizationForm);
+
+ char[] buf = new char[strInput.Length];
+
+ for (int attempts = 2; attempts > 0; attempts--)
+ {
+ int realLen = Interop.GlobalizationInterop.NormalizeString(normalizationForm, strInput, strInput.Length, buf, buf.Length);
+
+ if (realLen == -1)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput));
+ }
+
+ if (realLen <= buf.Length)
+ {
+ return new string(buf, 0, realLen);
+ }
+
+ buf = new char[realLen];
+ }
+
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput));
+ }
+
+ // -----------------------------
+ // ---- PAL layer ends here ----
+ // -----------------------------
+
+ private static void ValidateArguments(string strInput, NormalizationForm normalizationForm)
+ {
+ if (strInput == null)
+ {
+ throw new ArgumentNullException(nameof(strInput));
+ }
+
+ if (normalizationForm != NormalizationForm.FormC && normalizationForm != NormalizationForm.FormD &&
+ normalizationForm != NormalizationForm.FormKC && normalizationForm != NormalizationForm.FormKD)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNormalizationForm"), nameof(normalizationForm));
+ }
+
+ if (HasInvalidUnicodeSequence(strInput))
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput));
+ }
+ }
+
+ /// <summary>
+ /// ICU does not signal an error during normalization if the input string has invalid unicode,
+ /// unlike Windows (which uses the ERROR_NO_UNICODE_TRANSLATION error value to signal an error).
+ ///
+ /// We walk the string ourselves looking for these bad sequences so we can continue to throw
+ /// ArgumentException in these cases.
+ /// </summary>
+ private static bool HasInvalidUnicodeSequence(string s)
+ {
+ for (int i = 0; i < s.Length; i++)
+ {
+ char c = s[i];
+
+ if (c < '\ud800')
+ {
+ continue;
+ }
+
+ if (c == '\uFFFE')
+ {
+ return true;
+ }
+
+ // If we see low surrogate before a high one, the string is invalid.
+ if (char.IsLowSurrogate(c))
+ {
+ return true;
+ }
+
+ if (char.IsHighSurrogate(c))
+ {
+ if (i + 1 >= s.Length || !char.IsLowSurrogate(s[i + 1]))
+ {
+ // A high surrogate at the end of the string or a high surrogate
+ // not followed by a low surrogate
+ return true;
+ }
+ else
+ {
+ i++; // consume the low surrogate.
+ continue;
+ }
+ }
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Text/Normalization.Windows.cs b/src/mscorlib/src/System/Text/Normalization.Windows.cs
new file mode 100644
index 0000000000..b2faf0db68
--- /dev/null
+++ b/src/mscorlib/src/System/Text/Normalization.Windows.cs
@@ -0,0 +1,286 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Text
+{
+ using System;
+ using System.Security;
+ using System.Globalization;
+ using 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
+
+ internal class Normalization
+ {
+ //
+ // Flags that track whether given normalization form was initialized
+ //
+#if !FEATURE_NORM_IDNA_ONLY
+ private static volatile bool NFC;
+ private static volatile bool NFD;
+ private static volatile bool NFKC;
+ private static volatile bool NFKD;
+#endif // !FEATURE_NORM_IDNA_ONLY
+ private static volatile bool IDNA;
+#if !FEATURE_NORM_IDNA_ONLY
+ private static volatile bool NFCDisallowUnassigned;
+ private static volatile bool NFDDisallowUnassigned;
+ private static volatile bool NFKCDisallowUnassigned;
+ private static volatile bool NFKDDisallowUnassigned;
+#endif // !FEATURE_NORM_IDNA_ONLY
+ private static volatile bool IDNADisallowUnassigned;
+ private static volatile bool Other;
+
+ // These are error codes we get back from the Normalization DLL
+ private const int ERROR_SUCCESS = 0;
+ private const int ERROR_NOT_ENOUGH_MEMORY = 8;
+ private const int ERROR_INVALID_PARAMETER = 87;
+ private const int ERROR_INSUFFICIENT_BUFFER = 122;
+ private const int ERROR_NO_UNICODE_TRANSLATION = 1113;
+
+ static private unsafe void InitializeForm(NormalizationForm form, String strDataFile)
+ {
+ byte* pTables = null;
+
+ // Normalization uses OS on Win8
+ if (!Environment.IsWindows8OrAbove)
+ {
+ if (strDataFile == null)
+ {
+ // They were supposed to have a form that we know about!
+ throw new ArgumentException(
+ Environment.GetResourceString("Argument_InvalidNormalizationForm"));
+ }
+
+ // Tell the DLL where to find our data
+ pTables = GlobalizationAssembly.GetGlobalizationResourceBytePtr(
+ typeof(Normalization).Assembly, strDataFile);
+ if (pTables == null)
+ {
+ // Unable to load the specified normalizationForm,
+ // tables not loaded from file
+ throw new ArgumentException(
+ Environment.GetResourceString("Argument_InvalidNormalizationForm"));
+ }
+ }
+
+ nativeNormalizationInitNormalization(form, pTables);
+ }
+
+ static private void EnsureInitialized(NormalizationForm form)
+ {
+ switch ((ExtendedNormalizationForms)form)
+ {
+#if !FEATURE_NORM_IDNA_ONLY
+ case ExtendedNormalizationForms.FormC:
+ if (NFC) return;
+ InitializeForm(form, "normnfc.nlp");
+ NFC = true;
+ break;
+
+ case ExtendedNormalizationForms.FormD:
+ if (NFD) return;
+ InitializeForm(form, "normnfd.nlp");
+ NFD = true;
+ break;
+
+ case ExtendedNormalizationForms.FormKC:
+ if (NFKC) return;
+ InitializeForm(form, "normnfkc.nlp");
+ NFKC = true;
+ break;
+
+ case ExtendedNormalizationForms.FormKD:
+ if (NFKD) return;
+ InitializeForm(form, "normnfkd.nlp");
+ NFKD = true;
+ break;
+#endif // !FEATURE_NORM_IDNA_ONLY
+
+ case ExtendedNormalizationForms.FormIdna:
+ if (IDNA) return;
+ InitializeForm(form, "normidna.nlp");
+ IDNA = true;
+ break;
+
+#if !FEATURE_NORM_IDNA_ONLY
+ case ExtendedNormalizationForms.FormCDisallowUnassigned:
+ if (NFCDisallowUnassigned) return;
+ InitializeForm(form, "normnfc.nlp");
+ NFCDisallowUnassigned = true;
+ break;
+
+ case ExtendedNormalizationForms.FormDDisallowUnassigned:
+ if (NFDDisallowUnassigned) return;
+ InitializeForm(form, "normnfd.nlp");
+ NFDDisallowUnassigned = true;
+ break;
+
+ case ExtendedNormalizationForms.FormKCDisallowUnassigned:
+ if (NFKCDisallowUnassigned) return;
+ InitializeForm(form, "normnfkc.nlp");
+ NFKCDisallowUnassigned = true;
+ break;
+
+ case ExtendedNormalizationForms.FormKDDisallowUnassigned:
+ if (NFKDDisallowUnassigned) return;
+ InitializeForm(form, "normnfkd.nlp");
+ NFKDDisallowUnassigned = true;
+ break;
+#endif // !FEATURE_NORM_IDNA_ONLY
+
+ case ExtendedNormalizationForms.FormIdnaDisallowUnassigned:
+ if (IDNADisallowUnassigned) return;
+ InitializeForm(form, "normidna.nlp");
+ IDNADisallowUnassigned = true;
+ break;
+
+ default:
+ if (Other) return;
+ InitializeForm(form, null);
+ Other = true;
+ break;
+ }
+ }
+
+ internal static bool IsNormalized(String strInput, NormalizationForm normForm)
+ {
+ Contract.Requires(strInput != null);
+
+ EnsureInitialized(normForm);
+
+ int iError = ERROR_SUCCESS;
+ bool result = nativeNormalizationIsNormalizedString(
+ normForm,
+ ref iError,
+ strInput,
+ strInput.Length);
+
+ switch(iError)
+ {
+ // Success doesn't need to do anything
+ case ERROR_SUCCESS:
+ break;
+
+ // Do appropriate stuff for the individual errors:
+ case ERROR_INVALID_PARAMETER:
+ case ERROR_NO_UNICODE_TRANSLATION:
+ throw new ArgumentException(
+ Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
+ nameof(strInput));
+ case ERROR_NOT_ENOUGH_MEMORY:
+ throw new OutOfMemoryException(
+ Environment.GetResourceString("Arg_OutOfMemoryException"));
+ default:
+ throw new InvalidOperationException(
+ Environment.GetResourceString("UnknownError_Num", iError));
+ }
+
+ return result;
+ }
+
+ internal static String Normalize(String strInput, NormalizationForm normForm)
+ {
+ Contract.Requires(strInput != null);
+
+ EnsureInitialized(normForm);
+
+ int iError = ERROR_SUCCESS;
+
+ // Guess our buffer size first
+ int iLength = nativeNormalizationNormalizeString(normForm, ref iError, strInput, strInput.Length, null, 0);
+
+ // Could have an error (actually it'd be quite hard to have an error here)
+ if (iError != ERROR_SUCCESS)
+ {
+ if (iError == ERROR_INVALID_PARAMETER)
+ throw new ArgumentException(
+ Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
+ nameof(strInput));
+
+ // We shouldn't really be able to get here..., guessing length is
+ // a trivial math function...
+ // Can't really be Out of Memory, but just in case:
+ if (iError == ERROR_NOT_ENOUGH_MEMORY)
+ throw new OutOfMemoryException(
+ Environment.GetResourceString("Arg_OutOfMemoryException"));
+
+ // Who knows what happened? Not us!
+ throw new InvalidOperationException(
+ Environment.GetResourceString("UnknownError_Num", iError));
+ }
+
+ // Don't break for empty strings (only possible for D & KD and not really possible at that)
+ if (iLength == 0) return String.Empty;
+
+ // Someplace to stick our buffer
+ char[] cBuffer = null;
+
+ for (;;)
+ {
+ // (re)allocation buffer and normalize string
+ cBuffer = new char[iLength];
+
+ iLength = nativeNormalizationNormalizeString(
+ normForm,
+ ref iError,
+ strInput,
+ strInput.Length,
+ cBuffer,
+ cBuffer.Length);
+
+ if (iError == ERROR_SUCCESS)
+ break;
+
+ // Could have an error (actually it'd be quite hard to have an error here)
+ switch(iError)
+ {
+ // Do appropriate stuff for the individual errors:
+ case ERROR_INSUFFICIENT_BUFFER:
+ Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
+ continue;
+
+ case ERROR_INVALID_PARAMETER:
+ case ERROR_NO_UNICODE_TRANSLATION:
+ // Illegal code point or order found. Ie: FFFE or D800 D800, etc.
+ throw new ArgumentException(
+ Environment.GetResourceString("Argument_InvalidCharSequence", iLength ),
+ nameof(strInput));
+ case ERROR_NOT_ENOUGH_MEMORY:
+ throw new OutOfMemoryException(
+ Environment.GetResourceString("Arg_OutOfMemoryException"));
+
+ default:
+ // We shouldn't get here...
+ throw new InvalidOperationException(
+ Environment.GetResourceString("UnknownError_Num", iError));
+ }
+ }
+
+ // Copy our buffer into our new string, which will be the appropriate size
+ return new String(cBuffer, 0, iLength);
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ unsafe private static extern int nativeNormalizationNormalizeString(
+ NormalizationForm normForm, ref int iError,
+ String lpSrcString, int cwSrcLength,
+ char[] lpDstString, int cwDstLength);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ unsafe private static extern bool nativeNormalizationIsNormalizedString(
+ NormalizationForm normForm, ref int iError,
+ String lpString, int cwLength);
+
+ [SuppressUnmanagedCodeSecurity]
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ unsafe private static extern void nativeNormalizationInitNormalization(
+ NormalizationForm normForm, byte* pTableData);
+ }
+}
diff --git a/src/mscorlib/src/System/Text/Normalization.cs b/src/mscorlib/src/System/Text/Normalization.cs
index ce3c0c8e32..e7e733a587 100644
--- a/src/mscorlib/src/System/Text/Normalization.cs
+++ b/src/mscorlib/src/System/Text/Normalization.cs
@@ -4,15 +4,6 @@
namespace System.Text
{
- using System;
- using System.Security;
- using System.Globalization;
- using System.Text;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
// This is the enumeration for Normalization Forms
[System.Runtime.InteropServices.ComVisible(true)]
public enum NormalizationForm
@@ -42,309 +33,4 @@ namespace System.Text
#endif // !FEATURE_NORM_IDNA_ONLY
FormIdnaDisallowUnassigned = 0x10d
}
-
- // This internal class wraps up our normalization behavior
-
- internal class Normalization
- {
- //
- // Flags that track whether given normalization form was initialized
- //
-#if !FEATURE_NORM_IDNA_ONLY
- private static volatile bool NFC;
- private static volatile bool NFD;
- private static volatile bool NFKC;
- private static volatile bool NFKD;
-#endif // !FEATURE_NORM_IDNA_ONLY
- private static volatile bool IDNA;
-#if !FEATURE_NORM_IDNA_ONLY
- private static volatile bool NFCDisallowUnassigned;
- private static volatile bool NFDDisallowUnassigned;
- private static volatile bool NFKCDisallowUnassigned;
- private static volatile bool NFKDDisallowUnassigned;
-#endif // !FEATURE_NORM_IDNA_ONLY
- private static volatile bool IDNADisallowUnassigned;
- private static volatile bool Other;
-
- // These are error codes we get back from the Normalization DLL
- private const int ERROR_SUCCESS = 0;
- private const int ERROR_NOT_ENOUGH_MEMORY = 8;
- private const int ERROR_INVALID_PARAMETER = 87;
- 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)
- {
-#if FEATURE_COREFX_GLOBALIZATION
- //TODO: Implement this fully. We might need a PAL here.
- throw new NotImplementedException();
-#else
- byte* pTables = null;
-
- // Normalization uses OS on Win8
- if (!Environment.IsWindows8OrAbove)
- {
- if (strDataFile == null)
- {
- // They were supposed to have a form that we know about!
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidNormalizationForm"));
- }
-
- // Tell the DLL where to find our data
- pTables = GlobalizationAssembly.GetGlobalizationResourceBytePtr(
- typeof(Normalization).Assembly, strDataFile);
- if (pTables == null)
- {
- // Unable to load the specified normalizationForm,
- // tables not loaded from file
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidNormalizationForm"));
- }
- }
-
- nativeNormalizationInitNormalization(form, pTables);
-#endif
- }
-
- [System.Security.SecurityCritical] // auto-generated
- static private void EnsureInitialized(NormalizationForm form)
- {
- switch ((ExtendedNormalizationForms)form)
- {
-#if !FEATURE_NORM_IDNA_ONLY
- case ExtendedNormalizationForms.FormC:
- if (NFC) return;
- InitializeForm(form, "normnfc.nlp");
- NFC = true;
- break;
-
- case ExtendedNormalizationForms.FormD:
- if (NFD) return;
- InitializeForm(form, "normnfd.nlp");
- NFD = true;
- break;
-
- case ExtendedNormalizationForms.FormKC:
- if (NFKC) return;
- InitializeForm(form, "normnfkc.nlp");
- NFKC = true;
- break;
-
- case ExtendedNormalizationForms.FormKD:
- if (NFKD) return;
- InitializeForm(form, "normnfkd.nlp");
- NFKD = true;
- break;
-#endif // !FEATURE_NORM_IDNA_ONLY
-
- case ExtendedNormalizationForms.FormIdna:
- if (IDNA) return;
- InitializeForm(form, "normidna.nlp");
- IDNA = true;
- break;
-
-#if !FEATURE_NORM_IDNA_ONLY
- case ExtendedNormalizationForms.FormCDisallowUnassigned:
- if (NFCDisallowUnassigned) return;
- InitializeForm(form, "normnfc.nlp");
- NFCDisallowUnassigned = true;
- break;
-
- case ExtendedNormalizationForms.FormDDisallowUnassigned:
- if (NFDDisallowUnassigned) return;
- InitializeForm(form, "normnfd.nlp");
- NFDDisallowUnassigned = true;
- break;
-
- case ExtendedNormalizationForms.FormKCDisallowUnassigned:
- if (NFKCDisallowUnassigned) return;
- InitializeForm(form, "normnfkc.nlp");
- NFKCDisallowUnassigned = true;
- break;
-
- case ExtendedNormalizationForms.FormKDDisallowUnassigned:
- if (NFKDDisallowUnassigned) return;
- InitializeForm(form, "normnfkd.nlp");
- NFKDDisallowUnassigned = true;
- break;
-#endif // !FEATURE_NORM_IDNA_ONLY
-
- case ExtendedNormalizationForms.FormIdnaDisallowUnassigned:
- if (IDNADisallowUnassigned) return;
- InitializeForm(form, "normidna.nlp");
- IDNADisallowUnassigned = true;
- break;
-
- default:
- if (Other) return;
- InitializeForm(form, null);
- Other = true;
- break;
- }
- }
-
- [System.Security.SecurityCritical]
- internal static bool IsNormalized(String strInput, NormalizationForm normForm)
- {
- Contract.Requires(strInput != null);
-
- EnsureInitialized(normForm);
-
- int iError = ERROR_SUCCESS;
- bool result = nativeNormalizationIsNormalizedString(
- normForm,
- ref iError,
- strInput,
- strInput.Length);
-
- switch(iError)
- {
- // Success doesn't need to do anything
- case ERROR_SUCCESS:
- break;
-
- // Do appropriate stuff for the individual errors:
- case ERROR_INVALID_PARAMETER:
- case ERROR_NO_UNICODE_TRANSLATION:
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
- "strInput");
- case ERROR_NOT_ENOUGH_MEMORY:
- throw new OutOfMemoryException(
- Environment.GetResourceString("Arg_OutOfMemoryException"));
- default:
- throw new InvalidOperationException(
- Environment.GetResourceString("UnknownError_Num", iError));
- }
-
- return result;
- }
-
- [System.Security.SecurityCritical]
- internal static String Normalize(String strInput, NormalizationForm normForm)
- {
- Contract.Requires(strInput != null);
-
- EnsureInitialized(normForm);
-
- int iError = ERROR_SUCCESS;
-
- // Guess our buffer size first
- int iLength = nativeNormalizationNormalizeString(normForm, ref iError, strInput, strInput.Length, null, 0);
-
- // Could have an error (actually it'd be quite hard to have an error here)
- if (iError != ERROR_SUCCESS)
- {
- if (iError == ERROR_INVALID_PARAMETER)
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
- "strInput");
-
- // We shouldn't really be able to get here..., guessing length is
- // a trivial math function...
- // Can't really be Out of Memory, but just in case:
- if (iError == ERROR_NOT_ENOUGH_MEMORY)
- throw new OutOfMemoryException(
- Environment.GetResourceString("Arg_OutOfMemoryException"));
-
- // Who knows what happened? Not us!
- throw new InvalidOperationException(
- Environment.GetResourceString("UnknownError_Num", iError));
- }
-
- // Don't break for empty strings (only possible for D & KD and not really possible at that)
- if (iLength == 0) return String.Empty;
-
- // Someplace to stick our buffer
- char[] cBuffer = null;
-
- for (;;)
- {
- // (re)allocation buffer and normalize string
- cBuffer = new char[iLength];
-
- iLength = nativeNormalizationNormalizeString(
- normForm,
- ref iError,
- strInput,
- strInput.Length,
- cBuffer,
- cBuffer.Length);
-
- if (iError == ERROR_SUCCESS)
- break;
-
- // Could have an error (actually it'd be quite hard to have an error here)
- switch(iError)
- {
- // Do appropriate stuff for the individual errors:
- case ERROR_INSUFFICIENT_BUFFER:
- Contract.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
- continue;
-
- case ERROR_INVALID_PARAMETER:
- case ERROR_NO_UNICODE_TRANSLATION:
- // Illegal code point or order found. Ie: FFFE or D800 D800, etc.
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequence", iLength ),
- "strInput");
- case ERROR_NOT_ENOUGH_MEMORY:
- throw new OutOfMemoryException(
- Environment.GetResourceString("Arg_OutOfMemoryException"));
-
- default:
- // We shouldn't get here...
- throw new InvalidOperationException(
- Environment.GetResourceString("UnknownError_Num", iError));
- }
- }
-
- // Copy our buffer into our new string, which will be the appropriate size
- return new String(cBuffer, 0, iLength);
- }
-
-#if !FEATURE_COREFX_GLOBALIZATION
- [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(
- NormalizationForm normForm, byte* pTableData);
-#else
- unsafe private static int nativeNormalizationNormalizeString(
- NormalizationForm normForm, ref int iError,
- String lpSrcString, int cwSrcLength,
- char[] lpDstString, int cwDstLength)
- {
- throw new NotImplementedException();
- }
-
- unsafe private static bool nativeNormalizationIsNormalizedString(
- NormalizationForm normForm, ref int iError,
- String lpString, int cwLength)
- {
- throw new NotImplementedException();
- }
-
- unsafe private static void nativeNormalizationInitNormalization(
- NormalizationForm normForm, byte* pTableData)
- {
- throw new NotImplementedException();
- }
-#endif
- }
}
diff --git a/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs b/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs
index ce611d8b1f..8b07149fb7 100644
--- a/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs
+++ b/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs
@@ -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);
@@ -892,7 +881,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -905,14 +894,14 @@ namespace System.Text
// 1 to 1 for most characters. Only surrogates with fallbacks have less.
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -924,7 +913,7 @@ namespace System.Text
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
diff --git a/src/mscorlib/src/System/Text/StringBuilder.cs b/src/mscorlib/src/System/Text/StringBuilder.cs
index 8026c98e78..f20146fe00 100644
--- a/src/mscorlib/src/System/Text/StringBuilder.cs
+++ b/src/mscorlib/src/System/Text/StringBuilder.cs
@@ -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
@@ -55,7 +57,7 @@ namespace System.Text {
internal char[] m_ChunkChars; // The characters in this block
internal StringBuilder m_ChunkPrevious; // Link to the block logically before this block
internal int m_ChunkLength; // The index in m_ChunkChars that represent the end of the block
- internal int m_ChunkOffset; // The logial offset (sum of all characters in previous blocks)
+ internal int m_ChunkOffset; // The logical offset (sum of all characters in previous blocks)
internal int m_MaxCapacity = 0;
//
@@ -117,18 +119,17 @@ 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("capacity",
- Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "capacity"));
+ throw new ArgumentOutOfRangeException(nameof(capacity),
+ Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(capacity)));
}
if (length<0) {
- throw new ArgumentOutOfRangeException("length",
- Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", "length"));
+ throw new ArgumentOutOfRangeException(nameof(length),
+ Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(length)));
}
if (startIndex<0) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
Contract.EndContractBlock();
@@ -136,7 +137,7 @@ namespace System.Text {
value = String.Empty;
}
if (startIndex > value.Length - length) {
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
}
m_MaxCapacity = Int32.MaxValue;
if (capacity == 0) {
@@ -158,14 +159,14 @@ namespace System.Text {
// and a maximum capacity of maxCapacity.
public StringBuilder(int capacity, int maxCapacity) {
if (capacity>maxCapacity) {
- throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
+ throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
}
if (maxCapacity<1) {
- throw new ArgumentOutOfRangeException("maxCapacity", Environment.GetResourceString("ArgumentOutOfRange_SmallMaxCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(maxCapacity), Environment.GetResourceString("ArgumentOutOfRange_SmallMaxCapacity"));
}
if (capacity<0) {
- throw new ArgumentOutOfRangeException("capacity",
- Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "capacity"));
+ throw new ArgumentOutOfRangeException(nameof(capacity),
+ Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(capacity)));
}
Contract.EndContractBlock();
@@ -177,10 +178,9 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
int persistedCapacity = 0;
@@ -240,11 +240,10 @@ namespace System.Text {
VerifyClassInvariant();
}
- [System.Security.SecurityCritical] // auto-generated
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -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;
}
}
@@ -287,13 +286,13 @@ namespace System.Text {
get { return m_ChunkChars.Length + m_ChunkOffset; }
set {
if (value < 0) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
if (value > MaxCapacity) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
}
if (value < Length) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
Contract.EndContractBlock();
@@ -317,7 +316,7 @@ namespace System.Text {
//
public int EnsureCapacity(int capacity) {
if (capacity < 0) {
- throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
Contract.EndContractBlock();
@@ -326,7 +325,6 @@ namespace System.Text {
return Capacity;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
@@ -357,7 +355,7 @@ namespace System.Text {
}
else
{
- throw new ArgumentOutOfRangeException("chunkLength", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(chunkLength), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
chunk = chunk.m_ChunkPrevious;
@@ -370,26 +368,25 @@ 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);
int currentLength = this.Length;
if (startIndex < 0)
{
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (startIndex > currentLength)
{
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"));
}
if (length < 0)
{
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (startIndex > (currentLength - length))
{
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
}
VerifyClassInvariant();
@@ -433,7 +430,7 @@ namespace System.Text {
}
else
{
- throw new ArgumentOutOfRangeException("chunkCount", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(chunkCount), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
}
@@ -463,11 +460,11 @@ namespace System.Text {
set {
//If the new length is less than 0 or greater than our Maximum capacity, bail.
if (value<0) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (value>MaxCapacity) {
- throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
Contract.EndContractBlock();
@@ -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");
}
}
@@ -539,13 +536,13 @@ namespace System.Text {
if (indexInBlock >= 0)
{
if (indexInBlock >= chunk.m_ChunkLength)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
chunk.m_ChunkChars[indexInBlock] = value;
return;
}
chunk = chunk.m_ChunkPrevious;
if (chunk == null)
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
}
@@ -553,7 +550,7 @@ namespace System.Text {
// Appends a character at the end of this string builder. The capacity is adjusted as needed.
public StringBuilder Append(char value, int repeatCount) {
if (repeatCount<0) {
- throw new ArgumentOutOfRangeException("repeatCount", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ throw new ArgumentOutOfRangeException(nameof(repeatCount), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
@@ -561,6 +558,14 @@ namespace System.Text {
if (repeatCount==0) {
return this;
}
+
+ // this is where we can check if the repeatCount will put us over m_MaxCapacity
+ // We are doing the check here to prevent the corruption of the StringBuilder.
+ int newLength = Length + repeatCount;
+ if (newLength > m_MaxCapacity || newLength < repeatCount) {
+ throw new ArgumentOutOfRangeException(nameof(repeatCount), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
+ }
+
int idx = m_ChunkLength;
while (repeatCount > 0)
{
@@ -573,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;
}
}
@@ -583,10 +588,9 @@ 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("startIndex", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
if (charCount<0) {
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
@@ -598,7 +602,7 @@ namespace System.Text {
if (startIndex == 0 && charCount == 0) {
return this;
}
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
if (charCount > value.Length - startIndex) {
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index"));
@@ -620,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);
@@ -659,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)
@@ -668,23 +670,20 @@ 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("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (count < 0) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
@@ -694,7 +693,7 @@ namespace System.Text {
if (startIndex == 0 && count == 0) {
return this;
}
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
if (count == 0) {
@@ -702,7 +701,7 @@ namespace System.Text {
}
if (startIndex > value.Length - count) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
unsafe
@@ -730,19 +729,18 @@ 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("destination");
+ throw new ArgumentNullException(nameof(destination));
}
if (count < 0) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("Arg_NegativeArgCount"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("Arg_NegativeArgCount"));
}
if (destinationIndex < 0) {
- throw new ArgumentOutOfRangeException("destinationIndex",
- Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", "destinationIndex"));
+ throw new ArgumentOutOfRangeException(nameof(destinationIndex),
+ Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(destinationIndex)));
}
if (destinationIndex > destination.Length - count) {
@@ -750,7 +748,7 @@ namespace System.Text {
}
if ((uint)sourceIndex > (uint)Length) {
- throw new ArgumentOutOfRangeException("sourceIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (sourceIndex > Length - count) {
@@ -794,10 +792,9 @@ 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("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
@@ -805,7 +802,7 @@ namespace System.Text {
//Range check the index.
int currentLength = Length;
if ((uint)index > (uint)currentLength) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
//If value is null, empty or count is 0, do nothing. This is ECMA standard.
@@ -819,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;
@@ -843,11 +840,11 @@ namespace System.Text {
//
public StringBuilder Remove(int startIndex, int length) {
if (length<0) {
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (startIndex<0) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (length > Length - startIndex) {
@@ -989,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);
@@ -1003,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====================================
**
==============================================================================*/
@@ -1012,10 +1090,9 @@ 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("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
@@ -1075,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);
@@ -1092,7 +1168,7 @@ namespace System.Text {
//
public StringBuilder Insert(int index, char[] value) {
if ((uint)index > (uint)Length) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
@@ -1106,13 +1182,12 @@ 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);
int currentLength = Length;
if ((uint)index > (uint)currentLength) {
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
//If they passed in a null char array, just jump out quickly.
@@ -1121,12 +1196,12 @@ namespace System.Text {
{
return this;
}
- throw new ArgumentNullException("value", Environment.GetResourceString("ArgumentNull_String"));
+ throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String"));
}
//Range check the array.
if (startIndex < 0) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (charCount < 0) {
@@ -1134,7 +1209,7 @@ namespace System.Text {
}
if (startIndex > value.Length - charCount) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (charCount > 0)
@@ -1255,7 +1330,7 @@ namespace System.Text {
{
// To preserve the original exception behavior, throw an exception about format if both
// args and format are null. The actual null check for format is in AppendFormatHelper.
- throw new ArgumentNullException((format == null) ? "format" : "args");
+ throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -1283,7 +1358,7 @@ namespace System.Text {
{
// To preserve the original exception behavior, throw an exception about format if both
// args and format are null. The actual null check for format is in AppendFormatHelper.
- throw new ArgumentNullException((format == null) ? "format" : "args");
+ throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -1301,7 +1376,7 @@ namespace System.Text {
internal StringBuilder AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) {
if (format == null) {
- throw new ArgumentNullException("format");
+ throw new ArgumentNullException(nameof(format));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
@@ -1582,19 +1657,19 @@ namespace System.Text {
int currentLength = Length;
if ((uint)startIndex > (uint)currentLength)
{
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (count < 0 || startIndex > currentLength - count)
{
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (oldValue == null)
{
- throw new ArgumentNullException("oldValue");
+ throw new ArgumentNullException(nameof(oldValue));
}
if (oldValue.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "oldValue");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(oldValue));
}
if (newValue == null)
@@ -1648,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();
@@ -1668,11 +1743,11 @@ namespace System.Text {
int currentLength = Length;
if ((uint)startIndex > (uint)currentLength) {
- throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (count < 0 || startIndex > currentLength - count) {
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
int endIndex = startIndex + count;
@@ -1702,14 +1777,20 @@ 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)
{
// We don't check null value as this case will throw null reference exception anyway
if (valueCount < 0)
{
- throw new ArgumentOutOfRangeException("valueCount", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ throw new ArgumentOutOfRangeException(nameof(valueCount), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ }
+
+ // this is where we can check if the valueCount will put us over m_MaxCapacity
+ // We are doing the check here to prevent the corruption of the StringBuilder.
+ int newLength = Length + valueCount;
+ if (newLength > m_MaxCapacity || newLength < valueCount) {
+ throw new ArgumentOutOfRangeException(nameof(valueCount), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
}
// This case is so common we want to optimize for it heavily.
@@ -1732,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);
@@ -1745,12 +1826,11 @@ 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)
{
- throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (valueCount > 0)
@@ -1768,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)
@@ -1798,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
@@ -1810,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");
}
}
@@ -1855,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)
@@ -1863,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);
@@ -1888,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)
@@ -1900,11 +1977,10 @@ namespace System.Text {
}
else
{
- throw new ArgumentOutOfRangeException("destinationIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(destinationIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
}
- [SecurityCritical]
private static void ThreadSafeCopy(char[] source, int sourceIndex, char[] destination, int destinationIndex, int count)
{
if (count > 0)
@@ -1918,13 +1994,12 @@ namespace System.Text {
}
else
{
- throw new ArgumentOutOfRangeException("sourceIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
}
// 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;
@@ -1957,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;
}
@@ -1974,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;
}
@@ -2063,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"));
@@ -2133,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;
@@ -2147,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;
@@ -2180,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;
@@ -2210,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();
}
}
diff --git a/src/mscorlib/src/System/Text/SurrogateEncoder.cs b/src/mscorlib/src/System/Text/SurrogateEncoder.cs
index 409e8a34aa..bbfa180f29 100644
--- a/src/mscorlib/src/System/Text/SurrogateEncoder.cs
+++ b/src/mscorlib/src/System/Text/SurrogateEncoder.cs
@@ -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==================================
@@ -30,7 +31,7 @@ namespace System.Text
internal SurrogateEncoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All versions have a code page
@@ -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"));
}
}
diff --git a/src/mscorlib/src/System/Text/UTF32Encoding.cs b/src/mscorlib/src/System/Text/UTF32Encoding.cs
index 0bdbaefbf2..a7ac1d8539 100644
--- a/src/mscorlib/src/System/Text/UTF32Encoding.cs
+++ b/src/mscorlib/src/System/Text/UTF32Encoding.cs
@@ -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--;
@@ -296,26 +292,25 @@ namespace System.Text
// Check for overflows.
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString(
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString(
"ArgumentOutOfRange_GetByteCountOverflow"));
// 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
@@ -635,25 +629,24 @@ namespace System.Text
// Check for overflows.
if (charCount < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
// 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
@@ -885,7 +878,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -899,7 +892,7 @@ namespace System.Text
byteCount *= 4;
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
@@ -908,7 +901,7 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -929,7 +922,7 @@ namespace System.Text
}
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
diff --git a/src/mscorlib/src/System/Text/UTF7Encoding.cs b/src/mscorlib/src/System/Text/UTF7Encoding.cs
index 654fb8b80f..624ca735f6 100644
--- a/src/mscorlib/src/System/Text/UTF7Encoding.cs
+++ b/src/mscorlib/src/System/Text/UTF7Encoding.cs
@@ -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");
}
@@ -599,7 +592,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -623,7 +616,7 @@ namespace System.Text
// check for overflow
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
@@ -632,7 +625,7 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -663,7 +656,7 @@ namespace System.Text
internal Decoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Get common info
@@ -674,11 +667,10 @@ 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?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Save Whidbey data
@@ -727,7 +719,7 @@ namespace System.Text
internal Encoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Get common info
@@ -737,11 +729,10 @@ 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?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Save Whidbey data
@@ -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"));
diff --git a/src/mscorlib/src/System/Text/UTF8Encoding.cs b/src/mscorlib/src/System/Text/UTF8Encoding.cs
index a527de7b61..ba19649b56 100644
--- a/src/mscorlib/src/System/Text/UTF8Encoding.cs
+++ b/src/mscorlib/src/System/Text/UTF8Encoding.cs
@@ -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[]
@@ -2085,7 +2073,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -2099,7 +2087,7 @@ namespace System.Text
byteCount *= 3;
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
@@ -2108,7 +2096,7 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -2123,7 +2111,7 @@ namespace System.Text
}
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
@@ -2174,7 +2162,7 @@ namespace System.Text
internal UTF8Encoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Get common info
@@ -2194,11 +2182,10 @@ 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?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Save Whidbey data
@@ -2247,7 +2234,7 @@ namespace System.Text
internal UTF8Decoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Get common info
@@ -2268,11 +2255,10 @@ 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?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Save new Whidbey data
diff --git a/src/mscorlib/src/System/Text/UnicodeEncoding.cs b/src/mscorlib/src/System/Text/UnicodeEncoding.cs
index 41d4f3b5ea..25255c3230 100644
--- a/src/mscorlib/src/System/Text/UnicodeEncoding.cs
+++ b/src/mscorlib/src/System/Text/UnicodeEncoding.cs
@@ -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;
@@ -200,7 +196,7 @@ namespace System.Text
// (If they were all invalid chars, this would actually be wrong,
// but that's a ridiculously large # so we're not concerned about that case)
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
char* charStart = chars;
char* charEnd = chars + count;
@@ -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--;
@@ -448,7 +444,7 @@ namespace System.Text
// Throw it, using our complete character
throw new ArgumentException(
Environment.GetResourceString("Argument_RecursiveFallback",
- charLeftOver), "chars");
+ charLeftOver), nameof(chars));
}
else
{
@@ -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
}
@@ -851,7 +846,7 @@ namespace System.Text
// Throw it, using our complete character
throw new ArgumentException(
Environment.GetResourceString("Argument_RecursiveFallback",
- charLeftOver), "chars");
+ charLeftOver), nameof(chars));
}
else
{
@@ -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);
@@ -1697,7 +1690,7 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount",
+ throw new ArgumentOutOfRangeException(nameof(charCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1711,7 +1704,7 @@ namespace System.Text
byteCount <<= 1;
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
@@ -1720,7 +1713,7 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount",
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1735,7 +1728,7 @@ namespace System.Text
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
@@ -1781,7 +1774,7 @@ namespace System.Text
internal Decoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Get Common Info
@@ -1803,11 +1796,10 @@ 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?
- if (info==null) throw new ArgumentNullException("info");
+ if (info==null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Save Whidbey data
diff --git a/src/mscorlib/src/System/Threading/AsyncLocal.cs b/src/mscorlib/src/System/Threading/AsyncLocal.cs
index 264f2a6ff7..6ed1545ac7 100644
--- a/src/mscorlib/src/System/Threading/AsyncLocal.cs
+++ b/src/mscorlib/src/System/Threading/AsyncLocal.cs
@@ -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);
}
@@ -113,4 +108,382 @@ namespace System.Threading
ThreadContextChanged = contextChanged;
}
}
+
+ //
+ // Interface used to store an IAsyncLocal => object mapping in ExecutionContext.
+ // Implementations are specialized based on the number of elements in the immutable
+ // map in order to minimize memory consumption and look-up times.
+ //
+ interface IAsyncLocalValueMap
+ {
+ bool TryGetValue(IAsyncLocal key, out object value);
+ IAsyncLocalValueMap Set(IAsyncLocal key, object value);
+ }
+
+ //
+ // Utility functions for getting/creating instances of IAsyncLocalValueMap
+ //
+ internal static class AsyncLocalValueMap
+ {
+ public static IAsyncLocalValueMap Empty { get; } = new EmptyAsyncLocalValueMap();
+
+ public static IAsyncLocalValueMap Create(IAsyncLocal key, object value) => new OneElementAsyncLocalValueMap(key, value);
+
+ // Instance without any key/value pairs. Used as a singleton/
+ private sealed class EmptyAsyncLocalValueMap : IAsyncLocalValueMap
+ {
+ public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
+ {
+ // If the value isn't null, then create a new one-element map to store
+ // the key/value pair. If it is null, then we're still empty.
+ return value != null ?
+ new OneElementAsyncLocalValueMap(key, value) :
+ (IAsyncLocalValueMap)this;
+ }
+
+ public bool TryGetValue(IAsyncLocal key, out object value)
+ {
+ value = null;
+ return false;
+ }
+ }
+
+ // Instance with one key/value pair.
+ private sealed class OneElementAsyncLocalValueMap : IAsyncLocalValueMap
+ {
+ private readonly IAsyncLocal _key1;
+ private readonly object _value1;
+
+ public OneElementAsyncLocalValueMap(IAsyncLocal key, object value)
+ {
+ _key1 = key; _value1 = value;
+ }
+
+ public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
+ {
+ if (value != null)
+ {
+ // The value is non-null. If the key matches one already contained in this map,
+ // then create a new one-element map with the updated value, otherwise create
+ // a two-element map with the additional key/value.
+ return ReferenceEquals(key, _key1) ?
+ new OneElementAsyncLocalValueMap(key, value) :
+ (IAsyncLocalValueMap)new TwoElementAsyncLocalValueMap(_key1, _value1, key, value);
+ }
+ else
+ {
+ // The value is null. If the key exists in this map, remove it by downgrading to an empty map.
+ // Otherwise, there's nothing to add or remove, so just return this map.
+ return ReferenceEquals(key, _key1) ?
+ Empty :
+ (IAsyncLocalValueMap)this;
+ }
+ }
+
+ public bool TryGetValue(IAsyncLocal key, out object value)
+ {
+ if (ReferenceEquals(key, _key1))
+ {
+ value = _value1;
+ return true;
+ }
+ else
+ {
+ value = null;
+ return false;
+ }
+ }
+ }
+
+ // Instance with two key/value pairs.
+ private sealed class TwoElementAsyncLocalValueMap : IAsyncLocalValueMap
+ {
+ private readonly IAsyncLocal _key1, _key2;
+ private readonly object _value1, _value2;
+
+ public TwoElementAsyncLocalValueMap(IAsyncLocal key1, object value1, IAsyncLocal key2, object value2)
+ {
+ _key1 = key1; _value1 = value1;
+ _key2 = key2; _value2 = value2;
+ }
+
+ public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
+ {
+ if (value != null)
+ {
+ // The value is non-null. If the key matches one already contained in this map,
+ // then create a new two-element map with the updated value, otherwise create
+ // a three-element map with the additional key/value.
+ return
+ ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(key, value, _key2, _value2) :
+ ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, key, value) :
+ (IAsyncLocalValueMap)new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value);
+ }
+ else
+ {
+ // The value is null. If the key exists in this map, remove it by downgrading to a one-element map
+ // without the key. Otherwise, there's nothing to add or remove, so just return this map.
+ return
+ ReferenceEquals(key, _key1) ? new OneElementAsyncLocalValueMap(_key2, _value2) :
+ ReferenceEquals(key, _key2) ? new OneElementAsyncLocalValueMap(_key1, _value1) :
+ (IAsyncLocalValueMap)this;
+ }
+ }
+
+ public bool TryGetValue(IAsyncLocal key, out object value)
+ {
+ if (ReferenceEquals(key, _key1))
+ {
+ value = _value1;
+ return true;
+ }
+ else if (ReferenceEquals(key, _key2))
+ {
+ value = _value2;
+ return true;
+ }
+ else
+ {
+ value = null;
+ return false;
+ }
+ }
+ }
+
+ // Instance with three key/value pairs.
+ private sealed class ThreeElementAsyncLocalValueMap : IAsyncLocalValueMap
+ {
+ private readonly IAsyncLocal _key1, _key2, _key3;
+ private readonly object _value1, _value2, _value3;
+
+ public ThreeElementAsyncLocalValueMap(IAsyncLocal key1, object value1, IAsyncLocal key2, object value2, IAsyncLocal key3, object value3)
+ {
+ _key1 = key1; _value1 = value1;
+ _key2 = key2; _value2 = value2;
+ _key3 = key3; _value3 = value3;
+ }
+
+ public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
+ {
+ if (value != null)
+ {
+ // The value is non-null. If the key matches one already contained in this map,
+ // then create a new three-element map with the updated value.
+ if (ReferenceEquals(key, _key1)) return new ThreeElementAsyncLocalValueMap(key, value, _key2, _value2, _key3, _value3);
+ if (ReferenceEquals(key, _key2)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, key, value, _key3, _value3);
+ if (ReferenceEquals(key, _key3)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value);
+
+ // The key doesn't exist in this map, so upgrade to a multi map that contains
+ // the additional key/value pair.
+ var multi = new MultiElementAsyncLocalValueMap(4);
+ multi.UnsafeStore(0, _key1, _value1);
+ multi.UnsafeStore(1, _key2, _value2);
+ multi.UnsafeStore(2, _key3, _value3);
+ multi.UnsafeStore(3, key, value);
+ return multi;
+ }
+ else
+ {
+ // The value is null. If the key exists in this map, remove it by downgrading to a two-element map
+ // without the key. Otherwise, there's nothing to add or remove, so just return this map.
+ return
+ ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(_key2, _value2, _key3, _value3) :
+ ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, _key3, _value3) :
+ ReferenceEquals(key, _key3) ? new TwoElementAsyncLocalValueMap(_key1, _value1, _key2, _value2) :
+ (IAsyncLocalValueMap)this;
+ }
+ }
+
+ public bool TryGetValue(IAsyncLocal key, out object value)
+ {
+ if (ReferenceEquals(key, _key1))
+ {
+ value = _value1;
+ return true;
+ }
+ else if (ReferenceEquals(key, _key2))
+ {
+ value = _value2;
+ return true;
+ }
+ else if (ReferenceEquals(key, _key3))
+ {
+ value = _value3;
+ return true;
+ }
+ else
+ {
+ value = null;
+ return false;
+ }
+ }
+ }
+
+ // Instance with up to 16 key/value pairs.
+ private sealed class MultiElementAsyncLocalValueMap : IAsyncLocalValueMap
+ {
+ internal const int MaxMultiElements = 16;
+ private readonly KeyValuePair<IAsyncLocal, object>[] _keyValues;
+
+ internal MultiElementAsyncLocalValueMap(int count)
+ {
+ Debug.Assert(count <= MaxMultiElements);
+ _keyValues = new KeyValuePair<IAsyncLocal, object>[count];
+ }
+
+ internal void UnsafeStore(int index, IAsyncLocal key, object value)
+ {
+ Debug.Assert(index < _keyValues.Length);
+ _keyValues[index] = new KeyValuePair<IAsyncLocal, object>(key, value);
+ }
+
+ public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
+ {
+ // Find the key in this map.
+ for (int i = 0; i < _keyValues.Length; i++)
+ {
+ if (ReferenceEquals(key, _keyValues[i].Key))
+ {
+ // The key is in the map. If the value isn't null, then create a new map of the same
+ // size that has all of the same pairs, with this new key/value pair overwriting the old.
+ if (value != null)
+ {
+ var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length);
+ Array.Copy(_keyValues, 0, multi._keyValues, 0, _keyValues.Length);
+ multi._keyValues[i] = new KeyValuePair<IAsyncLocal, object>(key, value);
+ return multi;
+ }
+ else if (_keyValues.Length == 4)
+ {
+ // The value is null, and we only have four elements, one of which we're removing,
+ // so downgrade to a three-element map, without the matching element.
+ return
+ i == 0 ? new ThreeElementAsyncLocalValueMap(_keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) :
+ i == 1 ? new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) :
+ i == 2 ? new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[3].Key, _keyValues[3].Value) :
+ (IAsyncLocalValueMap)new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value);
+ }
+ else
+ {
+ // The value is null, and we have enough elements remaining to warrant a multi map.
+ // Create a new one and copy all of the elements from this one, except the one to be removed.
+ var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length - 1);
+ if (i != 0) Array.Copy(_keyValues, 0, multi._keyValues, 0, i);
+ if (i != _keyValues.Length - 1) Array.Copy(_keyValues, i + 1, multi._keyValues, i, _keyValues.Length - i - 1);
+ return multi;
+ }
+ }
+ }
+
+ // The key does not already exist in this map.
+
+ // If the value is null, then we can simply return this same map, as there's nothing to add or remove.
+ if (value == null)
+ {
+ return this;
+ }
+
+ // We need to create a new map that has the additional key/value pair.
+ // If with the addition we can still fit in a multi map, create one.
+ if (_keyValues.Length < MaxMultiElements)
+ {
+ var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length + 1);
+ Array.Copy(_keyValues, 0, multi._keyValues, 0, _keyValues.Length);
+ multi._keyValues[_keyValues.Length] = new KeyValuePair<IAsyncLocal, object>(key, value);
+ return multi;
+ }
+
+ // Otherwise, upgrade to a many map.
+ var many = new ManyElementAsyncLocalValueMap(MaxMultiElements + 1);
+ foreach (KeyValuePair<IAsyncLocal, object> pair in _keyValues)
+ {
+ many[pair.Key] = pair.Value;
+ }
+ many[key] = value;
+ return many;
+ }
+
+ public bool TryGetValue(IAsyncLocal key, out object value)
+ {
+ foreach (KeyValuePair<IAsyncLocal, object> pair in _keyValues)
+ {
+ if (ReferenceEquals(key, pair.Key))
+ {
+ value = pair.Value;
+ return true;
+ }
+ }
+ value = null;
+ return false;
+ }
+ }
+
+ // Instance with any number of key/value pairs.
+ private sealed class ManyElementAsyncLocalValueMap : Dictionary<IAsyncLocal, object>, IAsyncLocalValueMap
+ {
+ public ManyElementAsyncLocalValueMap(int capacity) : base(capacity) { }
+
+ public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
+ {
+ int count = Count;
+ bool containsKey = ContainsKey(key);
+
+ // If the value being set exists, create a new many map, copy all of the elements from this one,
+ // and then store the new key/value pair into it. This is the most common case.
+ if (value != null)
+ {
+ var map = new ManyElementAsyncLocalValueMap(count + (containsKey ? 0 : 1));
+ foreach (KeyValuePair<IAsyncLocal, object> pair in this)
+ {
+ map[pair.Key] = pair.Value;
+ }
+ map[key] = value;
+ return map;
+ }
+
+ // Otherwise, the value is null, which means null is being stored into an AsyncLocal.Value.
+ // Since there's no observable difference at the API level between storing null and the key
+ // not existing at all, we can downgrade to a smaller map rather than storing null.
+
+ // If the key is contained in this map, we're going to create a new map that's one pair smaller.
+ if (containsKey)
+ {
+ // If the new count would be within range of a multi map instead of a many map,
+ // downgrade to the many map, which uses less memory and is faster to access.
+ // Otherwise, just create a new many map that's missing this key.
+ if (count == MultiElementAsyncLocalValueMap.MaxMultiElements + 1)
+ {
+ var multi = new MultiElementAsyncLocalValueMap(MultiElementAsyncLocalValueMap.MaxMultiElements);
+ int index = 0;
+ foreach (KeyValuePair<IAsyncLocal, object> pair in this)
+ {
+ if (!ReferenceEquals(key, pair.Key))
+ {
+ multi.UnsafeStore(index++, pair.Key, pair.Value);
+ }
+ }
+ Debug.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
+ return multi;
+ }
+ else
+ {
+ var map = new ManyElementAsyncLocalValueMap(count - 1);
+ foreach (KeyValuePair<IAsyncLocal, object> pair in this)
+ {
+ if (!ReferenceEquals(key, pair.Key))
+ {
+ map[pair.Key] = pair.Value;
+ }
+ }
+ Debug.Assert(map.Count == count - 1);
+ return map;
+ }
+ }
+
+ // We were storing null, but the key wasn't in the map, so there's nothing to change.
+ // Just return this instance.
+ return this;
+ }
+ }
+ }
}
diff --git a/src/mscorlib/src/System/Threading/AutoResetEvent.cs b/src/mscorlib/src/System/Threading/AutoResetEvent.cs
index 6fe6c06232..78a6fa1234 100644
--- a/src/mscorlib/src/System/Threading/AutoResetEvent.cs
+++ b/src/mscorlib/src/System/Threading/AutoResetEvent.cs
@@ -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
{
diff --git a/src/mscorlib/src/System/Threading/CancellationToken.cs b/src/mscorlib/src/System/Threading/CancellationToken.cs
index 48a2344c31..5b78f20900 100644
--- a/src/mscorlib/src/System/Threading/CancellationToken.cs
+++ b/src/mscorlib/src/System/Threading/CancellationToken.cs
@@ -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();
}
@@ -192,7 +191,7 @@ namespace System.Threading
public CancellationTokenRegistration Register(Action callback)
{
if (callback == null)
- throw new ArgumentNullException("callback");
+ throw new ArgumentNullException(nameof(callback));
return Register(
s_ActionToActionObjShunt,
@@ -227,7 +226,7 @@ namespace System.Threading
public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext)
{
if (callback == null)
- throw new ArgumentNullException("callback");
+ throw new ArgumentNullException(nameof(callback));
return Register(
s_ActionToActionObjShunt,
@@ -260,7 +259,7 @@ namespace System.Threading
public CancellationTokenRegistration Register(Action<Object> callback, Object state)
{
if (callback == null)
- throw new ArgumentNullException("callback");
+ throw new ArgumentNullException(nameof(callback));
return Register(
callback,
@@ -318,14 +317,13 @@ namespace System.Threading
}
// the real work..
- [SecuritySafeCritical]
[MethodImpl(MethodImplOptions.NoInlining)]
private CancellationTokenRegistration Register(Action<Object> callback, Object state, bool useSynchronizationContext, bool useExecutionContext)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
if (callback == null)
- throw new ArgumentNullException("callback");
+ throw new ArgumentNullException(nameof(callback));
if (CanBeCanceled == false)
{
diff --git a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
index 34e0bb0aba..ac27fe30e6 100644
--- a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
+++ b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs
index 954cd38344..fe9e0dec76 100644
--- a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs
+++ b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs
@@ -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
{
@@ -275,7 +275,7 @@ namespace System.Threading
long totalMilliseconds = (long)delay.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
- throw new ArgumentOutOfRangeException("delay");
+ throw new ArgumentOutOfRangeException(nameof(delay));
}
InitializeWithTimer((int)totalMilliseconds);
@@ -304,7 +304,7 @@ namespace System.Threading
{
if (millisecondsDelay < -1)
{
- throw new ArgumentOutOfRangeException("millisecondsDelay");
+ throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));
}
InitializeWithTimer(millisecondsDelay);
@@ -414,7 +414,7 @@ namespace System.Threading
long totalMilliseconds = (long)delay.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
- throw new ArgumentOutOfRangeException("delay");
+ throw new ArgumentOutOfRangeException(nameof(delay));
}
CancelAfter((int)totalMilliseconds);
@@ -450,7 +450,7 @@ namespace System.Threading
if (millisecondsDelay < -1)
{
- throw new ArgumentOutOfRangeException("millisecondsDelay");
+ throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));
}
if (IsCancellationRequested) return;
@@ -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);
}
}
@@ -882,7 +882,7 @@ namespace System.Threading
public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens)
{
if (tokens == null)
- throw new ArgumentNullException("tokens");
+ throw new ArgumentNullException(nameof(tokens));
if (tokens.Length == 0)
throw new ArgumentException(Environment.GetResourceString("CancellationToken_CreateLinkedToken_TokensIsEmpty"));
@@ -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;
}
diff --git a/src/mscorlib/src/System/Threading/CountdownEvent.cs b/src/mscorlib/src/System/Threading/CountdownEvent.cs
index 1374766863..d86a2ccfb8 100644
--- a/src/mscorlib/src/System/Threading/CountdownEvent.cs
+++ b/src/mscorlib/src/System/Threading/CountdownEvent.cs
@@ -11,10 +11,10 @@
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
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
@@ -59,7 +58,7 @@ namespace System.Threading
{
if (initialCount < 0)
{
- throw new ArgumentOutOfRangeException("initialCount");
+ throw new ArgumentOutOfRangeException(nameof(initialCount));
}
m_initialCount = initialCount;
@@ -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)
{
@@ -229,11 +228,11 @@ namespace System.Threading
{
if (signalCount <= 0)
{
- throw new ArgumentOutOfRangeException("signalCount");
+ throw new ArgumentOutOfRangeException(nameof(signalCount));
}
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;
}
@@ -340,7 +339,7 @@ namespace System.Threading
{
if (signalCount <= 0)
{
- throw new ArgumentOutOfRangeException("signalCount");
+ throw new ArgumentOutOfRangeException(nameof(signalCount));
}
ThrowIfDisposed();
@@ -409,7 +408,7 @@ namespace System.Threading
if (count < 0)
{
- throw new ArgumentOutOfRangeException("count");
+ throw new ArgumentOutOfRangeException(nameof(count));
}
m_currentCount = count;
@@ -481,7 +480,7 @@ namespace System.Threading
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
- throw new ArgumentOutOfRangeException("timeout");
+ throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, new CancellationToken());
@@ -511,7 +510,7 @@ namespace System.Threading
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
- throw new ArgumentOutOfRangeException("timeout");
+ throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, cancellationToken);
@@ -555,7 +554,7 @@ namespace System.Threading
{
if (millisecondsTimeout < -1)
{
- throw new ArgumentOutOfRangeException("millisecondsTimeout");
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
}
ThrowIfDisposed();
diff --git a/src/mscorlib/src/System/Threading/EventWaitHandle.cs b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
index f56da1fa26..4b1611c6aa 100644
--- a/src/mscorlib/src/System/Threading/EventWaitHandle.cs
+++ b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
@@ -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)
@@ -56,7 +51,7 @@ namespace System.Threading
#else
if (System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
}
#endif
}
@@ -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)
@@ -105,24 +98,12 @@ namespace System.Threading
#else
if (System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
}
#endif
}
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
@@ -216,29 +183,25 @@ namespace System.Threading
#else
if (name == null)
{
- throw new ArgumentNullException("name", Environment.GetResourceString("ArgumentNull_WithParamName"));
+ throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName"));
}
if(name.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
}
if(null != name && System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
}
Contract.EndContractBlock();
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("eventSecurity");
- Contract.EndContractBlock();
-
- eventSecurity.Persist(safeWaitHandle);
- }
-#endif
}
}
diff --git a/src/mscorlib/src/System/Threading/ExecutionContext.cs b/src/mscorlib/src/System/Threading/ExecutionContext.cs
index 0440368608..5ea9942f65 100644
--- a/src/mscorlib/src/System/Threading/ExecutionContext.cs
+++ b/src/mscorlib/src/System/Threading/ExecutionContext.cs
@@ -14,33 +14,22 @@ namespace System.Threading
using System;
using System.Security;
using System.Runtime.Remoting;
-#if FEATURE_IMPERSONATION
- using System.Security.Principal;
-#endif
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Messaging;
-#endif // FEATURE_REMOTING
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void ContextCallback(Object state);
-#if FEATURE_CORECLR
-
- [SecurityCritical]
internal struct ExecutionContextSwitcher
{
internal ExecutionContext m_ec;
@@ -48,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)
@@ -63,32 +52,108 @@ namespace System.Threading
}
}
- public sealed class ExecutionContext : IDisposable
+ [Serializable]
+ public sealed class ExecutionContext : IDisposable, ISerializable
{
private static readonly ExecutionContext Default = new ExecutionContext();
- private readonly Dictionary<IAsyncLocal, object> m_localValues;
+ private readonly IAsyncLocalValueMap m_localValues;
private readonly IAsyncLocal[] m_localChangeNotifications;
+ private readonly bool m_isFlowSuppressed;
private ExecutionContext()
{
- m_localValues = new Dictionary<IAsyncLocal, object>();
+ m_localValues = AsyncLocalValueMap.Empty;
m_localChangeNotifications = Array.Empty<IAsyncLocal>();
}
- private ExecutionContext(Dictionary<IAsyncLocal, object> localValues, IAsyncLocal[] localChangeNotifications)
+ private ExecutionContext(
+ IAsyncLocalValueMap localValues,
+ IAsyncLocal[] localChangeNotifications,
+ bool isFlowSuppressed)
{
m_localValues = localValues;
m_localChangeNotifications = localChangeNotifications;
+ m_isFlowSuppressed = isFlowSuppressed;
+ }
+
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+ Contract.EndContractBlock();
+ }
+
+ private ExecutionContext(SerializationInfo info, StreamingContext context)
+ {
}
- [SecuritySafeCritical]
public static ExecutionContext Capture()
{
- return Thread.CurrentThread.ExecutionContext ?? ExecutionContext.Default;
+ ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
+ if (executionContext == null)
+ {
+ return Default;
+ }
+ if (executionContext.m_isFlowSuppressed)
+ {
+ // Prevent ExecutionContext.Run on a suppressed-flow context for desktop framework compatibility
+ return null;
+ }
+ return executionContext;
+ }
+
+ private ExecutionContext ShallowClone(bool isFlowSuppressed)
+ {
+ Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
+
+ if (!isFlowSuppressed &&
+ m_localValues == Default.m_localValues &&
+ m_localChangeNotifications == Default.m_localChangeNotifications)
+ {
+ return null; // implies the default context
+ }
+ return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed);
+ }
+
+ public static AsyncFlowControl SuppressFlow()
+ {
+ Thread currentThread = Thread.CurrentThread;
+ ExecutionContext executionContext = currentThread.ExecutionContext ?? Default;
+ if (executionContext.m_isFlowSuppressed)
+ {
+ throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes"));
+ }
+ Contract.EndContractBlock();
+
+ executionContext = executionContext.ShallowClone(isFlowSuppressed: true);
+ var asyncFlowControl = new AsyncFlowControl();
+ currentThread.ExecutionContext = executionContext;
+ asyncFlowControl.Initialize(currentThread);
+ return asyncFlowControl;
+ }
+
+ public static void RestoreFlow()
+ {
+ Thread currentThread = Thread.CurrentThread;
+ ExecutionContext executionContext = currentThread.ExecutionContext;
+ if (executionContext == null || !executionContext.m_isFlowSuppressed)
+ {
+ throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow"));
+ }
+ Contract.EndContractBlock();
+
+ currentThread.ExecutionContext = executionContext.ShallowClone(isFlowSuppressed: false);
+ }
+
+ public static bool IsFlowSuppressed()
+ {
+ ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
+ return executionContext != null && executionContext.m_isFlowSuppressed;
}
- [SecurityCritical]
[HandleProcessCorruptedStateExceptions]
public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
{
@@ -115,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;
@@ -133,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)
{
@@ -189,7 +251,6 @@ namespace System.Threading
}
}
- [SecurityCritical]
internal static object GetLocalValue(IAsyncLocal local)
{
ExecutionContext current = Thread.CurrentThread.ExecutionContext;
@@ -201,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;
@@ -212,16 +272,7 @@ namespace System.Threading
if (previousValue == newValue)
return;
- //
- // Allocate a new Dictionary containing a copy of the old values, plus the new value. We have to do this manually to
- // minimize allocations of IEnumerators, etc.
- //
- Dictionary<IAsyncLocal, object> newValues = new Dictionary<IAsyncLocal, object>(current.m_localValues.Count + (hadPreviousValue ? 0 : 1));
-
- foreach (KeyValuePair<IAsyncLocal, object> pair in current.m_localValues)
- newValues.Add(pair.Key, pair.Value);
-
- newValues[local] = newValue;
+ IAsyncLocalValueMap newValues = current.m_localValues.Set(local, newValue);
//
// Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
@@ -231,7 +282,7 @@ namespace System.Threading
{
if (hadPreviousValue)
{
- Contract.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
+ Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
}
else
{
@@ -241,7 +292,8 @@ namespace System.Threading
}
}
- Thread.CurrentThread.ExecutionContext = new ExecutionContext(newValues, newChangeNotifications);
+ Thread.CurrentThread.ExecutionContext =
+ new ExecutionContext(newValues, newChangeNotifications, current.m_isFlowSuppressed);
if (needChangeNotifications)
{
@@ -259,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.
@@ -296,14 +343,8 @@ namespace System.Threading
// For CLR compat only
}
- public static bool IsFlowSuppressed()
- {
- return false;
- }
-
internal static ExecutionContext PreAllocatedDefault
{
- [SecuritySafeCritical]
get { return ExecutionContext.Default; }
}
@@ -315,1084 +356,77 @@ namespace System.Threading
#endregion
}
-#else // FEATURE_CORECLR
-
- // Legacy desktop ExecutionContext implementation
-
- internal struct ExecutionContextSwitcher
+ public struct AsyncFlowControl : IDisposable
{
- internal ExecutionContext.Reader outerEC; // previous EC we need to restore on Undo
- internal bool outerECBelongsToScope;
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- internal SecurityContextSwitcher scsw;
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- internal Object hecsw;
-#if FEATURE_IMPERSONATION
- internal WindowsIdentity wi;
- internal bool cachedAlwaysFlowImpersonationPolicy;
- internal bool wiIsValid;
-#endif
- internal Thread thread;
-
- [System.Security.SecurityCritical] // auto-generated
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- internal bool UndoNoThrow(Thread currentThread)
- {
- try
- {
- Undo(currentThread);
- }
- catch
- {
- return false;
- }
- return true;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- internal void Undo(Thread currentThread)
- {
- //
- // Don't use an uninitialized switcher, or one that's already been used.
- //
- if (thread == null)
- return; // Don't do anything
-
- Contract.Assert(Thread.CurrentThread == this.thread);
-
- //
- // Restore the HostExecutionContext before restoring the ExecutionContext.
- //
-#if FEATURE_CAS_POLICY
- if (hecsw != null)
- HostExecutionContextSwitcher.Undo(hecsw);
-#endif // FEATURE_CAS_POLICY
-
- //
- // restore the saved Execution Context. Note that this will also restore the
- // SynchronizationContext, Logical/IllogicalCallContext, etc.
- //
- ExecutionContext.Reader innerEC = currentThread.GetExecutionContextReader();
- currentThread.SetExecutionContext(outerEC, outerECBelongsToScope);
-
-#if DEBUG
- try
- {
- currentThread.ForbidExecutionContextMutation = true;
-#endif
-
- //
- // Tell the SecurityContext to do the side-effects of restoration.
- //
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- if (scsw.currSC != null)
- {
- // Any critical failure inside scsw will cause FailFast
- scsw.Undo();
- }
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
-
-#if FEATURE_IMPERSONATION
- if (wiIsValid)
- SecurityContext.RestoreCurrentWI(outerEC, innerEC, wi, cachedAlwaysFlowImpersonationPolicy);
-#endif
-
- thread = null; // this will prevent the switcher object being used again
-#if DEBUG
- }
- finally
- {
- currentThread.ForbidExecutionContextMutation = false;
- }
-#endif
- ExecutionContext.OnAsyncLocalContextChanged(innerEC.DangerousGetRawExecutionContext(), outerEC.DangerousGetRawExecutionContext());
- }
- }
-
-
- public struct AsyncFlowControl: IDisposable
- {
- private bool useEC;
- private ExecutionContext _ec;
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- private SecurityContext _sc;
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
private Thread _thread;
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- [SecurityCritical]
- internal void Setup(SecurityContextDisableFlow flags)
- {
- useEC = false;
- Thread currentThread = Thread.CurrentThread;
- _sc = currentThread.GetMutableExecutionContext().SecurityContext;
- _sc._disableFlow = flags;
- _thread = currentThread;
- }
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- [SecurityCritical]
- internal void Setup()
+
+ internal void Initialize(Thread currentThread)
{
- useEC = true;
- Thread currentThread = Thread.CurrentThread;
- _ec = currentThread.GetMutableExecutionContext();
- _ec.isFlowSuppressed = true;
+ Debug.Assert(currentThread == Thread.CurrentThread);
_thread = currentThread;
}
-
- public void Dispose()
- {
- Undo();
- }
-
- [SecuritySafeCritical]
+
public void Undo()
{
if (_thread == null)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCMultiple"));
- }
- if (_thread != Thread.CurrentThread)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCOtherThread"));
- }
- if (useEC)
- {
- if (Thread.CurrentThread.GetMutableExecutionContext() != _ec)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"));
- }
- ExecutionContext.RestoreFlow();
- }
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- else
- {
- if (!Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(_sc))
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"));
- }
- SecurityContext.RestoreFlow();
- }
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- _thread = null;
- }
-
- public override int GetHashCode()
- {
- return _thread == null ? ToString().GetHashCode() : _thread.GetHashCode();
- }
-
- public override bool Equals(Object obj)
- {
- if (obj is AsyncFlowControl)
- return Equals((AsyncFlowControl)obj);
- else
- return false;
- }
-
- public bool Equals(AsyncFlowControl obj)
- {
- return obj.useEC == useEC && obj._ec == _ec &&
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- obj._sc == _sc &&
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- obj._thread == _thread;
- }
-
- public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
- {
- return a.Equals(b);
- }
-
- public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
- {
- return !(a == b);
- }
-
- }
-
-
-#if FEATURE_SERIALIZATION
- [Serializable]
-#endif
- public sealed class ExecutionContext : IDisposable, ISerializable
- {
- /*=========================================================================
- ** Data accessed from managed code that needs to be defined in
- ** ExecutionContextObject to maintain alignment between the two classes.
- ** DON'T CHANGE THESE UNLESS YOU MODIFY ExecutionContextObject in vm\object.h
- =========================================================================*/
-#if FEATURE_CAS_POLICY
- private HostExecutionContext _hostExecutionContext;
-#endif // FEATURE_CAS_POLICY
- private SynchronizationContext _syncContext;
- private SynchronizationContext _syncContextNoFlow;
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- private SecurityContext _securityContext;
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
-#if FEATURE_REMOTING
- [System.Security.SecurityCritical] // auto-generated
- private LogicalCallContext _logicalCallContext;
- private IllogicalCallContext _illogicalCallContext; // this call context follows the physical thread
-#endif // #if FEATURE_REMOTING
-
- enum Flags
- {
- None = 0x0,
- IsNewCapture = 0x1,
- IsFlowSuppressed = 0x2,
- IsPreAllocatedDefault = 0x4
- }
- private Flags _flags;
-
- private Dictionary<IAsyncLocal, object> _localValues;
- private List<IAsyncLocal> _localChangeNotifications;
-
- internal bool isNewCapture
- {
- get
- {
- return (_flags & (Flags.IsNewCapture | Flags.IsPreAllocatedDefault)) != Flags.None;
- }
- set
- {
- Contract.Assert(!IsPreAllocatedDefault);
- if (value)
- _flags |= Flags.IsNewCapture;
- else
- _flags &= ~Flags.IsNewCapture;
- }
- }
- internal bool isFlowSuppressed
- {
- get
- {
- return (_flags & Flags.IsFlowSuppressed) != Flags.None;
- }
- set
- {
- Contract.Assert(!IsPreAllocatedDefault);
- if (value)
- _flags |= Flags.IsFlowSuppressed;
- else
- _flags &= ~Flags.IsFlowSuppressed;
- }
- }
-
-
- private static readonly ExecutionContext s_dummyDefaultEC = new ExecutionContext(isPreAllocatedDefault: true);
-
- static internal ExecutionContext PreAllocatedDefault
- {
- [SecuritySafeCritical]
- get { return s_dummyDefaultEC; }
- }
-
- internal bool IsPreAllocatedDefault
- {
- get
- {
- // we use _flags instead of a direct comparison w/ s_dummyDefaultEC to avoid the static access on
- // hot code paths.
- if ((_flags & Flags.IsPreAllocatedDefault) != Flags.None)
- {
- Contract.Assert(this == s_dummyDefaultEC);
- return true;
- }
- else
- {
- return false;
- }
- }
- }
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal ExecutionContext()
- {
- }
-
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal ExecutionContext(bool isPreAllocatedDefault)
- {
- if (isPreAllocatedDefault)
- _flags = Flags.IsPreAllocatedDefault;
- }
-
- // Read-only wrapper around ExecutionContext. This enables safe reading of an ExecutionContext without accidentally modifying it.
- internal struct Reader
- {
- ExecutionContext m_ec;
-
- public Reader(ExecutionContext ec) { m_ec = ec; }
-
- public ExecutionContext DangerousGetRawExecutionContext() { return m_ec; }
-
- public bool IsNull { get { return m_ec == null; } }
- [SecurityCritical]
- public bool IsDefaultFTContext(bool ignoreSyncCtx) { return m_ec.IsDefaultFTContext(ignoreSyncCtx); }
- public bool IsFlowSuppressed
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- get { return IsNull ? false : m_ec.isFlowSuppressed; }
- }
- //public Thread Thread { get { return m_ec._thread; } }
- public bool IsSame(ExecutionContext.Reader other) { return m_ec == other.m_ec; }
-
- public SynchronizationContext SynchronizationContext { get { return IsNull ? null : m_ec.SynchronizationContext; } }
- public SynchronizationContext SynchronizationContextNoFlow { get { return IsNull ? null : m_ec.SynchronizationContextNoFlow; } }
-
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- public SecurityContext.Reader SecurityContext
- {
- [SecurityCritical]
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- get { return new SecurityContext.Reader(IsNull ? null : m_ec.SecurityContext); }
- }
-#endif
-
-#if FEATURE_REMOTING
- public LogicalCallContext.Reader LogicalCallContext
- {
- [SecurityCritical]
- get { return new LogicalCallContext.Reader(IsNull ? null : m_ec.LogicalCallContext); }
- }
-
- public IllogicalCallContext.Reader IllogicalCallContext
- {
- [SecurityCritical]
- get { return new IllogicalCallContext.Reader(IsNull ? null : m_ec.IllogicalCallContext); }
- }
-#endif
-
- [SecurityCritical]
- public object GetLocalValue(IAsyncLocal local)
- {
- if (IsNull)
- return null;
-
- if (m_ec._localValues == null)
- return null;
-
- object value;
- m_ec._localValues.TryGetValue(local, out value);
- return value;
- }
-
- [SecurityCritical]
- public bool HasSameLocalValues(ExecutionContext other)
- {
- var thisLocalValues = IsNull ? null : m_ec._localValues;
- var otherLocalValues = other == null ? null : other._localValues;
- return thisLocalValues == otherLocalValues;
- }
-
- [SecurityCritical]
- public bool HasLocalValues()
- {
- return !this.IsNull && m_ec._localValues != null;
- }
- }
-
- [SecurityCritical]
- internal static object GetLocalValue(IAsyncLocal local)
- {
- return Thread.CurrentThread.GetExecutionContextReader().GetLocalValue(local);
- }
-
- [SecurityCritical]
- internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
- {
- ExecutionContext current = Thread.CurrentThread.GetMutableExecutionContext();
-
- object previousValue = null;
- bool hadPreviousValue = current._localValues != null && current._localValues.TryGetValue(local, out previousValue);
-
- if (previousValue == newValue)
- return;
-
- if (current._localValues == null)
- current._localValues = new Dictionary<IAsyncLocal, object>();
- else
- current._localValues = new Dictionary<IAsyncLocal, object>(current._localValues);
-
- current._localValues[local] = newValue;
-
- if (needChangeNotifications)
- {
- if (hadPreviousValue)
- {
- Contract.Assert(current._localChangeNotifications != null);
- Contract.Assert(current._localChangeNotifications.Contains(local));
- }
- else
- {
- if (current._localChangeNotifications == null)
- current._localChangeNotifications = new List<IAsyncLocal>();
- else
- current._localChangeNotifications = new List<IAsyncLocal>(current._localChangeNotifications);
-
- current._localChangeNotifications.Add(local);
- }
-
- local.OnValueChanged(previousValue, newValue, false);
- }
- }
-
- [SecurityCritical]
- [HandleProcessCorruptedStateExceptions]
- internal static void OnAsyncLocalContextChanged(ExecutionContext previous, ExecutionContext current)
- {
- List<IAsyncLocal> previousLocalChangeNotifications = (previous == null) ? null : previous._localChangeNotifications;
- if (previousLocalChangeNotifications != null)
- {
- foreach (IAsyncLocal local in previousLocalChangeNotifications)
- {
- object previousValue = null;
- if (previous != null && previous._localValues != null)
- previous._localValues.TryGetValue(local, out previousValue);
-
- object currentValue = null;
- if (current != null && current._localValues != null)
- current._localValues.TryGetValue(local, out currentValue);
-
- if (previousValue != currentValue)
- local.OnValueChanged(previousValue, currentValue, true);
- }
- }
-
- List<IAsyncLocal> currentLocalChangeNotifications = (current == null) ? null : current._localChangeNotifications;
- if (currentLocalChangeNotifications != null && currentLocalChangeNotifications != previousLocalChangeNotifications)
- {
- try
- {
- foreach (IAsyncLocal local in currentLocalChangeNotifications)
- {
- // If the local has a value in the previous context, we already fired the event for that local
- // in the code above.
- object previousValue = null;
- if (previous == null ||
- previous._localValues == null ||
- !previous._localValues.TryGetValue(local, out previousValue))
- {
- object currentValue = null;
- if (current != null && current._localValues != null)
- current._localValues.TryGetValue(local, out currentValue);
-
- if (previousValue != currentValue)
- local.OnValueChanged(previousValue, currentValue, true);
- }
- }
- }
- catch (Exception ex)
- {
- Environment.FailFast(
- Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"),
- ex);
- }
- }
- }
-
-
-#if FEATURE_REMOTING
- internal LogicalCallContext LogicalCallContext
- {
- [System.Security.SecurityCritical] // auto-generated
- get
- {
- if (_logicalCallContext == null)
- {
- _logicalCallContext = new LogicalCallContext();
- }
- return _logicalCallContext;
- }
- [System.Security.SecurityCritical] // auto-generated
- set
- {
- Contract.Assert(this != s_dummyDefaultEC);
- _logicalCallContext = value;
- }
- }
-
- internal IllogicalCallContext IllogicalCallContext
- {
- get
- {
- if (_illogicalCallContext == null)
- {
- _illogicalCallContext = new IllogicalCallContext();
- }
- return _illogicalCallContext;
- }
- set
- {
- Contract.Assert(this != s_dummyDefaultEC);
- _illogicalCallContext = value;
- }
- }
-#endif // #if FEATURE_REMOTING
-
- internal SynchronizationContext SynchronizationContext
- {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- get
- {
- return _syncContext;
- }
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- set
- {
- Contract.Assert(this != s_dummyDefaultEC);
- _syncContext = value;
- }
- }
-
- internal SynchronizationContext SynchronizationContextNoFlow
- {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- get
- {
- return _syncContextNoFlow;
- }
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- set
- {
- Contract.Assert(this != s_dummyDefaultEC);
- _syncContextNoFlow = value;
- }
- }
-
-#if FEATURE_CAS_POLICY
- internal HostExecutionContext HostExecutionContext
- {
- get
- {
- return _hostExecutionContext;
}
- set
+ if (Thread.CurrentThread != _thread)
{
- Contract.Assert(this != s_dummyDefaultEC);
- _hostExecutionContext = value;
- }
- }
-#endif // FEATURE_CAS_POLICY
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- internal SecurityContext SecurityContext
- {
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- get
- {
- return _securityContext;
- }
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- set
- {
- Contract.Assert(this != s_dummyDefaultEC);
- // store the new security context
- _securityContext = value;
- // perform the reverse link too
- if (value != null)
- _securityContext.ExecutionContext = this;
- }
- }
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
-
-
- public void Dispose()
- {
- if(this.IsPreAllocatedDefault)
- return; //Do nothing if this is the default context
-#if FEATURE_CAS_POLICY
- if (_hostExecutionContext != null)
- _hostExecutionContext.Dispose();
-#endif // FEATURE_CAS_POLICY
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- if (_securityContext != null)
- _securityContext.Dispose();
-#endif //FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- }
-
- [DynamicSecurityMethod]
- [System.Security.SecurityCritical] // auto-generated_required
- public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
- {
- if (executionContext == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext"));
- if (!executionContext.isNewCapture)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext"));
-
- Run(executionContext, callback, state, false);
- }
-
- // This method is special from a security perspective - the VM will not allow a stack walk to
- // continue past the call to ExecutionContext.Run. If you change the signature to this method, make
- // sure to update SecurityStackWalk::IsSpecialRunFrame in the VM to search for the new signature.
- [DynamicSecurityMethod]
- [SecurityCritical]
- [FriendAccessAllowed]
- internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
- {
- RunInternal(executionContext, callback, state, preserveSyncCtx);
- }
-
- // Actual implementation of Run is here, in a non-DynamicSecurityMethod, because the JIT seems to refuse to inline callees into
- // a DynamicSecurityMethod.
- [SecurityCritical]
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
- [HandleProcessCorruptedStateExceptions]
- internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
- {
- Contract.Assert(executionContext != null);
- if (executionContext.IsPreAllocatedDefault)
- {
- Contract.Assert(executionContext.IsDefaultFTContext(preserveSyncCtx));
- }
- else
- {
- Contract.Assert(executionContext.isNewCapture);
- executionContext.isNewCapture = false;
- }
-
- Thread currentThread = Thread.CurrentThread;
- ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- ExecutionContext.Reader ec = currentThread.GetExecutionContextReader();
- if ( (ec.IsNull || ec.IsDefaultFTContext(preserveSyncCtx)) &&
- #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) &&
- #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- executionContext.IsDefaultFTContext(preserveSyncCtx) &&
- ec.HasSameLocalValues(executionContext)
- )
- {
- // Neither context is interesting, so we don't need to set the context.
- // We do need to reset any changes made by the user's callback,
- // so here we establish a "copy-on-write scope". Any changes will
- // result in a copy of the context being made, preserving the original
- // context.
- EstablishCopyOnWriteScope(currentThread, true, ref ecsw);
- }
- else
- {
- if (executionContext.IsPreAllocatedDefault)
- executionContext = new ExecutionContext();
- ecsw = SetExecutionContext(executionContext, preserveSyncCtx);
- }
-
- //
- // Call the user's callback
- //
- callback(state);
- }
- finally
- {
- ecsw.Undo(currentThread);
- }
- }
-
- [SecurityCritical]
- static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw)
- {
- EstablishCopyOnWriteScope(currentThread, false, ref ecsw);
- }
-
- [SecurityCritical]
- static private void EstablishCopyOnWriteScope(Thread currentThread, bool knownNullWindowsIdentity, ref ExecutionContextSwitcher ecsw)
- {
- Contract.Assert(currentThread == Thread.CurrentThread);
-
- ecsw.outerEC = currentThread.GetExecutionContextReader();
- ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope;
-
-#if FEATURE_IMPERSONATION
- ecsw.cachedAlwaysFlowImpersonationPolicy = SecurityContext.AlwaysFlowImpersonationPolicy;
- if (knownNullWindowsIdentity)
- Contract.Assert(SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy) == null);
- else
- ecsw.wi = SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy);
- ecsw.wiIsValid = true;
-#endif
- currentThread.ExecutionContextBelongsToCurrentScope = false;
- ecsw.thread = currentThread;
- }
-
-
- // Sets the given execution context object on the thread.
- // Returns the previous one.
- [System.Security.SecurityCritical] // auto-generated
- [DynamicSecurityMethodAttribute()]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
-#if FEATURE_CORRUPTING_EXCEPTIONS
- [HandleProcessCorruptedStateExceptions]
-#endif // FEATURE_CORRUPTING_EXCEPTIONS
- internal static ExecutionContextSwitcher SetExecutionContext(ExecutionContext executionContext, bool preserveSyncCtx)
- {
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
-
- Contract.Assert(executionContext != null);
- Contract.Assert(executionContext != s_dummyDefaultEC);
-
- // Set up the switcher object to return;
- ExecutionContextSwitcher ecsw = new ExecutionContextSwitcher();
-
- Thread currentThread = Thread.CurrentThread;
- ExecutionContext.Reader outerEC = currentThread.GetExecutionContextReader();
-
- ecsw.thread = currentThread;
- ecsw.outerEC = outerEC;
- ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope;
-
- if (preserveSyncCtx)
- executionContext.SynchronizationContext = outerEC.SynchronizationContext;
- executionContext.SynchronizationContextNoFlow = outerEC.SynchronizationContextNoFlow;
-
- currentThread.SetExecutionContext(executionContext, belongsToCurrentScope: true);
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- OnAsyncLocalContextChanged(outerEC.DangerousGetRawExecutionContext(), executionContext);
-
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- //set the security context
- SecurityContext sc = executionContext.SecurityContext;
- if (sc != null)
- {
- // non-null SC: needs to be set
- SecurityContext.Reader prevSeC = outerEC.SecurityContext;
- ecsw.scsw = SecurityContext.SetSecurityContext(sc, prevSeC, false, ref stackMark);
- }
- else if (!SecurityContext.CurrentlyInDefaultFTSecurityContext(ecsw.outerEC))
- {
- // null incoming SC, but we're currently not in FT: use static FTSC to set
- SecurityContext.Reader prevSeC = outerEC.SecurityContext;
- ecsw.scsw = SecurityContext.SetSecurityContext(SecurityContext.FullTrustSecurityContext, prevSeC, false, ref stackMark);
- }
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
-#if FEATURE_CAS_POLICY
- // set the Host Context
- HostExecutionContext hostContext = executionContext.HostExecutionContext;
- if (hostContext != null)
- {
- ecsw.hecsw = HostExecutionContextManager.SetHostExecutionContextInternal(hostContext);
- }
-#endif // FEATURE_CAS_POLICY
- }
- catch
- {
- ecsw.UndoNoThrow(currentThread);
- throw;
- }
- return ecsw;
- }
-
- //
- // Public CreateCopy. Used to copy captured ExecutionContexts so they can be reused multiple times.
- // This should only copy the portion of the context that we actually capture.
- //
- [SecuritySafeCritical]
- public ExecutionContext CreateCopy()
- {
- if (!isNewCapture)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotCopyUsedContext"));
- }
- ExecutionContext ec = new ExecutionContext();
- ec.isNewCapture = true;
- ec._syncContext = _syncContext == null ? null : _syncContext.CreateCopy();
- ec._localValues = _localValues;
- ec._localChangeNotifications = _localChangeNotifications;
-#if FEATURE_CAS_POLICY
- // capture the host execution context
- ec._hostExecutionContext = _hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy();
-#endif // FEATURE_CAS_POLICY
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- if (_securityContext != null)
- {
- ec._securityContext = _securityContext.CreateCopy();
- ec._securityContext.ExecutionContext = ec;
+ throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCOtherThread"));
}
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
-
-#if FEATURE_REMOTING
- if (this._logicalCallContext != null)
- ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone();
-
- Contract.Assert(this._illogicalCallContext == null);
-#endif // #if FEATURE_REMOTING
-
- return ec;
- }
-
- //
- // Creates a complete copy, used for copy-on-write.
- //
- [SecuritySafeCritical]
- internal ExecutionContext CreateMutableCopy()
- {
- Contract.Assert(!this.isNewCapture);
-
- ExecutionContext ec = new ExecutionContext();
- // We don't deep-copy the SyncCtx, since we're still in the same context after copy-on-write.
- ec._syncContext = this._syncContext;
- ec._syncContextNoFlow = this._syncContextNoFlow;
-
-#if FEATURE_CAS_POLICY
- // capture the host execution context
- ec._hostExecutionContext = this._hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy();
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- if (_securityContext != null)
+ // An async flow control cannot be undone when a different execution context is applied. The desktop framework
+ // mutates the execution context when its state changes, and only changes the instance when an execution context
+ // is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution
+ // context from being applied by returning null from ExecutionContext.Capture, so the only type of execution
+ // context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async
+ // local's value, the desktop framework verifies that a different execution context has not been applied by
+ // checking the execution context instance against the one saved from when flow was suppressed. In .NET Core,
+ // since the execution context instance will change after changing the async local's value, it verifies that a
+ // different execution context has not been applied, by instead ensuring that the current execution context's
+ // flow is suppressed.
+ if (!ExecutionContext.IsFlowSuppressed())
{
- ec._securityContext = this._securityContext.CreateMutableCopy();
- ec._securityContext.ExecutionContext = ec;
- }
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
-
-#if FEATURE_REMOTING
- if (this._logicalCallContext != null)
- ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone();
-
- if (this._illogicalCallContext != null)
- ec.IllogicalCallContext = (IllogicalCallContext)this.IllogicalCallContext.CreateCopy();
-#endif // #if FEATURE_REMOTING
-
- ec._localValues = this._localValues;
- ec._localChangeNotifications = this._localChangeNotifications;
- ec.isFlowSuppressed = this.isFlowSuppressed;
-
- return ec;
- }
-
- [System.Security.SecurityCritical] // auto-generated_required
- public static AsyncFlowControl SuppressFlow()
- {
- if (IsFlowSuppressed())
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes"));
+ throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"));
}
Contract.EndContractBlock();
- AsyncFlowControl afc = new AsyncFlowControl();
- afc.Setup();
- return afc;
- }
-
- [SecuritySafeCritical]
- public static void RestoreFlow()
- {
- ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
- if (!ec.isFlowSuppressed)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow"));
- }
- ec.isFlowSuppressed = false;
- }
- [Pure]
- public static bool IsFlowSuppressed()
- {
- return Thread.CurrentThread.GetExecutionContextReader().IsFlowSuppressed;
+ _thread = null;
+ ExecutionContext.RestoreFlow();
}
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static ExecutionContext Capture()
+ public void Dispose()
{
- // set up a stack mark for finding the caller
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ExecutionContext.Capture(ref stackMark, CaptureOptions.None);
+ Undo();
}
- //
- // Captures an ExecutionContext with optimization for the "default" case, and captures a "null" synchronization context.
- // When calling ExecutionContext.Run on the returned context, specify ignoreSyncCtx = true
- //
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- [FriendAccessAllowed]
- internal static ExecutionContext FastCapture()
+ public override bool Equals(object obj)
{
- // set up a stack mark for finding the caller
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return ExecutionContext.Capture(ref stackMark, CaptureOptions.IgnoreSyncCtx | CaptureOptions.OptimizeDefaultCase);
+ return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj);
}
-
- [Flags]
- internal enum CaptureOptions
+ public bool Equals(AsyncFlowControl obj)
{
- None = 0x00,
-
- IgnoreSyncCtx = 0x01, //Don't flow SynchronizationContext
-
- OptimizeDefaultCase = 0x02, //Faster in the typical case, but can't show the result to users
- // because they could modify the shared default EC.
- // Use this only if you won't be exposing the captured EC to users.
+ return _thread == obj._thread;
}
- // internal helper to capture the current execution context using a passed in stack mark
- [System.Security.SecurityCritical] // auto-generated
- static internal ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions options)
+ public override int GetHashCode()
{
- ExecutionContext.Reader ecCurrent = Thread.CurrentThread.GetExecutionContextReader();
-
- // check to see if Flow is suppressed
- if (ecCurrent.IsFlowSuppressed)
- return null;
-
- //
- // Attempt to capture context. There may be nothing to capture...
- //
-
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- // capture the security context
- SecurityContext secCtxNew = SecurityContext.Capture(ecCurrent, ref stackMark);
-#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
-#if FEATURE_CAS_POLICY
- // capture the host execution context
- HostExecutionContext hostCtxNew = HostExecutionContextManager.CaptureHostExecutionContext();
-#endif // FEATURE_CAS_POLICY
-
- SynchronizationContext syncCtxNew = null;
-
-#if FEATURE_REMOTING
- LogicalCallContext logCtxNew = null;
-#endif
-
- if (!ecCurrent.IsNull)
- {
- // capture the sync context
- if (0 == (options & CaptureOptions.IgnoreSyncCtx))
- syncCtxNew = (ecCurrent.SynchronizationContext == null) ? null : ecCurrent.SynchronizationContext.CreateCopy();
-
-#if FEATURE_REMOTING
- // copy over the Logical Call Context
- if (ecCurrent.LogicalCallContext.HasInfo)
- logCtxNew = ecCurrent.LogicalCallContext.Clone();
-#endif // #if FEATURE_REMOTING
- }
-
- Dictionary<IAsyncLocal, object> localValues = null;
- List<IAsyncLocal> localChangeNotifications = null;
- if (!ecCurrent.IsNull)
- {
- localValues = ecCurrent.DangerousGetRawExecutionContext()._localValues;
- localChangeNotifications = ecCurrent.DangerousGetRawExecutionContext()._localChangeNotifications;
- }
-
- //
- // If we didn't get anything but defaults, and we're allowed to return the
- // dummy default EC, don't bother allocating a new context.
- //
- if (0 != (options & CaptureOptions.OptimizeDefaultCase) &&
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- secCtxNew == null &&
-#endif
-#if FEATURE_CAS_POLICY
- hostCtxNew == null &&
-#endif // FEATURE_CAS_POLICY
- syncCtxNew == null &&
-#if FEATURE_REMOTING
- (logCtxNew == null || !logCtxNew.HasInfo) &&
-#endif // #if FEATURE_REMOTING
- localValues == null &&
- localChangeNotifications == null
- )
- {
- return s_dummyDefaultEC;
- }
-
- //
- // Allocate the new context, and fill it in.
- //
- ExecutionContext ecNew = new ExecutionContext();
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- ecNew.SecurityContext = secCtxNew;
- if (ecNew.SecurityContext != null)
- ecNew.SecurityContext.ExecutionContext = ecNew;
-#endif
-#if FEATURE_CAS_POLICY
- ecNew._hostExecutionContext = hostCtxNew;
-#endif // FEATURE_CAS_POLICY
- ecNew._syncContext = syncCtxNew;
-#if FEATURE_REMOTING
- ecNew.LogicalCallContext = logCtxNew;
-#endif // #if FEATURE_REMOTING
- ecNew._localValues = localValues;
- ecNew._localChangeNotifications = localChangeNotifications;
- ecNew.isNewCapture = true;
-
- return ecNew;
+ return _thread?.GetHashCode() ?? 0;
}
- //
- // Implementation of ISerializable
- //
-
- [System.Security.SecurityCritical] // auto-generated_required
- public void GetObjectData(SerializationInfo info, StreamingContext context)
+ public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
{
- if (info==null)
- throw new ArgumentNullException("info");
- Contract.EndContractBlock();
-
-#if FEATURE_REMOTING
- if (_logicalCallContext != null)
- {
- info.AddValue("LogicalCallContext", _logicalCallContext, typeof(LogicalCallContext));
- }
-#endif // #if FEATURE_REMOTING
+ return a.Equals(b);
}
- [System.Security.SecurityCritical] // auto-generated
- private ExecutionContext(SerializationInfo info, StreamingContext context)
- {
- SerializationInfoEnumerator e = info.GetEnumerator();
- while (e.MoveNext())
- {
-#if FEATURE_REMOTING
- if (e.Name.Equals("LogicalCallContext"))
- {
- _logicalCallContext = (LogicalCallContext) e.Value;
- }
-#endif // #if FEATURE_REMOTING
- }
- } // ObjRef .ctor
-
-
- [System.Security.SecurityCritical] // auto-generated
- internal bool IsDefaultFTContext(bool ignoreSyncCtx)
+ public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
{
-#if FEATURE_CAS_POLICY
- if (_hostExecutionContext != null)
- return false;
-#endif // FEATURE_CAS_POLICY
- if (!ignoreSyncCtx && _syncContext != null)
- return false;
-#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
- if (_securityContext != null && !_securityContext.IsDefaultFTSecurityContext())
- return false;
-#endif //#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
-#if FEATURE_REMOTING
- if (_logicalCallContext != null && _logicalCallContext.HasInfo)
- return false;
- if (_illogicalCallContext != null && _illogicalCallContext.HasUserData)
- return false;
-#endif //#if FEATURE_REMOTING
- return true;
+ return !(a == b);
}
- } // class ExecutionContext
-
-#endif //FEATURE_CORECLR
+ }
}
diff --git a/src/mscorlib/src/System/Threading/Interlocked.cs b/src/mscorlib/src/System/Threading/Interlocked.cs
index 50cc766d61..8a0b527fc0 100644
--- a/src/mscorlib/src/System/Threading/Interlocked.cs
+++ b/src/mscorlib/src/System/Threading/Interlocked.cs
@@ -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);
/******************************
diff --git a/src/mscorlib/src/System/Threading/LazyInitializer.cs b/src/mscorlib/src/System/Threading/LazyInitializer.cs
index c8e74e30e3..238cc89dbd 100644
--- a/src/mscorlib/src/System/Threading/LazyInitializer.cs
+++ b/src/mscorlib/src/System/Threading/LazyInitializer.cs
@@ -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;
}
diff --git a/src/mscorlib/src/System/Threading/LockRecursionException.cs b/src/mscorlib/src/System/Threading/LockRecursionException.cs
index c5e3146cbc..ab95e70c7e 100644
--- a/src/mscorlib/src/System/Threading/LockRecursionException.cs
+++ b/src/mscorlib/src/System/Threading/LockRecursionException.cs
@@ -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() { }
diff --git a/src/mscorlib/src/System/Threading/ManualResetEvent.cs b/src/mscorlib/src/System/Threading/ManualResetEvent.cs
index 504cfb423c..00041567df 100644
--- a/src/mscorlib/src/System/Threading/ManualResetEvent.cs
+++ b/src/mscorlib/src/System/Threading/ManualResetEvent.cs
@@ -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
{
diff --git a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
index b6114ef917..509af5bfa0 100644
--- a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
+++ b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
@@ -13,10 +13,10 @@
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
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)
@@ -218,13 +217,13 @@ namespace System.Threading
{
if (spinCount < 0)
{
- throw new ArgumentOutOfRangeException("spinCount");
+ throw new ArgumentOutOfRangeException(nameof(spinCount));
}
if (spinCount > SpinCountState_MaxValue)
{
throw new ArgumentOutOfRangeException(
- "spinCount",
+ nameof(spinCount),
String.Format(Environment.GetResourceString("ManualResetEventSlim_ctor_SpinCountOutOfRange"), SpinCountState_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)
{
@@ -464,7 +463,7 @@ namespace System.Threading
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
- throw new ArgumentOutOfRangeException("timeout");
+ throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, new CancellationToken());
@@ -495,7 +494,7 @@ namespace System.Threading
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
- throw new ArgumentOutOfRangeException("timeout");
+ throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, cancellationToken);
@@ -544,7 +543,7 @@ namespace System.Threading
if (millisecondsTimeout < -1)
{
- throw new ArgumentOutOfRangeException("millisecondsTimeout");
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
}
if (!IsSet)
@@ -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
{
diff --git a/src/mscorlib/src/System/Threading/Monitor.cs b/src/mscorlib/src/System/Threading/Monitor.cs
index 415948b425..94dec13d05 100644
--- a/src/mscorlib/src/System/Threading/Monitor.cs
+++ b/src/mscorlib/src/System/Threading/Monitor.cs
@@ -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);
@@ -127,7 +124,7 @@ namespace System.Threading {
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long)Int32.MaxValue)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
return (int)tm;
}
@@ -154,20 +151,17 @@ 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)
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
return IsEnteredNative(obj);
}
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsEnteredNative(Object obj);
@@ -182,15 +176,13 @@ 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)
- throw (new ArgumentNullException("obj"));
+ throw (new ArgumentNullException(nameof(obj)));
return ObjWait(exitContext, millisecondsTimeout, obj);
}
@@ -219,16 +211,14 @@ 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)
{
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
@@ -237,16 +227,14 @@ 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)
{
- throw new ArgumentNullException("obj");
+ throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Threading/Mutex.cs b/src/mscorlib/src/System/Threading/Mutex.cs
index 2e9b68176d..506abb7a07 100644
--- a/src/mscorlib/src/System/Threading/Mutex.cs
+++ b/src/mscorlib/src/System/Threading/Mutex.cs
@@ -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)
{
@@ -60,29 +53,15 @@ namespace System.Threading
#if !PLATFORM_UNIX
if (name != null && System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
}
#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)
{
@@ -94,7 +73,7 @@ namespace System.Threading
#if !PLATFORM_UNIX
if (name != null && System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
}
#endif
Contract.EndContractBlock();
@@ -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
{
@@ -182,7 +153,7 @@ namespace System.Threading
#if PLATFORM_UNIX
case Win32Native.ERROR_FILENAME_EXCED_RANGE:
// On Unix, length validation is done by CoreCLR's PAL after converting to utf-8
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPathComponentLength), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", PathInternal.MaxComponentLength), "name");
#endif
case Win32Native.ERROR_INVALID_HANDLE:
@@ -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,38 +248,31 @@ 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)
{
- throw new ArgumentNullException("name", Environment.GetResourceString("ArgumentNull_WithParamName"));
+ throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName"));
}
if(name.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
}
#if !PLATFORM_UNIX
if(System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
}
#endif
Contract.EndContractBlock();
@@ -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)
@@ -357,7 +294,7 @@ namespace System.Threading
if (name != null && errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE)
{
// On Unix, length validation is done by CoreCLR's PAL after converting to utf-8
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPathComponentLength), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", PathInternal.MaxComponentLength), nameof(name));
}
#endif
@@ -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("mutexSecurity");
- Contract.EndContractBlock();
-
- mutexSecurity.Persist(safeWaitHandle);
- }
-#endif
-
}
}
diff --git a/src/mscorlib/src/System/Threading/Overlapped.cs b/src/mscorlib/src/System/Threading/Overlapped.cs
index 3f9fbc4989..2b192c7b3a 100644
--- a/src/mscorlib/src/System/Threading/Overlapped.cs
+++ b/src/mscorlib/src/System/Threading/Overlapped.cs
@@ -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,12 +359,11 @@ 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)
{
if (nativeOverlappedPtr == null)
- throw new ArgumentNullException("nativeOverlappedPtr");
+ throw new ArgumentNullException(nameof(nativeOverlappedPtr));
Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
@@ -400,12 +371,11 @@ namespace System.Threading
return overlapped;
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
unsafe public static void Free(NativeOverlapped* nativeOverlappedPtr)
{
if (nativeOverlappedPtr == null)
- throw new ArgumentNullException("nativeOverlappedPtr");
+ throw new ArgumentNullException(nameof(nativeOverlappedPtr));
Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
diff --git a/src/mscorlib/src/System/Threading/ReaderWriterLock.cs b/src/mscorlib/src/System/Threading/ReaderWriterLock.cs
index 8cead1a87a..e35ac7685b 100644
--- a/src/mscorlib/src/System/Threading/ReaderWriterLock.cs
+++ b/src/mscorlib/src/System/Threading/ReaderWriterLock.cs
@@ -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,23 +81,20 @@ 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;
if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
AcquireReaderLockInternal((int)tm);
}
@@ -113,22 +104,19 @@ 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;
if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
AcquireWriterLockInternal((int)tm);
}
@@ -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);
@@ -184,7 +166,7 @@ namespace System.Threading {
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
return UpgradeToWriterLock((int)tm);
}
@@ -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();
diff --git a/src/mscorlib/src/System/Threading/Semaphore.cs b/src/mscorlib/src/System/Threading/Semaphore.cs
index 303593b776..1eac4aaaeb 100644
--- a/src/mscorlib/src/System/Threading/Semaphore.cs
+++ b/src/mscorlib/src/System/Threading/Semaphore.cs
@@ -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,20 +14,18 @@ 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)
{
- throw new ArgumentOutOfRangeException("initialCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(initialCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (maximumCount < 1)
{
- throw new ArgumentOutOfRangeException("maximumCount", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(maximumCount), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if (initialCount > maximumCount)
@@ -49,17 +48,16 @@ namespace System.Threading
this.SafeWaitHandle = myHandle;
}
- [SecurityCritical]
public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew)
{
if (initialCount < 0)
{
- throw new ArgumentOutOfRangeException("initialCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(initialCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (maximumCount < 1)
{
- throw new ArgumentOutOfRangeException("maximumCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(maximumCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (initialCount > maximumCount)
@@ -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)
@@ -96,19 +92,17 @@ namespace System.Threading
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
#else
if (name.Length > Path.MaxPath)
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
#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,24 +119,22 @@ 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
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
#else
if (name == null)
- throw new ArgumentNullException("name", Environment.GetResourceString("ArgumentNull_WithParamName"));
+ throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName"));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
if (name.Length > Path.MaxPath)
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), "name");
+ throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
const int SYNCHRONIZE = 0x00100000;
const int SEMAPHORE_MODIFY_STATE = 0x00000002;
@@ -177,12 +169,11 @@ namespace System.Threading
}
// increase the count on a semaphore, returns previous count
- [SecuritySafeCritical]
public int Release(int releaseCount)
{
if (releaseCount < 1)
{
- throw new ArgumentOutOfRangeException("releaseCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(releaseCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
//If ReleaseSempahore returns false when the specified value would cause
diff --git a/src/mscorlib/src/System/Threading/SemaphoreFullException.cs b/src/mscorlib/src/System/Threading/SemaphoreFullException.cs
index e1928e05de..01c5040b7e 100644
--- a/src/mscorlib/src/System/Threading/SemaphoreFullException.cs
+++ b/src/mscorlib/src/System/Threading/SemaphoreFullException.cs
@@ -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")){
diff --git a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
index c2dcbb3451..92d760d77d 100644
--- a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
+++ b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
@@ -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
@@ -182,13 +179,13 @@ namespace System.Threading
if (initialCount < 0 || initialCount > maxCount)
{
throw new ArgumentOutOfRangeException(
- "initialCount", initialCount, GetResourceString("SemaphoreSlim_ctor_InitialCountWrong"));
+ nameof(initialCount), initialCount, GetResourceString("SemaphoreSlim_ctor_InitialCountWrong"));
}
//validate input
if (maxCount <= 0)
{
- throw new ArgumentOutOfRangeException("maxCount", maxCount, GetResourceString("SemaphoreSlim_ctor_MaxCountWrong"));
+ throw new ArgumentOutOfRangeException(nameof(maxCount), maxCount, GetResourceString("SemaphoreSlim_ctor_MaxCountWrong"));
}
m_maxCount = maxCount;
@@ -245,7 +242,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- "timeout", timeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(timeout), timeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
}
// Call wait with the timeout milliseconds
@@ -275,7 +272,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- "timeout", timeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(timeout), timeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
}
// Call wait with the timeout milliseconds
@@ -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)
{
@@ -579,7 +576,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- "timeout", timeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(timeout), timeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
}
// Call wait with the timeout milliseconds
@@ -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
@@ -776,7 +773,7 @@ namespace System.Threading
if (releaseCount < 1)
{
throw new ArgumentOutOfRangeException(
- "releaseCount", releaseCount, GetResourceString("SemaphoreSlim_Release_CountWrong"));
+ nameof(releaseCount), releaseCount, GetResourceString("SemaphoreSlim_Release_CountWrong"));
}
int returnCount;
@@ -797,14 +794,12 @@ namespace System.Threading
// Signal to any synchronous waiters
int waitCount = m_waitCount;
- if (currentCount == 1 || waitCount == 1)
+
+ int waitersToNotify = Math.Min(releaseCount, waitCount);
+ for (int i = 0; i < waitersToNotify; i++)
{
Monitor.Pulse(m_lockObj);
}
- else if (waitCount > 1)
- {
- Monitor.PulseAll(m_lockObj);
- }
// Now signal to any asynchronous waiters, if there are any. While we've already
// signaled the synchronous waiters, we still hold the lock, and thus
@@ -814,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)
{
@@ -844,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);
@@ -898,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.
diff --git a/src/mscorlib/src/System/Threading/SpinLock.cs b/src/mscorlib/src/System/Threading/SpinLock.cs
index dea87435a7..1d90890d6e 100644
--- a/src/mscorlib/src/System/Threading/SpinLock.cs
+++ b/src/mscorlib/src/System/Threading/SpinLock.cs
@@ -12,11 +12,11 @@
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
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
@@ -225,7 +219,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- "timeout", timeout, Environment.GetResourceString("SpinLock_TryEnter_ArgumentOutOfRange"));
+ nameof(timeout), timeout, Environment.GetResourceString("SpinLock_TryEnter_ArgumentOutOfRange"));
}
// Call reliable enter with the int-based timeout milliseconds
@@ -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)
{
@@ -291,23 +277,15 @@ namespace System.Threading
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
- "millisecondsTimeout", millisecondsTimeout, Environment.GetResourceString("SpinLock_TryEnter_ArgumentOutOfRange"));
+ 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,18 +311,22 @@ 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
+ return;
+ }
+ }
+ else if (millisecondsTimeout == 0)
+ {
+ // Did not aquire lock as owned and timeout is 0 so fail fast
+ return;
}
else //failed to acquire the lock,then try to update the waiters. If the waiters count reached the maximum, jsut break the loop to avoid overflow
{
@@ -352,17 +334,6 @@ namespace System.Threading
turn = (Interlocked.Add(ref m_owner, 2) & WAITERS_MASK) >> 1 ;
}
-
-
- // Check the timeout.
- if (millisecondsTimeout == 0 ||
- (millisecondsTimeout != Timeout.Infinite &&
- TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0))
- {
- DecrementWaiters();
- return;
- }
-
//***Step 2. Spinning
//lock acquired failed and waiters updated
int processorCount = PlatformHelper.ProcessorCount;
@@ -377,32 +348,24 @@ 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
}
}
- }
- // Check the timeout.
- if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0)
- {
- DecrementWaiters();
- return;
+ // Check the timeout.
+ if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0)
+ {
+ DecrementWaiters();
+ return;
+ }
}
//*** Step 3, Yielding
@@ -413,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)
@@ -470,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();
@@ -483,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.
@@ -510,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 ||
@@ -550,11 +499,6 @@ namespace System.Threading
ExitSlowPath(true);
else
Interlocked.Decrement(ref m_owner);
-
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
-
}
/// <summary>
@@ -586,10 +530,6 @@ namespace System.Threading
}
else
ExitSlowPath(useMemoryBarrier);
-
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
}
/// <summary>
diff --git a/src/mscorlib/src/System/Threading/SpinWait.cs b/src/mscorlib/src/System/Threading/SpinWait.cs
index c2cd0b6203..1b31407e0f 100644
--- a/src/mscorlib/src/System/Threading/SpinWait.cs
+++ b/src/mscorlib/src/System/Threading/SpinWait.cs
@@ -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
}
@@ -220,7 +216,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- "timeout", timeout, Environment.GetResourceString("SpinWait_SpinUntil_TimeoutWrong"));
+ nameof(timeout), timeout, Environment.GetResourceString("SpinWait_SpinUntil_TimeoutWrong"));
}
// Call wait with the timeout milliseconds
@@ -242,11 +238,11 @@ namespace System.Threading
if (millisecondsTimeout < Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(
- "millisecondsTimeout", millisecondsTimeout, Environment.GetResourceString("SpinWait_SpinUntil_TimeoutWrong"));
+ nameof(millisecondsTimeout), millisecondsTimeout, Environment.GetResourceString("SpinWait_SpinUntil_TimeoutWrong"));
}
if (condition == null)
{
- throw new ArgumentNullException("condition", Environment.GetResourceString("SpinWait_SpinUntil_ArgumentNull"));
+ throw new ArgumentNullException(nameof(condition), Environment.GetResourceString("SpinWait_SpinUntil_ArgumentNull"));
}
uint startTime = 0;
if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite)
@@ -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);
diff --git a/src/mscorlib/src/System/Threading/SynchronizationContext.cs b/src/mscorlib/src/System/Threading/SynchronizationContext.cs
index a3f28d1d73..5531597229 100644
--- a/src/mscorlib/src/System/Threading/SynchronizationContext.cs
+++ b/src/mscorlib/src/System/Threading/SynchronizationContext.cs
@@ -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()
{
@@ -143,39 +138,43 @@ namespace System.Threading
}
#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
- // Method called when the CLR does a wait operation
- [System.Security.SecurityCritical] // auto-generated_required
+ // Method called when the CLR does a wait operation
[CLSCompliant(false)]
[PrePrepareMethod]
public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
{
+ return WaitHelper(waitHandles, waitAll, millisecondsTimeout);
+ }
+
+ // Method that can be called by Wait overrides
+ [CLSCompliant(false)]
+ [PrePrepareMethod]
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
+ protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
+ {
if (waitHandles == null)
{
- throw new ArgumentNullException("waitHandles");
+ throw new ArgumentNullException(nameof(waitHandles));
}
Contract.EndContractBlock();
- return WaitHelper(waitHandles, waitAll, millisecondsTimeout);
+
+ return WaitHelperNative(waitHandles, waitAll, millisecondsTimeout);
}
-
- // Static helper to which the above method can delegate to in order to get the default
+
+ // 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)]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- protected static extern int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
+ 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;
@@ -206,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:
@@ -274,10 +228,8 @@ namespace System.Threading
return null;
}
- [SecurityCritical]
static WinRTSynchronizationContextFactoryBase s_winRTContextFactory;
- [SecurityCritical]
private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory()
{
//
@@ -295,7 +247,6 @@ namespace System.Threading
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Interface)]
private static extern object GetWinRTDispatcherForCurrentThread();
@@ -310,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);
diff --git a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs
index c29b11a922..ec7c5aaeea 100644
--- a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs b/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs
index 05e6dbf1a9..71eb787c5e 100644
--- a/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
index cb4a22bb2b..c7a96b0394 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
@@ -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
@@ -101,9 +100,9 @@ namespace System.Threading.Tasks
public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask)
{
// Validate arguments
- if (taskScheduler == null) throw new ArgumentNullException("taskScheduler");
- if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException("maxConcurrencyLevel");
- if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException("maxItemsPerTask");
+ if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler));
+ if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel));
+ if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask));
Contract.EndContractBlock();
// Store configuration
@@ -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
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
index b1f634c707..c98e219e86 100644
--- a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
@@ -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
@@ -832,32 +832,17 @@ namespace System.Threading.Tasks
try
{
- // Do NOT change the code below.
- // 4.5 relies on the fact that IAsyncResult CompletedSynchronously flag needs to be set correctly,
- // sadly this has not been the case that is why the behaviour from 4.5 broke 4.0 buggy apps. Any other
- // change will likely brake 4.5 behavior so if possible never touch this code again.
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
+ //This is 4.5 behaviour
+ //if we don't require synchronization, a faster set result path is taken
+ var asyncResult = beginMethod(iar =>
{
- //This is 4.5 behaviour
- //if we don't require synchronization, a faster set result path is taken
- var asyncResult = beginMethod(iar =>
- {
- if (!iar.CompletedSynchronously)
- FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
- }, state);
- if (asyncResult.CompletedSynchronously)
- {
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
- FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
- }
- }
- else
- {
- //This is the original 4.0 behaviour
- var asyncResult = beginMethod(iar =>
- {
+ if (!iar.CompletedSynchronously)
FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
- }, state);
+ }, state);
+ if (asyncResult.CompletedSynchronously)
+ {
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
catch
@@ -969,31 +954,16 @@ namespace System.Threading.Tasks
try
{
- // Do NOT change the code below.
- // 4.5 relies on the fact that IAsyncResult CompletedSynchronously flag needs to be set correctly,
- // sadly this has not been the case that is why the behaviour from 4.5 broke 4.0 buggy apps. Any other
- // change will likely brake 4.5 behavior so if possible never touch this code again.
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
+ //if we don't require synchronization, a faster set result path is taken
+ var asyncResult = beginMethod(arg1, iar =>
{
- //if we don't require synchronization, a faster set result path is taken
- var asyncResult = beginMethod(arg1, iar =>
- {
- if (!iar.CompletedSynchronously)
- FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
- }, state);
- if (asyncResult.CompletedSynchronously)
- {
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
- FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
- }
- }
- else
- {
- //quirk for previous versions
- var asyncResult = beginMethod(arg1, iar =>
- {
+ if (!iar.CompletedSynchronously)
FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
- }, state);
+ }, state);
+ if (asyncResult.CompletedSynchronously)
+ {
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
catch
@@ -1114,31 +1084,16 @@ namespace System.Threading.Tasks
try
{
- // Do NOT change the code below.
- // 4.5 relies on the fact that IAsyncResult CompletedSynchronously flag needs to be set correctly,
- // sadly this has not been the case that is why the behaviour from 4.5 broke 4.0 buggy apps. Any other
- // change will likely brake 4.5 behavior so if possible never touch this code again.
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
+ //if we don't require synchronization, a faster set result path is taken
+ var asyncResult = beginMethod(arg1, arg2, iar =>
{
- //if we don't require synchronization, a faster set result path is taken
- var asyncResult = beginMethod(arg1, arg2, iar =>
- {
- if (!iar.CompletedSynchronously)
- FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
- }, state);
- if (asyncResult.CompletedSynchronously)
- {
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
- FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
- }
- }
- else
- {
- //quirk for previous versions
- var asyncResult = beginMethod(arg1, arg2, iar =>
- {
+ if (!iar.CompletedSynchronously)
FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
- }, state);
+ }, state);
+ if (asyncResult.CompletedSynchronously)
+ {
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
catch
@@ -1266,31 +1221,16 @@ namespace System.Threading.Tasks
try
{
- // Do NOT change the code below.
- // 4.5 relies on the fact that IAsyncResult CompletedSynchronously flag needs to be set correctly,
- // sadly this has not been the case that is why the behaviour from 4.5 broke 4.0 buggy apps. Any other
- // change will likely brake 4.5 behavior so if possible never touch this code again.
- if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
+ //if we don't require synchronization, a faster set result path is taken
+ var asyncResult = beginMethod(arg1, arg2, arg3, iar =>
{
- //if we don't require synchronization, a faster set result path is taken
- var asyncResult = beginMethod(arg1, arg2, arg3, iar =>
- {
- if (!iar.CompletedSynchronously)
- FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
- }, state);
- if (asyncResult.CompletedSynchronously)
- {
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
- FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
- }
- }
- else
- {
- //quirk for previous versions
- var asyncResult = beginMethod(arg1, arg2, arg3, iar =>
- {
+ if (!iar.CompletedSynchronously)
FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
- }, state);
+ }, state);
+ if (asyncResult.CompletedSynchronously)
+ {
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
catch
@@ -1330,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
@@ -1345,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);
}
@@ -1425,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;
@@ -1454,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");
}
}
@@ -1801,7 +1741,7 @@ namespace System.Threading.Tasks
}
else
{
- Contract.Assert(continuationAction != null);
+ Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
// use a cached delegate
@@ -1854,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;
@@ -2200,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
@@ -2246,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,
diff --git a/src/mscorlib/src/System/Threading/Tasks/Parallel.cs b/src/mscorlib/src/System/Threading/Tasks/Parallel.cs
index 5ec2ae33c0..7808943870 100644
--- a/src/mscorlib/src/System/Threading/Tasks/Parallel.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/Parallel.cs
@@ -98,7 +98,7 @@ namespace System.Threading.Tasks
set
{
if ((value == 0) || (value < -1))
- throw new ArgumentOutOfRangeException("MaxDegreeOfParallelism");
+ throw new ArgumentOutOfRangeException(nameof(MaxDegreeOfParallelism));
m_maxDegreeOfParallelism = value;
}
}
@@ -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
@@ -208,11 +207,11 @@ namespace System.Threading.Tasks
{
if (actions == null)
{
- throw new ArgumentNullException("actions");
+ throw new ArgumentNullException(nameof(actions));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
// Throw an ODE if we're passed a disposed CancellationToken.
@@ -423,7 +422,7 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
return ForWorker<object>(
@@ -452,7 +451,7 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
return ForWorker64<object>(
@@ -491,11 +490,11 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForWorker<object>(
@@ -534,11 +533,11 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForWorker64<object>(
@@ -590,7 +589,7 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
return ForWorker<object>(
@@ -620,7 +619,7 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
return ForWorker64<object>(
@@ -661,11 +660,11 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForWorker<object>(
@@ -707,11 +706,11 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForWorker64<object>(
@@ -765,15 +764,15 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
return ForWorker(
@@ -827,15 +826,15 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
return ForWorker64(
@@ -900,19 +899,19 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForWorker(
@@ -977,19 +976,19 @@ namespace System.Threading.Tasks
{
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
@@ -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.
@@ -1656,11 +1655,11 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
return ForEachWorker<TSource, object>(
@@ -1701,15 +1700,15 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForEachWorker<TSource, object>(
@@ -1741,11 +1740,11 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
return ForEachWorker<TSource, object>(
@@ -1788,15 +1787,15 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForEachWorker<TSource, object>(
@@ -1828,11 +1827,11 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
return ForEachWorker<TSource, object>(
@@ -1875,15 +1874,15 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForEachWorker<TSource, object>(
@@ -1936,19 +1935,19 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
return ForEachWorker<TSource, TLocal>(
@@ -2013,23 +2012,23 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForEachWorker<TSource, TLocal>(
@@ -2082,19 +2081,19 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
return ForEachWorker<TSource, TLocal>(
@@ -2158,23 +2157,23 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return ForEachWorker<TSource, TLocal>(
@@ -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)
{
@@ -2416,11 +2415,11 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
return PartitionerForEachWorker<TSource, object>(source, s_defaultParallelOptions, body, null, null, null, null, null, null);
@@ -2475,11 +2474,11 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
return PartitionerForEachWorker<TSource, object>(source, s_defaultParallelOptions, null, body, null, null, null, null, null);
@@ -2537,11 +2536,11 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (!source.KeysNormalized)
@@ -2621,19 +2620,19 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
return PartitionerForEachWorker<TSource, TLocal>(source, s_defaultParallelOptions, null, null, null, body, null, localInit, localFinally);
@@ -2711,19 +2710,19 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
if (!source.KeysNormalized)
@@ -2793,15 +2792,15 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return PartitionerForEachWorker<TSource, object>(source, parallelOptions, body, null, null, null, null, null, null);
@@ -2868,15 +2867,15 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return PartitionerForEachWorker<TSource, object>(source, parallelOptions, null, body, null, null, null, null, null);
@@ -2946,15 +2945,15 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
if (!source.KeysNormalized)
@@ -3046,23 +3045,23 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
return PartitionerForEachWorker<TSource, TLocal>(source, parallelOptions, null, null, null, body, null, localInit, localFinally);
@@ -3152,23 +3151,23 @@ namespace System.Threading.Tasks
{
if (source == null)
{
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (body == null)
{
- throw new ArgumentNullException("body");
+ throw new ArgumentNullException(nameof(body));
}
if (localInit == null)
{
- throw new ArgumentNullException("localInit");
+ throw new ArgumentNullException(nameof(localInit));
}
if (localFinally == null)
{
- throw new ArgumentNullException("localFinally");
+ throw new ArgumentNullException(nameof(localFinally));
}
if (parallelOptions == null)
{
- throw new ArgumentNullException("parallelOptions");
+ throw new ArgumentNullException(nameof(parallelOptions));
}
if (!source.KeysNormalized)
@@ -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.
diff --git a/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs b/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs
index 4db3a9d105..6a62cf8977 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs
@@ -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"));
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs b/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs
index c4b66c41a9..49f61a6614 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
index 462ee0a9bd..6b9dfbbe37 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
@@ -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;
diff --git a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
index 5f79f30b35..325aa91b44 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs
index 36f8401a4d..cf081f75fd 100644
--- a/src/mscorlib/src/System/Threading/Tasks/Task.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs
@@ -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
@@ -152,7 +151,7 @@ namespace System.Threading.Tasks
private volatile int m_taskId; // this task's unique ID. initialized only if it is ever requested
- internal object m_action; // The body of the task. Might be Action<object>, Action<TState> or Action. Or possibly a Func.
+ internal Delegate m_action; // The body of the task. Might be Action<object>, Action<TState> or Action. Or possibly a Func.
// If m_action is set to null it will indicate that we operate in the
// "externally triggered completion" mode, which is exclusively meant
// for the signalling Task<TResult> (aka. promise). In this mode,
@@ -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
@@ -580,7 +579,7 @@ namespace System.Threading.Tasks
/// <param name="cancellationToken">A CancellationToken for the Task.</param>
/// <param name="creationOptions">Options to customize behavior of Task.</param>
/// <param name="internalOptions">Internal options to customize behavior of Task.</param>
- internal void TaskConstructorCore(object action, object state, CancellationToken cancellationToken,
+ internal void TaskConstructorCore(Delegate action, object state, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
{
m_action = action;
@@ -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);
}
@@ -753,7 +752,7 @@ namespace System.Threading.Tasks
{
get
{
- Delegate d = (Delegate)m_action;
+ Delegate d = m_action;
return d != null ? d.Method.ToString() : "{null}";
}
}
@@ -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)
@@ -1912,7 +1908,7 @@ namespace System.Threading.Tasks
if (AsyncCausalityTracer.LoggingOn && (Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0)
{
//For all other task than TaskContinuations we want to log. TaskContinuations log in their constructor
- AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "Task: "+((Delegate)m_action).Method.Name, 0);
+ AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "Task: " + m_action.Method.Name, 0);
}
@@ -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.
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
index 8b1dd2a62f..320f704f09 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
@@ -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);
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
index 4c035dfddb..70b9418dbf 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
@@ -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
@@ -305,7 +305,7 @@ namespace System.Threading.Tasks
m_options = options;
m_taskScheduler = scheduler;
if (AsyncCausalityTracer.LoggingOn)
- AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, m_task.Id, "Task.ContinueWith: " + ((Delegate)task.m_action).Method.Name, 0);
+ AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, m_task.Id, "Task.ContinueWith: " + task.m_action.Method.Name, 0);
if (Task.s_asyncDebuggingEnabled)
{
@@ -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.
@@ -374,7 +374,7 @@ namespace System.Threading.Tasks
return m_task.GetDelegateContinuationsForDebugger();
}
- return new Delegate[] { m_task.m_action as Delegate };
+ return new Delegate[] { m_task.m_action };
}
}
@@ -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) };
}
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
index 198db8e15c..45817dab23 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
@@ -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,17 +283,17 @@ 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
}
// Anything else is a programming error
else
{
- throw new ArgumentException(Environment.GetResourceString("TaskExceptionHolder_UnknownExceptionType"), "exceptionObject");
+ throw new ArgumentException(Environment.GetResourceString("TaskExceptionHolder_UnknownExceptionType"), nameof(exceptionObject));
}
}
}
@@ -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;
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
index 52b471628a..aa4c2df74b 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
@@ -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
@@ -225,7 +225,7 @@ namespace System.Threading.Tasks
TaskCreationOptions.PreferFairness |
TaskCreationOptions.RunContinuationsAsynchronously)) != 0)
{
- throw new ArgumentOutOfRangeException("creationOptions");
+ throw new ArgumentOutOfRangeException(nameof(creationOptions));
}
Contract.EndContractBlock();
}
@@ -1593,9 +1593,9 @@ namespace System.Threading.Tasks
{
// Options detected here cause exceptions in FromAsync methods that take beginMethod as a parameter
if ((creationOptions & TaskCreationOptions.LongRunning) != 0)
- throw new ArgumentOutOfRangeException("creationOptions", Environment.GetResourceString("Task_FromAsync_LongRunning"));
+ throw new ArgumentOutOfRangeException(nameof(creationOptions), Environment.GetResourceString("Task_FromAsync_LongRunning"));
if ((creationOptions & TaskCreationOptions.PreferFairness) != 0)
- throw new ArgumentOutOfRangeException("creationOptions", Environment.GetResourceString("Task_FromAsync_PreferFairness"));
+ throw new ArgumentOutOfRangeException(nameof(creationOptions), Environment.GetResourceString("Task_FromAsync_PreferFairness"));
}
// Check for general validity of options
@@ -1606,7 +1606,7 @@ namespace System.Threading.Tasks
TaskCreationOptions.PreferFairness |
TaskCreationOptions.LongRunning)) != 0)
{
- throw new ArgumentOutOfRangeException("creationOptions");
+ throw new ArgumentOutOfRangeException(nameof(creationOptions));
}
}
@@ -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; } }
@@ -1801,7 +1801,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -1833,7 +1833,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, CancellationToken cancellationToken)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -1870,7 +1870,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, TaskContinuationOptions continuationOptions)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -1918,7 +1918,7 @@ namespace System.Threading.Tasks
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -1945,7 +1945,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -1979,7 +1979,7 @@ namespace System.Threading.Tasks
public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction,
CancellationToken cancellationToken)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2018,7 +2018,7 @@ namespace System.Threading.Tasks
public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction,
TaskContinuationOptions continuationOptions)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2067,7 +2067,7 @@ namespace System.Threading.Tasks
public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2097,7 +2097,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2133,7 +2133,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2174,7 +2174,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2226,7 +2226,7 @@ namespace System.Threading.Tasks
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2258,7 +2258,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2295,7 +2295,7 @@ namespace System.Threading.Tasks
public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
CancellationToken cancellationToken)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2338,7 +2338,7 @@ namespace System.Threading.Tasks
public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2391,7 +2391,7 @@ namespace System.Threading.Tasks
public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -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.
@@ -2489,7 +2489,7 @@ namespace System.Threading.Tasks
for(int i=0; i<numTasks; i++)
{
var task = tasks[i];
- if (task == null) throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
+ if (task == null) throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks));
if (checkArgsOnly) continue;
@@ -2531,7 +2531,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2562,7 +2562,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, CancellationToken cancellationToken)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2599,7 +2599,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2647,7 +2647,7 @@ namespace System.Threading.Tasks
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2678,7 +2678,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2713,7 +2713,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2754,7 +2754,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2806,7 +2806,7 @@ namespace System.Threading.Tasks
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2838,7 +2838,7 @@ namespace System.Threading.Tasks
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark);
}
@@ -2872,7 +2872,7 @@ namespace System.Threading.Tasks
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
CancellationToken cancellationToken)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2915,7 +2915,7 @@ namespace System.Threading.Tasks
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2968,7 +2968,7 @@ namespace System.Threading.Tasks
public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
+ if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -2996,7 +2996,7 @@ namespace System.Threading.Tasks
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -3029,7 +3029,7 @@ namespace System.Threading.Tasks
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction,
CancellationToken cancellationToken)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -3068,7 +3068,7 @@ namespace System.Threading.Tasks
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction,
TaskContinuationOptions continuationOptions)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -3117,7 +3117,7 @@ namespace System.Threading.Tasks
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
- if (continuationAction == null) throw new ArgumentNullException("continuationAction");
+ if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -3129,9 +3129,9 @@ namespace System.Threading.Tasks
internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks)
{
if (tasks == null)
- throw new ArgumentNullException("tasks");
+ throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), "tasks");
+ throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), nameof(tasks));
Contract.EndContractBlock();
Task[] tasksCopy = new Task[tasks.Length];
@@ -3140,7 +3140,7 @@ namespace System.Threading.Tasks
tasksCopy[i] = tasks[i];
if (tasksCopy[i] == null)
- throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
+ throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks));
}
return tasksCopy;
@@ -3149,9 +3149,9 @@ namespace System.Threading.Tasks
internal static Task<TResult>[] CheckMultiContinuationTasksAndCopy<TResult>(Task<TResult>[] tasks)
{
if (tasks == null)
- throw new ArgumentNullException("tasks");
+ throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), "tasks");
+ throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), nameof(tasks));
Contract.EndContractBlock();
Task<TResult>[] tasksCopy = new Task<TResult>[tasks.Length];
@@ -3160,7 +3160,7 @@ namespace System.Threading.Tasks
tasksCopy[i] = tasks[i];
if (tasksCopy[i] == null)
- throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
+ throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks));
}
return tasksCopy;
@@ -3179,7 +3179,7 @@ namespace System.Threading.Tasks
const TaskContinuationOptions illegalMask = TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning;
if ((continuationOptions & illegalMask) == illegalMask)
{
- throw new ArgumentOutOfRangeException("continuationOptions", Environment.GetResourceString("Task_ContinueWith_ESandLR"));
+ throw new ArgumentOutOfRangeException(nameof(continuationOptions), Environment.GetResourceString("Task_ContinueWith_ESandLR"));
}
// Check that no nonsensical options are specified.
@@ -3193,12 +3193,12 @@ namespace System.Threading.Tasks
NotOnAny |
TaskContinuationOptions.ExecuteSynchronously)) != 0)
{
- throw new ArgumentOutOfRangeException("continuationOptions");
+ throw new ArgumentOutOfRangeException(nameof(continuationOptions));
}
// Check that no "fire" options are specified.
if ((continuationOptions & NotOnAny) != 0)
- throw new ArgumentOutOfRangeException("continuationOptions", Environment.GetResourceString("Task_MultiTaskContinuation_FireOptions"));
+ throw new ArgumentOutOfRangeException(nameof(continuationOptions), Environment.GetResourceString("Task_MultiTaskContinuation_FireOptions"));
Contract.EndContractBlock();
}
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
index f82492499c..fad3fc06c5 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
@@ -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’s 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;
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs
index 02b130c297..90743aeec5 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs
@@ -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
diff --git a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs
index dd4cbc9a66..5c6ca9bb76 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs
@@ -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());
diff --git a/src/mscorlib/src/System/Threading/Tasks/future.cs b/src/mscorlib/src/System/Threading/Tasks/future.cs
index 39e6ca1d45..0c3fec89b7 100644
--- a/src/mscorlib/src/System/Threading/Tasks/future.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/future.cs
@@ -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
@@ -447,7 +446,7 @@ namespace System.Threading.Tasks
{
get
{
- Delegate d = (Delegate)m_action;
+ Delegate d = m_action;
return d != null ? d.Method.ToString() : "{null}";
}
}
@@ -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
diff --git a/src/mscorlib/src/System/Threading/Thread.cs b/src/mscorlib/src/System/Threading/Thread.cs
index e62cfae9fe..8294c20c4d 100644
--- a/src/mscorlib/src/System/Threading/Thread.cs
+++ b/src/mscorlib/src/System/Threading/Thread.cs
@@ -12,16 +12,13 @@
**
=============================================================================*/
+using Internal.Runtime.Augments;
+
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;
@@ -31,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;
@@ -53,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;
@@ -71,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;
@@ -90,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)
@@ -121,25 +106,20 @@ namespace System.Threading {
// deliberately not [serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Thread))]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class Thread : CriticalFinalizerObject, _Thread
+ [System.Runtime.InteropServices.ComVisible(true)]
+ public sealed class Thread : RuntimeThread, _Thread
{
/*=========================================================================
** Data accessed from managed code that needs to be defined in
** 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;
@@ -212,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
@@ -224,41 +201,37 @@ namespace System.Threading {
**
** Exceptions: ArgumentNullException if start == null.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public Thread(ThreadStart start) {
if (start == null) {
- throw new ArgumentNullException("start");
+ throw new ArgumentNullException(nameof(start));
}
Contract.EndContractBlock();
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("start");
+ throw new ArgumentNullException(nameof(start));
}
if (0 > maxStackSize)
- throw new ArgumentOutOfRangeException("maxStackSize",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(maxStackSize),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Thread(ParameterizedThreadStart start) {
if (start == null) {
- throw new ArgumentNullException("start");
+ throw new ArgumentNullException(nameof(start));
}
Contract.EndContractBlock();
SetStartHelper((Delegate)start, 0);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Thread(ParameterizedThreadStart start, int maxStackSize) {
if (start == null) {
- throw new ArgumentNullException("start");
+ throw new ArgumentNullException(nameof(start));
}
if (0 > maxStackSize)
- throw new ArgumentOutOfRangeException("maxStackSize",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(maxStackSize),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
@@ -269,11 +242,10 @@ namespace System.Threading {
return m_ManagedThreadId;
}
- extern public int ManagedThreadId
+ extern public new int ManagedThreadId
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical] // auto-generated
get;
}
@@ -299,17 +271,15 @@ 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 void Start()
+ public new void Start()
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Start(ref stackMark);
}
- [HostProtection(Synchronization=true,ExternalThreading=true)]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public void Start(object parameter)
+ public new void Start(object parameter)
{
//In the case of a null delegate (second call to start on same thread)
// StartInternal method will take care of the error reporting
@@ -325,7 +295,6 @@ namespace System.Threading {
Start(ref stackMark);
}
- [System.Security.SecuritySafeCritical]
private void Start(ref StackCrawlMark stackMark)
{
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
@@ -346,16 +315,11 @@ namespace System.Threading {
ExecutionContext.CaptureOptions.IgnoreSyncCtx);
t.SetExecutionContextHelper(ec);
}
-#if FEATURE_IMPERSONATION
- IPrincipal principal = (IPrincipal)CallContext.Principal;
-#else
+
IPrincipal principal = null;
-#endif
StartInternal(principal, ref stackMark);
}
-
-#if FEATURE_CORECLR
internal ExecutionContext ExecutionContext
{
get { return m_ExecutionContext; }
@@ -366,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 )
@@ -456,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()
{
@@ -478,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();
@@ -497,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
@@ -535,152 +390,14 @@ 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 void Interrupt() { InterruptInternal(); }
-
- // Internal helper (since we can't place security demands on
- // ecalls/fcalls).
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void InterruptInternal();
-#endif
-
- /*=========================================================================
- ** Returns the priority of the thread.
- **
- ** Exceptions: ThreadStateException if the thread is dead.
- =========================================================================*/
-
- public ThreadPriority Priority {
- [System.Security.SecuritySafeCritical] // auto-generated
- get { return (ThreadPriority)GetPriorityNative(); }
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(SelfAffectingThreading=true)]
- set { SetPriorityNative((int)value); }
- }
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern int GetPriorityNative();
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void SetPriorityNative(int priority);
-
- /*=========================================================================
- ** Returns true if the thread has been started and is not dead.
- =========================================================================*/
- public extern bool IsAlive {
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImpl(MethodImplOptions.InternalCall)]
- get;
- }
-
- /*=========================================================================
- ** Returns true if the thread is a threadpool thread.
- =========================================================================*/
- public extern bool IsThreadPoolThread {
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImpl(MethodImplOptions.InternalCall)]
- get;
- }
-
- /*=========================================================================
- ** 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.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern bool JoinInternal(int millisecondsTimeout);
-
- [System.Security.SecuritySafeCritical]
- [HostProtection(Synchronization=true, ExternalThreading=true)]
- public void Join()
- {
- JoinInternal(Timeout.Infinite);
- }
-
- [System.Security.SecuritySafeCritical]
- [HostProtection(Synchronization=true, ExternalThreading=true)]
- public bool Join(int millisecondsTimeout)
- {
- return JoinInternal(millisecondsTimeout);
- }
-
- [HostProtection(Synchronization=true, ExternalThreading=true)]
public bool Join(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
return Join((int)tm);
}
@@ -693,12 +410,10 @@ 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 void Sleep(int millisecondsTimeout)
+ public static new void Sleep(int millisecondsTimeout)
{
SleepInternal(millisecondsTimeout);
// Ensure we don't return to app code when the pause is underway
@@ -710,7 +425,7 @@ namespace System.Threading {
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Sleep((int)tm);
}
@@ -719,69 +434,41 @@ 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 void SpinWait(int iterations)
+ 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 bool Yield()
+ public static new bool Yield()
{
return YieldInternal();
}
- public static Thread CurrentThread {
- [System.Security.SecuritySafeCritical] // auto-generated
+ public static new Thread CurrentThread {
[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)
@@ -794,7 +481,6 @@ namespace System.Threading {
}
}
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern ulong GetProcessDefaultStackSize();
@@ -803,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()
{
@@ -818,52 +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_COMINTEROP
- [System.Security.SecurityCritical] // auto-generated
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern void 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 bool IsBackground {
- [System.Security.SecuritySafeCritical] // auto-generated
- get { return IsBackgroundNative(); }
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(SelfAffectingThreading=true)]
- set { SetBackgroundNative(value); }
- }
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern bool IsBackgroundNative();
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void SetBackgroundNative(bool isBackground);
-
-
- /*=========================================================================
- ** Return the thread state as a consistent set of bits. This is more
- ** general then IsAlive or IsBackground.
- =========================================================================*/
- public ThreadState ThreadState {
- [System.Security.SecuritySafeCritical] // auto-generated
- get { return (ThreadState)GetThreadStateNative(); }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern int GetThreadStateNative();
-
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
/*=========================================================================
** An unstarted thread can be marked to indicate that it will host a
@@ -875,35 +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);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
- public ApartmentState GetApartmentState()
- {
- return (ApartmentState)GetApartmentStateNative();
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization=true, SelfAffectingThreading=true)]
- public bool TrySetApartmentState(ApartmentState state)
- {
- return SetApartmentStateHelper(state, false);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization=true, SelfAffectingThreading=true)]
public void SetApartmentState(ApartmentState state)
{
bool result = SetApartmentStateHelper(state, true);
@@ -911,31 +535,6 @@ namespace System.Threading {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ApartmentStateSwitchFailed"));
}
- [System.Security.SecurityCritical] // auto-generated
- private bool SetApartmentStateHelper(ApartmentState state, bool fireMDAOnMismatch)
- {
- ApartmentState retState = (ApartmentState)SetApartmentStateNative((int)state, fireMDAOnMismatch);
-
- // Special case where we pass in Unknown and get back MTA.
- // Once we CoUninitialize the thread, the OS will still
- // report the thread as implicitly in the MTA if any
- // other thread in the process is CoInitialized.
- if ((state == System.Threading.ApartmentState.Unknown) && (retState == System.Threading.ApartmentState.MTA))
- return true;
-
- if (retState != state)
- return false;
-
- return true;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern int GetApartmentStateNative();
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern int SetApartmentStateNative(int state, bool fireMDAOnMismatch);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void StartupSetApartmentStateInternal();
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
@@ -944,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();
@@ -955,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);
@@ -966,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);
@@ -977,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);
@@ -986,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;
@@ -1003,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;
@@ -1044,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
@@ -1075,11 +667,9 @@ namespace System.Threading {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(ExternalThreading=true)]
set {
if (value == null) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -1119,7 +709,6 @@ namespace System.Threading {
}
#if FEATURE_LEAK_CULTURE_INFO
- [System.Security.SecuritySafeCritical] // auto-generated
#endif
internal CultureInfo GetCurrentUICultureNoAppX() {
@@ -1152,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
@@ -1184,13 +772,11 @@ namespace System.Threading {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
#if FEATURE_LEAK_CULTURE_INFO
- [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
#endif
set {
if (null==value) {
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -1225,7 +811,6 @@ namespace System.Threading {
}
#if FEATURE_LEAK_CULTURE_INFO
- [System.Security.SecuritySafeCritical] // auto-generated
#endif
private CultureInfo GetCurrentCultureNoAppX() {
@@ -1255,114 +840,21 @@ namespace System.Threading {
#endif
}
-#if! FEATURE_LEAK_CULTURE_INFO
- [System.Security.SecurityCritical] // auto-generated
+#if !FEATURE_LEAK_CULTURE_INFO
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nativeInitCultureAccessors();
#endif
- /*=============================================================*/
-
- /*======================================================================
- ** Current thread context is stored in a slot in the thread local store
- ** CurrentContext gets the Context from the slot.
- ======================================================================*/
-#if FEATURE_REMOTING
- public static Context CurrentContext
- {
- [System.Security.SecurityCritical] // auto-generated_required
- get
- {
- return CurrentThread.GetCurrentContextInternal();
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal Context GetCurrentContextInternal()
- {
- if (m_Context == null)
- {
- m_Context = Context.DefaultContext;
- }
- return m_Context;
- }
-#endif
-
-
-#if FEATURE_IMPERSONATION
- // Get and set thread's current principal (for role based security).
- public static IPrincipal CurrentPrincipal
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- get
- {
- lock (CurrentThread)
- {
- IPrincipal principal = (IPrincipal)
- CallContext.Principal;
- if (principal == null)
- {
- principal = GetDomain().GetThreadPrincipal();
- CallContext.Principal = principal;
- }
- return principal;
- }
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)]
- set
- {
- CallContext.Principal = value;
- }
- }
-
- // Private routine called from unmanaged code to set an initial
- // principal for a newly created thread.
- [System.Security.SecurityCritical] // auto-generated
- private void SetPrincipalInternal(IPrincipal principal)
- {
- GetMutableExecutionContext().LogicalCallContext.SecurityData.Principal = principal;
- }
-#endif // FEATURE_IMPERSONATION
-
-#if FEATURE_REMOTING
-
- // This returns the exposed context for a given context ID.
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern Context GetContextInternal(IntPtr id);
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern Object InternalCrossContextCallback(Context ctx, IntPtr ctxID, Int32 appDomainID, InternalCrossContextDelegate ftnToCall, Object[] args);
-
- [System.Security.SecurityCritical] // auto-generated
- internal Object InternalCrossContextCallback(Context ctx, InternalCrossContextDelegate ftnToCall, Object[] args)
- {
- return InternalCrossContextCallback(ctx, ctx.InternalContextID, 0, ftnToCall, args);
- }
-
- // CompleteCrossContextCallback is called by the EE after transitioning to the requested context
- private static Object CompleteCrossContextCallback(InternalCrossContextDelegate ftnToCall, Object[] args)
- {
- return ftnToCall(args);
- }
-#endif // FEATURE_REMOTING
-
/*======================================================================
** 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);
@@ -1373,9 +865,6 @@ namespace System.Threading {
if (ad == null)
ad = GetDomainInternal();
-#if FEATURE_REMOTING
- Contract.Assert(CurrentThread.m_Context == null || CurrentThread.m_Context.AppDomain == ad, "AppDomains on the managed & unmanaged threads should match");
-#endif
return ad;
}
@@ -1391,13 +880,10 @@ namespace System.Threading {
// Retrieves the name of the thread.
//
- public String Name {
+ public new String Name {
get {
return m_Name;
-
}
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(ExternalThreading=true)]
set {
lock(this) {
if (m_Name != null)
@@ -1409,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
@@ -1428,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
@@ -1679,7 +1126,6 @@ namespace System.Threading {
address = value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void MemoryBarrier();
@@ -1696,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();
diff --git a/src/mscorlib/src/System/Threading/ThreadAbortException.cs b/src/mscorlib/src/System/Threading/ThreadAbortException.cs
index 11c8744c72..09ad4e1bd6 100644
--- a/src/mscorlib/src/System/Threading/ThreadAbortException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadAbortException.cs
@@ -39,7 +39,6 @@ namespace System.Threading
public Object ExceptionState
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {return Thread.CurrentThread.AbortReason;}
}
}
diff --git a/src/mscorlib/src/System/Threading/ThreadLocal.cs b/src/mscorlib/src/System/Threading/ThreadLocal.cs
index b4cf12ab7c..2b996cb34d 100644
--- a/src/mscorlib/src/System/Threading/ThreadLocal.cs
+++ b/src/mscorlib/src/System/Threading/ThreadLocal.cs
@@ -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
{
@@ -107,7 +106,7 @@ namespace System.Threading
public ThreadLocal(Func<T> valueFactory)
{
if (valueFactory == null)
- throw new ArgumentNullException("valueFactory");
+ throw new ArgumentNullException(nameof(valueFactory));
Initialize(valueFactory, false);
}
@@ -127,7 +126,7 @@ namespace System.Threading
public ThreadLocal(Func<T> valueFactory, bool trackAllValues)
{
if (valueFactory == null)
- throw new ArgumentNullException("valueFactory");
+ throw new ArgumentNullException(nameof(valueFactory));
Initialize(valueFactory, trackAllValues);
}
@@ -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;
}
}
diff --git a/src/mscorlib/src/System/Threading/ThreadPool.cs b/src/mscorlib/src/System/Threading/ThreadPool.cs
index 09fe93c682..451b15d22f 100644
--- a/src/mscorlib/src/System/Threading/ThreadPool.cs
+++ b/src/mscorlib/src/System/Threading/ThreadPool.cs
@@ -29,15 +29,14 @@
namespace System.Threading
{
using System.Security;
- using System.Runtime.Remoting;
using System.Security.Permissions;
using System;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
@@ -46,19 +45,17 @@ namespace System.Threading
{
//Per-appDomain quantum (in ms) for which the thread keeps processing
//requests in the current domain.
- public static uint tpQuantum = 30U;
+ public const uint TP_QUANTUM = 30U;
- public static int processorCount = Environment.ProcessorCount;
+ public static readonly int processorCount = Environment.ProcessorCount;
- public static bool tpHosted = ThreadPool.IsThreadPoolHosted();
+ public static readonly bool tpHosted = ThreadPool.IsThreadPoolHosted();
public static volatile bool vmTpInitialized;
public static bool enableWorkerTracking;
- [SecurityCritical]
- public static ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
+ public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
- [System.Security.SecuritySafeCritical] // static constructors should be safe to call
static ThreadPoolGlobals()
{
}
@@ -173,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
@@ -235,7 +232,7 @@ namespace System.Threading
IThreadPoolWorkItem unused;
if (LocalPop(out unused))
{
- Contract.Assert(unused == obj);
+ Debug.Assert(unused == obj);
return true;
}
return false;
@@ -434,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);
@@ -463,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];
}
@@ -486,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);
@@ -498,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;
}
@@ -546,7 +543,7 @@ namespace System.Threading
internal volatile QueueSegment queueTail;
internal bool loggingEnabled;
- internal static SparseArray<WorkStealingQueue> allThreadQueues = new SparseArray<WorkStealingQueue>(16);
+ internal static readonly SparseArray<WorkStealingQueue> allThreadQueues = new SparseArray<WorkStealingQueue>(16);
private volatile int numOutstandingThreadRequests = 0;
@@ -556,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)
@@ -564,7 +560,6 @@ namespace System.Threading
return ThreadPoolWorkQueueThreadLocals.threadLocals;
}
- [SecurityCritical]
internal void EnsureThreadRequested()
{
//
@@ -585,7 +580,6 @@ namespace System.Threading
}
}
- [SecurityCritical]
internal void MarkThreadRequestSatisfied()
{
//
@@ -606,7 +600,6 @@ namespace System.Threading
}
}
- [SecurityCritical]
public void Enqueue(IThreadPoolWorkItem callback, bool forceGlobal)
{
ThreadPoolWorkQueueThreadLocals tl = null;
@@ -639,7 +632,6 @@ namespace System.Threading
EnsureThreadRequested();
}
- [SecurityCritical]
internal bool LocalFindAndPop(IThreadPoolWorkItem callback)
{
ThreadPoolWorkQueueThreadLocals tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
@@ -649,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;
@@ -657,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)
{
@@ -666,7 +657,7 @@ namespace System.Threading
{
if (tail.TryDequeue(out callback))
{
- Contract.Assert(null != callback);
+ Debug.Assert(null != callback);
break;
}
@@ -696,7 +687,7 @@ namespace System.Threading
otherQueue != wsq &&
otherQueue.TrySteal(out callback, ref missedSteal))
{
- Contract.Assert(null != callback);
+ Debug.Assert(null != callback);
break;
}
c--;
@@ -704,12 +695,11 @@ namespace System.Threading
}
}
- [SecurityCritical]
static internal bool Dispatch()
{
var workQueue = ThreadPoolGlobals.workQueue;
//
- // The clock is ticking! We have ThreadPoolGlobals.tpQuantum milliseconds to get some work done, and then
+ // The clock is ticking! We have ThreadPoolGlobals.TP_QUANTUM milliseconds to get some work done, and then
// we need to return to the VM.
//
int quantumStartTime = Environment.TickCount;
@@ -743,7 +733,7 @@ namespace System.Threading
//
// Loop until our quantum expires.
//
- while ((Environment.TickCount - quantumStartTime) < ThreadPoolGlobals.tpQuantum)
+ while ((Environment.TickCount - quantumStartTime) < ThreadPoolGlobals.TP_QUANTUM)
{
//
// Dequeue and EnsureThreadRequested must be protected from ThreadAbortException.
@@ -855,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;
}
}
@@ -864,7 +854,6 @@ namespace System.Threading
internal sealed class ThreadPoolWorkQueueThreadLocals
{
[ThreadStatic]
- [SecurityCritical]
public static ThreadPoolWorkQueueThreadLocals threadLocals;
public readonly ThreadPoolWorkQueue workQueue;
@@ -878,7 +867,6 @@ namespace System.Threading
ThreadPoolWorkQueue.allThreadQueues.Add(workStealingQueue);
}
- [SecurityCritical]
private void CleanUp()
{
if (null != workStealingQueue)
@@ -895,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
@@ -910,7 +898,6 @@ namespace System.Threading
}
}
- [SecuritySafeCritical]
~ThreadPoolWorkQueueThreadLocals()
{
// Since the purpose of calling CleanUp is to transfer any pending workitems into the global
@@ -927,7 +914,6 @@ namespace System.Threading
{
private static IntPtr InvalidHandle
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return Win32Native.INVALID_HANDLE_VALUE;
@@ -938,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;
@@ -956,7 +939,6 @@ namespace System.Threading
registeredWaitHandle = handle;
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal void SetWaitObject(WaitHandle waitObject)
{
@@ -975,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
@@ -1033,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
@@ -1084,21 +1064,15 @@ 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);
}
[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_REMOTING
public sealed class RegisteredWaitHandle : MarshalByRefObject {
-#else // FEATURE_REMOTING
- public sealed class RegisteredWaitHandle {
-#endif // FEATURE_REMOTING
private RegisteredWaitHandleSafe internalRegisteredWait;
internal RegisteredWaitHandle()
@@ -1111,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(
@@ -1143,7 +1115,6 @@ namespace System.Threading
//
internal static class _ThreadPoolWaitCallback
{
- [System.Security.SecurityCritical]
static internal bool PerformWaitCallback()
{
return ThreadPoolWorkQueue.Dispatch();
@@ -1161,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;
@@ -1181,7 +1149,7 @@ namespace System.Threading
~QueueUserWorkItemCallback()
{
- Contract.Assert(
+ Debug.Assert(
executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
"A QueueUserWorkItemCallback was never called!");
}
@@ -1189,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;
@@ -1203,7 +1170,6 @@ namespace System.Threading
context = ec;
}
- [SecurityCritical]
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
@@ -1222,7 +1188,6 @@ namespace System.Threading
}
}
- [SecurityCritical]
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
{
#if DEBUG
@@ -1232,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;
@@ -1258,7 +1220,7 @@ namespace System.Threading
~QueueUserWorkItemCallbackDefaultContext()
{
- Contract.Assert(
+ Debug.Assert(
executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
"A QueueUserWorkItemCallbackDefaultContext was never called!");
}
@@ -1266,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
@@ -1288,7 +1248,6 @@ namespace System.Threading
ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, ccb, this, true);
}
- [SecurityCritical]
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
{
#if DEBUG
@@ -1298,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);
}
@@ -1314,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;
@@ -1340,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);
@@ -1359,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)
{
@@ -1384,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
@@ -1392,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
@@ -1455,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
@@ -1471,7 +1398,6 @@ namespace System.Threading
}
- [System.Security.SecurityCritical] // auto-generated
private static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
WaitOrTimerCallback callBack,
@@ -1482,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)
@@ -1508,13 +1428,12 @@ namespace System.Threading
}
else
{
- throw new ArgumentNullException("WaitOrTimerCallback");
+ throw new ArgumentNullException(nameof(WaitOrTimerCallback));
}
return registeredWaitHandle;
}
- [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,
@@ -1525,13 +1444,12 @@ namespace System.Threading
)
{
if (millisecondsTimeOutInterval < -1)
- throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
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,
@@ -1542,13 +1460,12 @@ namespace System.Threading
)
{
if (millisecondsTimeOutInterval < -1)
- throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
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,
@@ -1559,13 +1476,12 @@ namespace System.Threading
)
{
if (millisecondsTimeOutInterval < -1)
- throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
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,
@@ -1576,13 +1492,12 @@ namespace System.Threading
)
{
if (millisecondsTimeOutInterval < -1)
- throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
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,
@@ -1594,14 +1509,13 @@ namespace System.Threading
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_LessEqualToIntegerMaxVal"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_LessEqualToIntegerMaxVal"));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
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,
@@ -1613,14 +1527,13 @@ namespace System.Threading
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_LessEqualToIntegerMaxVal"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_LessEqualToIntegerMaxVal"));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
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
@@ -1631,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
@@ -1641,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
@@ -1655,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;
@@ -1690,15 +1600,14 @@ namespace System.Threading
}
else
{
- throw new ArgumentNullException("WaitCallback");
+ throw new ArgumentNullException(nameof(WaitCallback));
}
return success;
}
- [SecurityCritical]
internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal)
{
- Contract.Assert(null != workItem);
+ Debug.Assert(null != workItem);
EnsureVMInitialized();
//
@@ -1712,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);
@@ -1766,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);
@@ -1800,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)
@@ -1846,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)
@@ -1882,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,
@@ -1907,30 +1793,19 @@ namespace System.Threading
bool compressStack
);
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
+
[Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.", false)]
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static bool BindHandle(
IntPtr osHandle
)
{
return BindIOCompletionCallbackNative(osHandle);
}
-#endif
- #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)
- throw new ArgumentNullException("osHandle");
+ throw new ArgumentNullException(nameof(osHandle));
bool ret = false;
bool mustReleaseSafeHandle = false;
@@ -1946,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);
diff --git a/src/mscorlib/src/System/Threading/Timer.cs b/src/mscorlib/src/System/Threading/Timer.cs
index cb08c6e033..5bfefccad2 100644
--- a/src/mscorlib/src/System/Threading/Timer.cs
+++ b/src/mscorlib/src/System/Threading/Timer.cs
@@ -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,19 +756,13 @@ namespace System.Threading
}
- [HostProtection(Synchronization=true, ExternalThreading=true)]
[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_REMOTING
public sealed class Timer : MarshalByRefObject, IDisposable
-#else // FEATURE_REMOTING
- public sealed class Timer : IDisposable
-#endif // FEATURE_REMOTING
{
private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe;
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,
@@ -792,16 +770,15 @@ namespace System.Threading
int period)
{
if (dueTime < -1)
- throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1 )
- throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
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,
@@ -810,22 +787,21 @@ namespace System.Threading
{
long dueTm = (long)dueTime.TotalMilliseconds;
if (dueTm < -1)
- throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(dueTm),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTm > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(dueTm),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
- throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (periodTm > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm,ref stackMark);
}
[CLSCompliant(false)]
- [SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
@@ -836,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,
@@ -844,19 +819,18 @@ namespace System.Threading
long period)
{
if (dueTime < -1)
- throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
- throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTime > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
if (period > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
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)
{
@@ -869,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,
@@ -877,19 +850,17 @@ namespace System.Threading
ref StackCrawlMark stackMark)
{
if (callback == null)
- throw new ArgumentNullException("TimerCallback");
+ throw new ArgumentNullException(nameof(TimerCallback));
Contract.EndContractBlock();
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();
@@ -898,9 +869,9 @@ namespace System.Threading
public bool Change(int dueTime, int period)
{
if (dueTime < -1 )
- throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
- throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
@@ -920,13 +891,13 @@ namespace System.Threading
public bool Change(long dueTime, long period)
{
if (dueTime < -1 )
- throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
- throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTime > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
if (period > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
@@ -935,7 +906,7 @@ namespace System.Threading
public bool Dispose(WaitHandle notifyObject)
{
if (notifyObject==null)
- throw new ArgumentNullException("notifyObject");
+ throw new ArgumentNullException(nameof(notifyObject));
Contract.EndContractBlock();
return m_timer.Close(notifyObject);
diff --git a/src/mscorlib/src/System/Threading/Volatile.cs b/src/mscorlib/src/System/Threading/Volatile.cs
index af687fbae1..3894b435fa 100644
--- a/src/mscorlib/src/System/Threading/Volatile.cs
+++ b/src/mscorlib/src/System/Threading/Volatile.cs
@@ -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
{
diff --git a/src/mscorlib/src/System/Threading/WaitHandle.cs b/src/mscorlib/src/System/Threading/WaitHandle.cs
index 9980c822a6..7638c8b35b 100644
--- a/src/mscorlib/src/System/Threading/WaitHandle.cs
+++ b/src/mscorlib/src/System/Threading/WaitHandle.cs
@@ -27,12 +27,8 @@ namespace System.Threading
using System.Diagnostics.CodeAnalysis;
using Win32Native = Microsoft.Win32.Win32Native;
-[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_REMOTING
+ [System.Runtime.InteropServices.ComVisible(true)]
public abstract class WaitHandle : MarshalByRefObject, IDisposable {
-#else // FEATURE_REMOTING
- public abstract class WaitHandle : IDisposable {
-#endif // FEATURE_REMOTING
public const int WaitTimeout = 0x102;
private const int MAX_WAITHANDLES = 64;
@@ -41,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;
@@ -70,7 +64,6 @@ namespace System.Threading
Init();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private void Init()
{
safeWaitHandle = null;
@@ -82,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)
@@ -113,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
{
@@ -129,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
{
@@ -168,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;
@@ -179,7 +156,7 @@ namespace System.Threading
{
if (millisecondsTimeout < -1)
{
- throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
}
Contract.EndContractBlock();
return WaitOne((long)millisecondsTimeout,exitContext);
@@ -190,7 +167,7 @@ namespace System.Threading
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long) Int32.MaxValue < tm)
{
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
}
return WaitOne(tm,exitContext);
}
@@ -211,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)
@@ -238,7 +213,6 @@ namespace System.Threading
return (ret != WaitTimeout);
}
- [System.Security.SecurityCritical]
internal bool WaitOneWithoutFAS()
{
// version of waitone without fast application switch (FAS) support
@@ -258,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);
@@ -271,17 +244,15 @@ 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)
{
- throw new ArgumentNullException("waitHandles", Environment.GetResourceString("ArgumentNull_Waithandles"));
+ throw new ArgumentNullException(nameof(waitHandles), Environment.GetResourceString("ArgumentNull_Waithandles"));
}
if(waitHandles.Length == 0)
{
@@ -294,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("waitHandles", Environment.GetResourceString("Argument_EmptyWaithandleArray"));
-#endif
}
if (waitHandles.Length > MAX_WAITHANDLES)
{
@@ -306,7 +273,7 @@ namespace System.Threading
}
if (-1 > millisecondsTimeout)
{
- throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
}
Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
@@ -317,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
@@ -354,7 +316,7 @@ namespace System.Threading
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long) Int32.MaxValue < tm)
{
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
}
return WaitAll(waitHandles,(int)tm, exitContext);
}
@@ -388,13 +350,12 @@ 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)
{
if (waitHandles==null)
{
- throw new ArgumentNullException("waitHandles", Environment.GetResourceString("ArgumentNull_Waithandles"));
+ throw new ArgumentNullException(nameof(waitHandles), Environment.GetResourceString("ArgumentNull_Waithandles"));
}
if(waitHandles.Length == 0)
{
@@ -406,7 +367,7 @@ namespace System.Threading
}
if (-1 > millisecondsTimeout)
{
- throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
}
Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
@@ -417,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
@@ -459,7 +415,7 @@ namespace System.Threading
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long) Int32.MaxValue < tm)
{
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
}
return WaitAny(waitHandles,(int)tm, exitContext);
}
@@ -491,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);
@@ -519,13 +474,12 @@ namespace System.Threading
long tm = (long)timeout.TotalMilliseconds;
if (-1 > tm || (long) Int32.MaxValue < tm)
{
- throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
}
return SignalAndWait(toSignal,toWaitOn,(int)tm,exitContext);
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")]
public static bool SignalAndWait(
WaitHandle toSignal,
@@ -538,15 +492,15 @@ namespace System.Threading
#else
if(null == toSignal)
{
- throw new ArgumentNullException("toSignal");
+ throw new ArgumentNullException(nameof(toSignal));
}
if(null == toWaitOn)
{
- throw new ArgumentNullException("toWaitOn");
+ throw new ArgumentNullException(nameof(toWaitOn));
}
if (-1 > millisecondsTimeout)
{
- throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
}
Contract.EndContractBlock();
@@ -554,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();
@@ -599,7 +545,6 @@ namespace System.Threading
GC.SuppressFinalize(this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected virtual void Dispose(bool explicitDisposing)
{
if (safeWaitHandle != null)
diff --git a/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs b/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs
index f873057992..68445a78d9 100644
--- a/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs
+++ b/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs
@@ -12,11 +12,7 @@ namespace System.Threading
[Serializable]
[ComVisibleAttribute(false)]
-#if FEATURE_CORECLR
- public class WaitHandleCannotBeOpenedException : Exception {
-#else
public class WaitHandleCannotBeOpenedException : ApplicationException {
-#endif // FEATURE_CORECLR
public WaitHandleCannotBeOpenedException() : base(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException"))
{
SetErrorCode(__HResults.COR_E_WAITHANDLECANNOTBEOPENED);
diff --git a/src/mscorlib/src/System/Threading/WaitHandleExtensions.cs b/src/mscorlib/src/System/Threading/WaitHandleExtensions.cs
deleted file mode 100644
index 76c3feb649..0000000000
--- a/src/mscorlib/src/System/Threading/WaitHandleExtensions.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-//
-
-using Microsoft.Win32.SafeHandles;
-using System.Security;
-
-namespace System.Threading
-{
- public static class WaitHandleExtensions
- {
- /// <summary>
- /// Gets the native operating system handle.
- /// </summary>
- /// <param name="waitHandle">The <see cref="System.Threading.WaitHandle"/> to operate on.</param>
- /// <returns>A <see cref="System.Runtime.InteropServices.SafeHandle"/> representing the native operating system handle.</returns>
- [SecurityCritical]
- public static SafeWaitHandle GetSafeWaitHandle(this WaitHandle waitHandle)
- {
- if (waitHandle == null)
- {
- throw new ArgumentNullException("waitHandle");
- }
-
- return waitHandle.SafeWaitHandle;
- }
-
- /// <summary>
- /// Sets the native operating system handle
- /// </summary>
- /// <param name="waitHandle">The <see cref="System.Threading.WaitHandle"/> to operate on.</param>
- /// <param name="value">A <see cref="System.Runtime.InteropServices.SafeHandle"/> representing the native operating system handle.</param>
- [SecurityCritical]
- public static void SetSafeWaitHandle(this WaitHandle waitHandle, SafeWaitHandle value)
- {
- if (waitHandle == null)
- {
- throw new ArgumentNullException("waitHandle");
- }
-
- waitHandle.SafeWaitHandle = value;
- }
- }
-}
diff --git a/src/mscorlib/src/System/ThrowHelper.cs b/src/mscorlib/src/System/ThrowHelper.cs
index 3105d56f7c..a534dec818 100644
--- a/src/mscorlib/src/System/ThrowHelper.cs
+++ b/src/mscorlib/src/System/ThrowHelper.cs
@@ -10,7 +10,7 @@ namespace System {
// The old way to throw an exception generates quite a lot IL code and assembly code.
// Following is an example:
// C# source
- // throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
+ // throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
// IL code:
// IL_0003: ldstr "key"
// IL_0008: ldstr "ArgumentNull_Key"
@@ -39,112 +39,206 @@ namespace System {
using Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Pure]
internal static class ThrowHelper {
+#if FEATURE_SPAN_OF_T
+ internal static void ThrowArrayTypeMismatchException() {
+ throw new ArrayTypeMismatchException();
+ }
+
+ internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType) {
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeWithPointersNotSupported", targetType));
+ }
+
+ internal static void ThrowIndexOutOfRangeException() {
+ throw new IndexOutOfRangeException();
+ }
+
+ 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() {
- throw new ArgumentOutOfRangeException(GetArgumentName(ExceptionArgument.index),
- Environment.GetResourceString(GetResourceName(ExceptionResource.ArgumentOutOfRange_Index)));
+ throw GetArgumentOutOfRangeException(ExceptionArgument.index,
+ ExceptionResource.ArgumentOutOfRange_Index);
}
internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() {
- throw new ArgumentOutOfRangeException(
- GetArgumentName(ExceptionArgument.index),
- Environment.GetResourceString(GetResourceName(ExceptionResource.ArgumentOutOfRange_NeedNonNegNum)));
+ throw GetArgumentOutOfRangeException(ExceptionArgument.index,
+ ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ }
+
+ internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() {
+ throw GetArgumentOutOfRangeException(ExceptionArgument.length,
+ ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
+ }
+
+ internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() {
+ throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex,
+ ExceptionResource.ArgumentOutOfRange_Index);
+ }
+
+ internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() {
+ throw GetArgumentOutOfRangeException(ExceptionArgument.count,
+ ExceptionResource.ArgumentOutOfRange_Count);
}
internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType) {
- throw new ArgumentException(Environment.GetResourceString("Arg_WrongType", key, targetType), "key");
+ throw GetWrongKeyTypeArgumentException(key, targetType);
}
internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType) {
- throw new ArgumentException(Environment.GetResourceString("Arg_WrongType", value, targetType), "value");
+ throw GetWrongValueTypeArgumentException(value, targetType);
+ }
+
+ private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) {
+ return new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicateWithKey", key));
}
-#if FEATURE_CORECLR
internal static void ThrowAddingDuplicateWithKeyArgumentException(object key) {
- throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicateWithKey", key));
+ throw GetAddingDuplicateWithKeyArgumentException(key);
}
-#endif
internal static void ThrowKeyNotFoundException() {
throw new System.Collections.Generic.KeyNotFoundException();
}
internal static void ThrowArgumentException(ExceptionResource resource) {
- throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource)));
+ throw GetArgumentException(resource);
}
internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument) {
- throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource)), GetArgumentName(argument));
+ throw GetArgumentException(resource, argument);
}
internal static void ThrowArgumentNullException(ExceptionArgument argument) {
throw new ArgumentNullException(GetArgumentName(argument));
}
+ internal static void ThrowArgumentNullException(ExceptionResource resource) {
+ throw new ArgumentNullException(GetResourceString(resource));
+ }
+
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) {
throw new ArgumentOutOfRangeException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) {
- throw new ArgumentOutOfRangeException(GetArgumentName(argument),
- Environment.GetResourceString(GetResourceName(resource)));
+ throw GetArgumentOutOfRangeException(argument, resource);
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) {
- throw new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]",
- Environment.GetResourceString(GetResourceName(resource)));
+ throw GetArgumentOutOfRangeException(argument, paramNumber, resource);
}
internal static void ThrowInvalidOperationException(ExceptionResource resource) {
- throw new InvalidOperationException(Environment.GetResourceString(GetResourceName(resource)));
+ throw GetInvalidOperationException(resource);
}
internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) {
- throw new InvalidOperationException(Environment.GetResourceString(GetResourceName(resource)), e);
+ throw new InvalidOperationException(GetResourceString(resource), e);
}
internal static void ThrowSerializationException(ExceptionResource resource) {
- throw new SerializationException(Environment.GetResourceString(GetResourceName(resource)));
+ throw new SerializationException(GetResourceString(resource));
}
internal static void ThrowSecurityException(ExceptionResource resource) {
- throw new System.Security.SecurityException(Environment.GetResourceString(GetResourceName(resource)));
+ throw new System.Security.SecurityException(GetResourceString(resource));
}
internal static void ThrowRankException(ExceptionResource resource) {
- throw new RankException(Environment.GetResourceString(GetResourceName(resource)));
+ throw new RankException(GetResourceString(resource));
}
internal static void ThrowNotSupportedException(ExceptionResource resource) {
- throw new NotSupportedException(Environment.GetResourceString(GetResourceName(resource)));
+ throw new NotSupportedException(GetResourceString(resource));
}
internal static void ThrowUnauthorizedAccessException(ExceptionResource resource) {
- throw new UnauthorizedAccessException(Environment.GetResourceString(GetResourceName(resource)));
+ throw new UnauthorizedAccessException(GetResourceString(resource));
}
internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource) {
- throw new ObjectDisposedException(objectName, Environment.GetResourceString(GetResourceName(resource)));
+ throw new ObjectDisposedException(objectName, GetResourceString(resource));
}
- internal static void ThrowObjectDisposedException(ExceptionResource resource)
- {
- throw new ObjectDisposedException(null, Environment.GetResourceString(GetResourceName(resource)));
+ internal static void ThrowObjectDisposedException(ExceptionResource resource) {
+ throw new ObjectDisposedException(null, GetResourceString(resource));
}
- internal static void ThrowNotSupportedException()
- {
+ internal static void ThrowNotSupportedException() {
throw new NotSupportedException();
}
- internal static void ThrowAggregateException(List<Exception> exceptions)
- {
+ internal static void ThrowAggregateException(List<Exception> exceptions) {
throw new AggregateException(exceptions);
}
+ internal static void ThrowArgumentException_Argument_InvalidArrayType() {
+ throw GetArgumentException(ExceptionResource.Argument_InvalidArrayType);
+ }
+
+ internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted() {
+ throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted);
+ }
+
+ internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded() {
+ throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded);
+ }
+
+ internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() {
+ throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
+ }
+
+ internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() {
+ throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
+ }
+
+ private static ArgumentException GetArgumentException(ExceptionResource resource) {
+ return new ArgumentException(GetResourceString(resource));
+ }
+
+ private static InvalidOperationException GetInvalidOperationException(ExceptionResource resource) {
+ return new InvalidOperationException(GetResourceString(resource));
+ }
+
+ private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType) {
+ return new ArgumentException(Environment.GetResourceString("Arg_WrongType", key, targetType), nameof(key));
+ }
+
+ private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType) {
+ return new ArgumentException(Environment.GetResourceString("Arg_WrongType", value, targetType), nameof(value));
+ }
+
+ private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) {
+ return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource));
+ }
+
+ private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument) {
+ return new ArgumentException(GetResourceString(resource), GetArgumentName(argument));
+ }
+
+ private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) {
+ return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]", GetResourceString(resource));
+ }
+
// Allow nulls for reference types and Nullable<U>, but not for value types.
// Aggressively inline so the jit evaluates the if in place and either drops the call altogether
// Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException
@@ -155,26 +249,43 @@ namespace System {
ThrowHelper.ThrowArgumentNullException(argName);
}
- //
// This function will convert an ExceptionArgument enum value to the argument name string.
- //
- internal static string GetArgumentName(ExceptionArgument argument) {
- Contract.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
+ private static string GetArgumentName(ExceptionArgument argument) {
+ // This is indirected through a second NoInlining function it has a special meaning
+ // in System.Private.CoreLib of indicatating it takes a StackMark which cause
+ // the caller to also be not inlined; so we can't mark it directly.
+ // So is the effect of marking this function as non-inlining in a regular situation.
+ return GetArgumentNameInner(argument);
+ }
+
+ // This function will convert an ExceptionArgument enum value to the argument name string.
+ // Second function in chain so as to not propergate the non-inlining to outside caller
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static string GetArgumentNameInner(ExceptionArgument argument) {
+ Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
"The enum value is not defined, please check the ExceptionArgument Enum.");
return argument.ToString();
}
- //
// This function will convert an ExceptionResource enum value to the resource string.
- //
- internal static string GetResourceName(ExceptionResource resource) {
- Contract.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
+ private static string GetResourceString(ExceptionResource resource) {
+ // This is indirected through a second NoInlining function it has a special meaning
+ // in System.Private.CoreLib of indicatating it takes a StackMark which cause
+ // the caller to also be not inlined; so we can't mark it directly.
+ // So is the effect of marking this function as non-inlining in a regular situation.
+ return GetResourceStringInner(resource);
+ }
+
+ // This function will convert an ExceptionResource enum value to the resource string.
+ // Second function in chain so as to not propergate the non-inlining to outside caller
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static string GetResourceStringInner(ExceptionResource resource) {
+ Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
"The enum value is not defined, please check the ExceptionResource Enum.");
- return resource.ToString();
+ return Environment.GetResourceString(resource.ToString());
}
-
}
//
@@ -247,6 +358,11 @@ namespace System {
beginMethod,
continuationOptions,
continuationAction,
+ valueFactory,
+ addValueFactory,
+ updateValueFactory,
+ concurrencyLevel,
+ text,
}
@@ -341,6 +457,17 @@ namespace System {
TaskCompletionSourceT_TrySetException_NullException,
TaskCompletionSourceT_TrySetException_NoExceptions,
InvalidOperation_WrongAsyncResultOrEndCalledMultiple,
+ ConcurrentDictionary_ConcurrencyLevelMustBePositive,
+ ConcurrentDictionary_CapacityMustNotBeNegative,
+ ConcurrentDictionary_TypeOfValueIncorrect,
+ ConcurrentDictionary_TypeOfKeyIncorrect,
+ ConcurrentDictionary_SourceContainsDuplicateKeys,
+ ConcurrentDictionary_KeyAlreadyExisted,
+ ConcurrentDictionary_ItemKeyIsNull,
+ ConcurrentDictionary_IndexIsNegative,
+ ConcurrentDictionary_ArrayNotLargeEnough,
+ ConcurrentDictionary_ArrayIncorrectType,
+ ConcurrentCollection_SyncRoot_NotSupported,
}
}
diff --git a/src/mscorlib/src/System/TimeSpan.cs b/src/mscorlib/src/System/TimeSpan.cs
index c9cfc084f3..a594da20e7 100644
--- a/src/mscorlib/src/System/TimeSpan.cs
+++ b/src/mscorlib/src/System/TimeSpan.cs
@@ -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
{
@@ -289,11 +289,11 @@ namespace System {
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) {
- TimeSpanParse.ValidateStyles(styles, "styles");
+ TimeSpanParse.ValidateStyles(styles, nameof(styles));
return TimeSpanParse.ParseExact(input, format, formatProvider, styles);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) {
- TimeSpanParse.ValidateStyles(styles, "styles");
+ TimeSpanParse.ValidateStyles(styles, nameof(styles));
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles);
}
public static Boolean TryParse(String s, out TimeSpan result) {
@@ -309,11 +309,11 @@ namespace System {
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) {
- TimeSpanParse.ValidateStyles(styles, "styles");
+ TimeSpanParse.ValidateStyles(styles, nameof(styles));
return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) {
- TimeSpanParse.ValidateStyles(styles, "styles");
+ TimeSpanParse.ValidateStyles(styles, nameof(styles));
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result);
}
public override String ToString() {
@@ -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;
diff --git a/src/mscorlib/src/System/TimeZone.cs b/src/mscorlib/src/System/TimeZone.cs
index 602e86ab54..c0a369fd3c 100644
--- a/src/mscorlib/src/System/TimeZone.cs
+++ b/src/mscorlib/src/System/TimeZone.cs
@@ -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;
diff --git a/src/mscorlib/src/System/TimeZoneInfo.cs b/src/mscorlib/src/System/TimeZoneInfo.cs
index a9d194afab..72fc28fc3e 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.cs
@@ -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;
@@ -319,24 +290,58 @@ namespace System {
}
}
+#if PLATFORM_UNIX
+ // The rules we use in Unix cares mostly about the start and end dates but doesn’t fill the transition start and end info.
+ // as the rules now is public, we should fill it properly so the caller doesn’t have to know how we use it internally
+ // and can use it as it is used in Windows
- // ---- SECTION: public methods --------------*
+ private AdjustmentRule[] GetFilledRules()
+ {
+ 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++)
+ {
+ var rule = m_adjustmentRules[i];
+ var start = rule.DateStart.Kind == DateTimeKind.Utc ?
+ new DateTime(TimeZoneInfo.ConvertTime(rule.DateStart, this).Ticks, DateTimeKind.Unspecified) :
+ rule.DateStart;
+ var end = rule.DateEnd.Kind == DateTimeKind.Utc ?
+ new DateTime(TimeZoneInfo.ConvertTime(rule.DateEnd, this).Ticks - 1, DateTimeKind.Unspecified) :
+ rule.DateEnd;
+
+ var startTransition = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, start.Hour, start.Minute, start.Second), start.Month, start.Day);
+ var endTransition = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, end.Hour, end.Minute, end.Second), end.Month, end.Day);
+
+ rules[i] = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(start.Date, end.Date, rule.DaylightDelta, startTransition, endTransition);
+ }
+
+ return rules;
+ }
+#endif // PLATFORM_UNIX
+ // ---- SECTION: public methods --------------*
//
// GetAdjustmentRules -
//
// returns a cloned array of AdjustmentRule objects
//
- public AdjustmentRule [] GetAdjustmentRules() {
- if (m_adjustmentRules == null) {
- return new AdjustmentRule[0];
+ public AdjustmentRule [] GetAdjustmentRules()
+ {
+ if (m_adjustmentRules == null)
+ {
+ return Array.Empty<AdjustmentRule>();
}
- else {
- return (AdjustmentRule[])m_adjustmentRules.Clone();
+ else
+ {
+#if PLATFORM_UNIX
+ return GetFilledRules();
+#else
+ return (AdjustmentRule[]) m_adjustmentRules.Clone();
+#endif // PLATFORM_UNIX
}
}
-
//
// GetAmbiguousTimeOffsets -
//
@@ -345,7 +350,7 @@ namespace System {
//
public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset) {
if (!SupportsDaylightSavingTime) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), "dateTimeOffset");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), nameof(dateTimeOffset));
}
Contract.EndContractBlock();
@@ -354,12 +359,12 @@ namespace System {
Boolean isAmbiguous = false;
AdjustmentRule rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime);
if (rule != null && rule.HasDaylightSaving) {
- DaylightTime daylightTime = GetDaylightTime(adjustedTime.Year, rule);
+ DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
if (!isAmbiguous) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), "dateTimeOffset");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), nameof(dateTimeOffset));
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
@@ -382,7 +387,7 @@ namespace System {
public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime) {
if (!SupportsDaylightSavingTime) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), "dateTime");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), nameof(dateTime));
}
Contract.EndContractBlock();
@@ -393,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;
@@ -402,12 +407,12 @@ namespace System {
Boolean isAmbiguous = false;
AdjustmentRule rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime);
if (rule != null && rule.HasDaylightSaving) {
- DaylightTime daylightTime = GetDaylightTime(adjustedTime.Year, rule);
+ DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
if (!isAmbiguous) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), "dateTime");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), nameof(dateTime));
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
@@ -491,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);
}
@@ -558,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;
@@ -566,7 +571,7 @@ namespace System {
AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime);
if (rule != null && rule.HasDaylightSaving) {
- DaylightTime daylightTime = GetDaylightTime(adjustedTime.Year, rule);
+ DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
return GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
return false;
@@ -644,7 +649,7 @@ namespace System {
//
AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime);
if (rule != null && rule.HasDaylightSaving) {
- DaylightTime daylightTime = GetDaylightTime(adjustedTime.Year, rule);
+ DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
return GetIsDaylightSavings(adjustedTime, rule, daylightTime, flags);
}
else {
@@ -668,7 +673,7 @@ namespace System {
AdjustmentRule rule = GetAdjustmentRuleForTime(dateTime);
if (rule != null && rule.HasDaylightSaving) {
- DaylightTime daylightTime = GetDaylightTime(dateTime.Year, rule);
+ DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule);
isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);
}
else {
@@ -690,22 +695,25 @@ namespace System {
s_cachedData = new CachedData();
}
-#if FEATURE_WIN32_REGISTRY
//
// ConvertTimeBySystemTimeZoneId -
//
// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone
//
- static public DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, String destinationTimeZoneId) {
+ static public DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, String destinationTimeZoneId)
+ {
return ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId));
}
- static public DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, String destinationTimeZoneId) {
+ static public DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, String destinationTimeZoneId)
+ {
return ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId));
}
- static public DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, String sourceTimeZoneId, String destinationTimeZoneId) {
- if (dateTime.Kind == DateTimeKind.Local && String.Compare(sourceTimeZoneId, TimeZoneInfo.Local.Id, StringComparison.OrdinalIgnoreCase) == 0) {
+ static public DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, String sourceTimeZoneId, String destinationTimeZoneId)
+ {
+ if (dateTime.Kind == DateTimeKind.Local && String.Compare(sourceTimeZoneId, TimeZoneInfo.Local.Id, StringComparison.OrdinalIgnoreCase) == 0)
+ {
// TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData.
// Take snapshot of cached data to guarantee this method will not be impacted by the ClearCachedData call.
// Without the snapshot, there is a chance that ConvertTime will throw since 'source' won't
@@ -714,21 +722,21 @@ namespace System {
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, cachedData.Local, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
}
- else if (dateTime.Kind == DateTimeKind.Utc && String.Compare(sourceTimeZoneId, TimeZoneInfo.Utc.Id, StringComparison.OrdinalIgnoreCase) == 0) {
+ else if (dateTime.Kind == DateTimeKind.Utc && String.Compare(sourceTimeZoneId, TimeZoneInfo.Utc.Id, StringComparison.OrdinalIgnoreCase) == 0)
+ {
// TimeZoneInfo.Utc can be cleared by another thread calling TimeZoneInfo.ClearCachedData.
// Take snapshot of cached data to guarantee this method will not be impacted by the ClearCachedData call.
// Without the snapshot, there is a chance that ConvertTime will throw since 'source' won't
// 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 {
+ else
+ {
return ConvertTime(dateTime, FindSystemTimeZoneById(sourceTimeZoneId), FindSystemTimeZoneById(destinationTimeZoneId));
}
}
-#endif // FEATURE_WIN32_REGISTRY
-
//
// ConvertTime -
@@ -738,7 +746,7 @@ namespace System {
static public DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) {
if (destinationTimeZone == null) {
- throw new ArgumentNullException("destinationTimeZone");
+ throw new ArgumentNullException(nameof(destinationTimeZone));
}
Contract.EndContractBlock();
@@ -762,7 +770,7 @@ namespace System {
static public DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone) {
if (destinationTimeZone == null) {
- throw new ArgumentNullException("destinationTimeZone");
+ throw new ArgumentNullException(nameof(destinationTimeZone));
}
Contract.EndContractBlock();
@@ -772,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);
@@ -790,17 +798,17 @@ namespace System {
static private DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData) {
if (sourceTimeZone == null) {
- throw new ArgumentNullException("sourceTimeZone");
+ throw new ArgumentNullException(nameof(sourceTimeZone));
}
if (destinationTimeZone == null) {
- throw new ArgumentNullException("destinationTimeZone");
+ throw new ArgumentNullException(nameof(destinationTimeZone));
}
Contract.EndContractBlock();
DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone);
if ( ((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind) ) {
- throw new ArgumentException(Environment.GetResourceString("Argument_ConvertMismatch"), "sourceTimeZone");
+ throw new ArgumentException(Environment.GetResourceString("Argument_ConvertMismatch"), nameof(sourceTimeZone));
}
//
@@ -818,12 +826,12 @@ namespace System {
sourceOffset = sourceOffset + sourceRule.BaseUtcOffsetDelta;
if (sourceRule.HasDaylightSaving) {
Boolean sourceIsDaylightSavings = false;
- DaylightTime sourceDaylightTime = sourceTimeZone.GetDaylightTime(dateTime.Year, sourceRule);
+ DaylightTimeStruct sourceDaylightTime = sourceTimeZone.GetDaylightTime(dateTime.Year, sourceRule);
// 'dateTime' might be in an invalid time range since it is in an AdjustmentRule
// period that supports DST
if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && GetIsInvalidTime(dateTime, sourceRule, sourceDaylightTime)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsInvalid"), "dateTime");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsInvalid"), nameof(dateTime));
}
sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime, flags);
@@ -866,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);
}
@@ -880,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);
}
@@ -889,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);
}
@@ -909,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);
}
//
@@ -921,10 +925,10 @@ namespace System {
//
static public TimeZoneInfo FromSerializedString(string source) {
if (source == null) {
- throw new ArgumentNullException("source");
+ throw new ArgumentNullException(nameof(source));
}
if (source.Length == 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSerializedString", source), "source");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSerializedString", source), nameof(source));
}
Contract.EndContractBlock();
@@ -936,7 +940,7 @@ namespace System {
// GetHashCode -
//
public override int GetHashCode() {
- return m_id.ToUpper(CultureInfo.InvariantCulture).GetHashCode();
+ return StringComparer.OrdinalIgnoreCase.GetHashCode(m_id);
}
//
@@ -952,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;
@@ -973,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);
}
@@ -981,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
@@ -1025,7 +1026,7 @@ namespace System {
//
public Boolean HasSameRules(TimeZoneInfo other) {
if (other == null) {
- throw new ArgumentNullException("other");
+ throw new ArgumentNullException(nameof(other));
}
// check the utcOffset and supportsDaylightSavingTime members
@@ -1118,7 +1119,7 @@ namespace System {
static public TimeZoneInfo Utc {
get {
Contract.Ensures(Contract.Result<TimeZoneInfo>() != null);
- return s_cachedData.Utc;
+ return s_utcTimeZone;
}
}
@@ -1130,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)) {
@@ -1262,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 -----------------*
@@ -1312,7 +1309,7 @@ namespace System {
String daylightDisplayName,
AdjustmentRule [] adjustmentRules) {
- return new TimeZoneInfo(
+ return CreateCustomTimeZone(
id,
baseUtcOffset,
displayName,
@@ -1341,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,
@@ -1373,10 +1374,9 @@ namespace System {
}
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -1392,7 +1392,7 @@ namespace System {
TimeZoneInfo(SerializationInfo info, StreamingContext context) {
if (info == null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
m_id = (String)info.GetValue("Id", typeof(String));
@@ -1554,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
@@ -1612,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);
@@ -1670,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;
@@ -1679,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;
}
}
@@ -1712,7 +1704,7 @@ namespace System {
//
// Helper function that returns a DaylightTime from a year and AdjustmentRule
//
- private DaylightTime GetDaylightTime(Int32 year, AdjustmentRule rule) {
+ private DaylightTimeStruct GetDaylightTime(Int32 year, AdjustmentRule rule) {
TimeSpan delta = rule.DaylightDelta;
DateTime startTime;
DateTime endTime;
@@ -1733,7 +1725,7 @@ namespace System {
startTime = TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
endTime = TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
}
- return new DaylightTime(startTime, endTime, delta);
+ return new DaylightTimeStruct(startTime, endTime, delta);
}
//
@@ -1742,7 +1734,7 @@ namespace System {
// Helper function that checks if a given dateTime is in Daylight Saving Time (DST)
// This function assumes the dateTime and AdjustmentRule are both in the same time zone
//
- static private Boolean GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTime daylightTime, TimeZoneInfoOptions flags) {
+ static private Boolean GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime, TimeZoneInfoOptions flags) {
if (rule == null) {
return false;
}
@@ -1837,7 +1829,7 @@ namespace System {
// Get the daylight changes for the year of the specified time.
- DaylightTime daylightTime = zone.GetDaylightTime(Year, rule);
+ DaylightTimeStruct daylightTime = zone.GetDaylightTime(Year, rule);
// The start and end times represent the range of universal times that are in DST for that year.
// Within that there is an ambiguous hour, usually right at the end, but at the beginning in
@@ -1856,7 +1848,7 @@ namespace System {
if (rule.IsStartDateMarkerForBeginningOfYear() && daylightTime.Start.Year > DateTime.MinValue.Year) {
AdjustmentRule previousYearRule = zone.GetAdjustmentRuleForTime(new DateTime(daylightTime.Start.Year - 1, 12, 31));
if (previousYearRule != null && previousYearRule.IsEndDateMarkerForEndOfYear()) {
- DaylightTime previousDaylightTime = zone.GetDaylightTime(daylightTime.Start.Year - 1, previousYearRule);
+ DaylightTimeStruct previousDaylightTime = zone.GetDaylightTime(daylightTime.Start.Year - 1, previousYearRule);
startTime = previousDaylightTime.Start - utc - previousYearRule.BaseUtcOffsetDelta;
ignoreYearAdjustment = true;
} else {
@@ -1874,7 +1866,7 @@ namespace System {
if (nextYearRule.IsEndDateMarkerForEndOfYear()) {// next year end with daylight saving on too
endTime = new DateTime(daylightTime.End.Year + 1, 12, 31) - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;
} else {
- DaylightTime nextdaylightTime = zone.GetDaylightTime(daylightTime.End.Year + 1, nextYearRule);
+ DaylightTimeStruct nextdaylightTime = zone.GetDaylightTime(daylightTime.End.Year + 1, nextYearRule);
endTime = nextdaylightTime.End - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;
}
ignoreYearAdjustment = true;
@@ -1980,7 +1972,7 @@ namespace System {
// In this example, any DateTime values that fall into the [1AM - 1:59:59AM] range
// are ambiguous; as it is unclear if these times are in Daylight Saving Time.
//
- static private Boolean GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTime daylightTime) {
+ static private Boolean GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) {
Boolean isAmbiguous = false;
if (rule == null || rule.DaylightDelta == TimeSpan.Zero) {
return isAmbiguous;
@@ -2044,7 +2036,7 @@ namespace System {
// A "time hole" is not limited to only occurring at the start of DST, and may occur at
// the end of DST as well.
//
- static private Boolean GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTime daylightTime) {
+ static private Boolean GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) {
Boolean isInvalid = false;
if (rule == null || rule.DaylightDelta == TimeSpan.Zero) {
return isInvalid;
@@ -2112,7 +2104,6 @@ namespace System {
// assumes cachedData lock is taken
//
- [System.Security.SecuritySafeCritical] // auto-generated
static private TimeZoneInfo GetLocalTimeZone(CachedData cachedData) {
@@ -2280,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;
@@ -2360,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;
@@ -2476,7 +2465,6 @@ namespace System {
//
// The TryGetLocalTzFile() call returns a Byte[] containing the compiled tzfile.
//
- [System.Security.SecurityCritical]
static private TimeZoneInfo GetLocalTimeZoneFromTzFile()
{
byte[] rawData;
@@ -2539,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 {
@@ -2582,7 +2569,7 @@ namespace System {
}
if (id == null) {
- throw new ArgumentNullException("id");
+ throw new ArgumentNullException(nameof(id));
}
else if (!IsValidSystemTimeZoneId(id)) {
throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id));
@@ -2606,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
@@ -2647,7 +2634,7 @@ namespace System {
if (rule != null) {
baseOffset = baseOffset + rule.BaseUtcOffsetDelta;
if (rule.HasDaylightSaving) {
- DaylightTime daylightTime = zone.GetDaylightTime(time.Year, rule);
+ DaylightTimeStruct daylightTime = zone.GetDaylightTime(time.Year, rule);
Boolean isDaylightSavings = GetIsDaylightSavings(time, rule, daylightTime, flags);
baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
}
@@ -2719,7 +2706,7 @@ namespace System {
// As we get the associated rule using the adjusted targetTime, we should use the adjusted year (targetTime.Year) too as after adding the baseOffset,
// sometimes the year value can change if the input datetime was very close to the beginning or the end of the year. Examples of such cases:
- // “Libya Standard Time” when used with the date 2011-12-31T23:59:59.9999999Z
+ // Libya Standard Time when used with the date 2011-12-31T23:59:59.9999999Z
// "W. Australia Standard Time" used with date 2005-12-31T23:59:00.0000000Z
DateTime targetTime = time + baseOffset;
year = targetTime.Year;
@@ -2745,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 -
@@ -2856,7 +2842,7 @@ namespace System {
//
// Helper function that converts a year and TransitionTime into a DateTime
//
- static private DateTime TransitionTimeToDateTime(Int32 year, TransitionTime transitionTime) {
+ internal static DateTime TransitionTimeToDateTime(Int32 year, TransitionTime transitionTime) {
DateTime value;
DateTime timeOfDay = transitionTime.TimeOfDay;
@@ -2951,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;
}
@@ -2992,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;
}
@@ -3000,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;
}
@@ -3023,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;
}
@@ -3046,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;
}
@@ -3062,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...
@@ -3098,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
@@ -3117,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);
@@ -3127,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;
@@ -3152,7 +3136,8 @@ namespace System {
//
Boolean result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
- if (!result) {
+ if (!result)
+ {
return false;
}
@@ -3161,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...
@@ -3176,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 {
@@ -3204,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;
@@ -3277,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)) {
@@ -3308,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;
@@ -3387,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;
@@ -3397,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;
@@ -4204,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));
@@ -4213,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])
@@ -4386,20 +4354,20 @@ namespace System {
out Boolean adjustmentRulesSupportDst) {
if (id == null) {
- throw new ArgumentNullException("id");
+ throw new ArgumentNullException(nameof(id));
}
if (id.Length == 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidId", id), "id");
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidId", id), nameof(id));
}
if (UtcOffsetOutOfRange(baseUtcOffset)) {
- throw new ArgumentOutOfRangeException("baseUtcOffset", Environment.GetResourceString("ArgumentOutOfRange_UtcOffset"));
+ throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), Environment.GetResourceString("ArgumentOutOfRange_UtcOffset"));
}
if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeSpanHasSeconds"), "baseUtcOffset");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TimeSpanHasSeconds"), nameof(baseUtcOffset));
}
Contract.EndContractBlock();
@@ -4454,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 {
@@ -4534,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);
}
@@ -4555,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,
@@ -4590,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(
@@ -4601,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 ----------------*
@@ -4649,21 +4617,21 @@ namespace System {
if (dateStart.Kind != DateTimeKind.Unspecified && dateStart.Kind != DateTimeKind.Utc) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecifiedOrUtc"), "dateStart");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecifiedOrUtc"), nameof(dateStart));
}
if (dateEnd.Kind != DateTimeKind.Unspecified && dateEnd.Kind != DateTimeKind.Utc) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecifiedOrUtc"), "dateEnd");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecifiedOrUtc"), nameof(dateEnd));
}
if (daylightTransitionStart.Equals(daylightTransitionEnd) && !noDaylightTransitions) {
throw new ArgumentException(Environment.GetResourceString("Argument_TransitionTimesAreIdentical"),
- "daylightTransitionEnd");
+ nameof(daylightTransitionEnd));
}
if (dateStart > dateEnd) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OutOfOrderDateTimes"), "dateStart");
+ throw new ArgumentException(Environment.GetResourceString("Argument_OutOfOrderDateTimes"), nameof(dateStart));
}
// This cannot use UtcOffsetOutOfRange to account for the scenario where Samoa moved across the International Date Line,
@@ -4671,23 +4639,23 @@ namespace System {
// So when trying to describe DaylightDeltas for those times, the DaylightDelta needs
// to be -23 (what it takes to go from UTC+13 to UTC-10)
if (daylightDelta.TotalHours < -23.0 || daylightDelta.TotalHours > 14.0) {
- throw new ArgumentOutOfRangeException("daylightDelta", daylightDelta,
+ throw new ArgumentOutOfRangeException(nameof(daylightDelta), daylightDelta,
Environment.GetResourceString("ArgumentOutOfRange_UtcOffset"));
}
if (daylightDelta.Ticks % TimeSpan.TicksPerMinute != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_TimeSpanHasSeconds"),
- "daylightDelta");
+ nameof(daylightDelta));
}
if (dateStart != DateTime.MinValue && dateStart.Kind == DateTimeKind.Unspecified && dateStart.TimeOfDay != TimeSpan.Zero) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTimeOfDay"),
- "dateStart");
+ nameof(dateStart));
}
if (dateEnd != DateTime.MaxValue && dateEnd.Kind == DateTimeKind.Unspecified && dateEnd.TimeOfDay != TimeSpan.Zero) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTimeOfDay"),
- "dateEnd");
+ nameof(dateEnd));
}
Contract.EndContractBlock();
}
@@ -4709,10 +4677,9 @@ namespace System {
}
}
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -4727,7 +4694,7 @@ namespace System {
AdjustmentRule(SerializationInfo info, StreamingContext context) {
if (info == null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
m_dateStart = (DateTime)info.GetValue("DateStart", typeof(DateTime));
@@ -4764,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 --------------*
@@ -4859,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 -----------------*
@@ -4879,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);
}
@@ -4889,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);
}
@@ -4930,33 +4880,33 @@ namespace System {
DayOfWeek dayOfWeek) {
if (timeOfDay.Kind != DateTimeKind.Unspecified) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecified"), "timeOfDay");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecified"), nameof(timeOfDay));
}
// Month range 1-12
if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_MonthParam"));
+ throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_MonthParam"));
}
// Day range 1-31
if (day < 1 || day > 31) {
- throw new ArgumentOutOfRangeException("day", Environment.GetResourceString("ArgumentOutOfRange_DayParam"));
+ throw new ArgumentOutOfRangeException(nameof(day), Environment.GetResourceString("ArgumentOutOfRange_DayParam"));
}
// Week range 1-5
if (week < 1 || week > 5) {
- throw new ArgumentOutOfRangeException("week", Environment.GetResourceString("ArgumentOutOfRange_Week"));
+ throw new ArgumentOutOfRangeException(nameof(week), Environment.GetResourceString("ArgumentOutOfRange_Week"));
}
// DayOfWeek range 0-6
if ((int)dayOfWeek < 0 || (int)dayOfWeek > 6) {
- throw new ArgumentOutOfRangeException("dayOfWeek", Environment.GetResourceString("ArgumentOutOfRange_DayOfWeek"));
+ throw new ArgumentOutOfRangeException(nameof(dayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_DayOfWeek"));
}
Contract.EndContractBlock();
if (timeOfDay.Year != 1 || timeOfDay.Month != 1
|| timeOfDay.Day != 1 || (timeOfDay.Ticks % TimeSpan.TicksPerMillisecond != 0)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTicks"), "timeOfDay");
+ throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTicks"), nameof(timeOfDay));
}
}
@@ -4973,10 +4923,9 @@ namespace System {
}
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -4990,7 +4939,7 @@ namespace System {
TransitionTime(SerializationInfo info, StreamingContext context) {
if (info == null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
m_timeOfDay = (DateTime)info.GetValue("TimeOfDay", typeof(DateTime));
@@ -5125,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);
@@ -5653,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
{
@@ -5681,7 +5622,7 @@ namespace System {
{
if (data == null || data.Length < index + c_len)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoInvalidTZif"), "data");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoInvalidTZif"), nameof(data));
}
Contract.EndContractBlock();
UtcOffset = new TimeSpan(0, 0, TZif_ToInt32(data, index + 00));
@@ -5705,7 +5646,7 @@ namespace System {
{
if (data == null || data.Length < c_len)
{
- throw new ArgumentException("bad data", "data");
+ throw new ArgumentException("bad data", nameof(data));
}
Contract.EndContractBlock();
@@ -5714,7 +5655,7 @@ namespace System {
if (Magic != 0x545A6966)
{
// 0x545A6966 = {0x54, 0x5A, 0x69, 0x66} = "TZif"
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoBadTZif"), "data");
+ throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoBadTZif"), nameof(data));
}
byte version = data[index + 04];
diff --git a/src/mscorlib/src/System/TimeZoneNotFoundException.cs b/src/mscorlib/src/System/TimeZoneNotFoundException.cs
index 5f8b919a76..cabcc150f6 100644
--- a/src/mscorlib/src/System/TimeZoneNotFoundException.cs
+++ b/src/mscorlib/src/System/TimeZoneNotFoundException.cs
@@ -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)
diff --git a/src/mscorlib/src/System/Tuple.cs b/src/mscorlib/src/System/Tuple.cs
index 99164bc654..037b2ceee8 100644
--- a/src/mscorlib/src/System/Tuple.cs
+++ b/src/mscorlib/src/System/Tuple.cs
@@ -5,8 +5,13 @@ using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
+//
+// Note: F# compiler depends on the exact tuple hashing algorithm. Do not ever change it.
+//
+
namespace System {
/// <summary>
@@ -119,7 +124,7 @@ namespace System {
Tuple<T1> objTuple = other as Tuple<T1>;
if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
}
return comparer.Compare(m_Item1, objTuple.m_Item1);
@@ -195,7 +200,7 @@ namespace System {
Tuple<T1, T2> objTuple = other as Tuple<T1, T2>;
if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
}
int c = 0;
@@ -282,7 +287,7 @@ namespace System {
Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;
if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
}
int c = 0;
@@ -378,7 +383,7 @@ namespace System {
Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>;
if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
}
int c = 0;
@@ -483,7 +488,7 @@ namespace System {
Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>;
if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
}
int c = 0;
@@ -597,7 +602,7 @@ namespace System {
Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>;
if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
}
int c = 0;
@@ -720,7 +725,7 @@ namespace System {
Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
}
int c = 0;
@@ -856,7 +861,7 @@ namespace System {
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
if (objTuple == null) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), nameof(other));
}
int c = 0;
@@ -919,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;
}
diff --git a/src/mscorlib/src/System/Type.cs b/src/mscorlib/src/System/Type.cs
index 730003307a..2d30c4c7f2 100644
--- a/src/mscorlib/src/System/Type.cs
+++ b/src/mscorlib/src/System/Type.cs
@@ -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);
@@ -395,11 +385,11 @@ namespace System {
{
// Must provide some types (Type[0] for nothing)
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i=0;i<types.Length;i++)
if (types[i] == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
return GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers);
}
@@ -407,11 +397,11 @@ namespace System {
public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
{
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i=0;i<types.Length;i++)
if (types[i] == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
return GetConstructorImpl(bindingAttr, binder, CallingConventions.Any, types, modifiers);
}
@@ -464,13 +454,13 @@ namespace System {
ParameterModifier[] modifiers)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i = 0; i < types.Length; i++)
if (types[i] == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
}
@@ -481,46 +471,46 @@ namespace System {
ParameterModifier[] modifiers)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i = 0; i < types.Length; i++)
if (types[i] == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
return GetMethodImpl(name, bindingAttr, binder, CallingConventions.Any, types, modifiers);
}
public MethodInfo GetMethod(String name, Type[] types, ParameterModifier[] modifiers)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i=0;i<types.Length;i++)
if (types[i] == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
return GetMethodImpl(name, Type.DefaultLookup, null, CallingConventions.Any, types, modifiers);
}
public MethodInfo GetMethod(String name,Type[] types)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i=0;i<types.Length;i++)
if (types[i] == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
return GetMethodImpl(name, Type.DefaultLookup, null, CallingConventions.Any, types, null);
}
public MethodInfo GetMethod(String name, BindingFlags bindingAttr)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
return GetMethodImpl(name, bindingAttr, null, CallingConventions.Any, null, null);
}
@@ -528,7 +518,7 @@ namespace System {
public MethodInfo GetMethod(String name)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
return GetMethodImpl(name, Type.DefaultLookup, null, CallingConventions.Any, null, null);
}
@@ -584,7 +574,7 @@ namespace System {
public virtual Type[] FindInterfaces(TypeFilter filter,Object filterCriteria)
{
if (filter == null)
- throw new ArgumentNullException("filter");
+ throw new ArgumentNullException(nameof(filter));
Contract.EndContractBlock();
Type[] c = GetInterfaces();
int cnt = 0;
@@ -631,9 +621,9 @@ namespace System {
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
return GetPropertyImpl(name,bindingAttr,binder,returnType,types,modifiers);
}
@@ -641,9 +631,9 @@ namespace System {
public PropertyInfo GetProperty(String name, Type returnType, Type[] types,ParameterModifier[] modifiers)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,types,modifiers);
}
@@ -651,7 +641,7 @@ namespace System {
public PropertyInfo GetProperty(String name, BindingFlags bindingAttr)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
return GetPropertyImpl(name,bindingAttr,null,null,null,null);
}
@@ -659,9 +649,9 @@ namespace System {
public PropertyInfo GetProperty(String name, Type returnType, Type[] types)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,types,null);
}
@@ -669,9 +659,9 @@ namespace System {
public PropertyInfo GetProperty(String name, Type[] types)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (types == null)
- throw new ArgumentNullException("types");
+ throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
return GetPropertyImpl(name,Type.DefaultLookup,null,null,types,null);
}
@@ -679,9 +669,9 @@ namespace System {
public PropertyInfo GetProperty(String name, Type returnType)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (returnType == null)
- throw new ArgumentNullException("returnType");
+ throw new ArgumentNullException(nameof(returnType));
Contract.EndContractBlock();
return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,null,null);
}
@@ -689,9 +679,9 @@ namespace System {
internal PropertyInfo GetProperty(String name, BindingFlags bindingAttr, Type returnType)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
if (returnType == null)
- throw new ArgumentNullException("returnType");
+ throw new ArgumentNullException(nameof(returnType));
Contract.EndContractBlock();
return GetPropertyImpl(name, bindingAttr, null, returnType, null, null);
}
@@ -699,7 +689,7 @@ namespace System {
public PropertyInfo GetProperty(String name)
{
if (name == null)
- throw new ArgumentNullException("name");
+ throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
return GetPropertyImpl(name,Type.DefaultLookup,null,null,null,null);
}
@@ -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;
@@ -1076,11 +1061,7 @@ namespace System {
get {return ((GetAttributeFlagsImpl() & TypeAttributes.Sealed) != 0);}
}
-#if FEATURE_CORECLR
- public bool IsEnum {
-#else
public virtual bool IsEnum {
-#endif
[Pure]
get
{
@@ -1305,14 +1286,15 @@ namespace System {
// Protected routine to determine if this class is contextful
- protected virtual bool IsContextfulImpl(){
- return typeof(ContextBoundObject).IsAssignableFrom(this);
+ protected virtual bool IsContextfulImpl()
+ {
+ return false;
}
-
// Protected routine to determine if this class is marshaled by ref
- protected virtual bool IsMarshalByRefImpl(){
- return typeof(MarshalByRefObject).IsAssignableFrom(this);
+ protected virtual bool IsMarshalByRefImpl()
+ {
+ return false;
}
internal virtual bool HasProxyAttributeImpl()
@@ -1362,7 +1344,7 @@ namespace System {
return rootElementType;
}
- #region Enum methods
+#region Enum methods
// Default implementations of GetEnumNames, GetEnumValues, and GetEnumUnderlyingType
// Subclass of types can override these methods.
@@ -1465,7 +1447,7 @@ namespace System {
public virtual bool IsEnumDefined(object value)
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
if (!IsEnum)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
@@ -1513,7 +1495,7 @@ namespace System {
public virtual string GetEnumName(object value)
{
if (value == null)
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
if (!IsEnum)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
@@ -1522,7 +1504,7 @@ namespace System {
Type valueType = value.GetType();
if (!(valueType.IsEnum || Type.IsIntegerType(valueType)))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), nameof(value));
Array values = GetEnumRawConstantValues();
int index = BinarySearch(values, value);
@@ -1561,7 +1543,7 @@ namespace System {
t == typeof(char) ||
t == typeof(bool));
}
- #endregion
+#endregion
public virtual bool IsSecurityCritical { [Pure] get { throw new NotImplementedException(); } }
@@ -1743,7 +1725,7 @@ namespace System {
// types.
public static Type[] GetTypeArray(Object[] args) {
if (args == null)
- throw new ArgumentNullException("args");
+ throw new ArgumentNullException(nameof(args));
Contract.EndContractBlock();
Type[] cls = new Type[args.Length];
for (int i = 0;i < cls.Length;i++)
@@ -1766,11 +1748,7 @@ namespace System {
// _Type.Equals(Type)
[Pure]
-#if !FEATURE_CORECLR
public virtual bool Equals(Type o)
-#else
- public bool Equals(Type o)
-#endif
{
if ((object)o == null)
return false;
@@ -1778,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);
@@ -1814,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;
diff --git a/src/mscorlib/src/System/TypeInitializationException.cs b/src/mscorlib/src/System/TypeInitializationException.cs
index 62d189d53b..bcc1c3e968 100644
--- a/src/mscorlib/src/System/TypeInitializationException.cs
+++ b/src/mscorlib/src/System/TypeInitializationException.cs
@@ -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));
diff --git a/src/mscorlib/src/System/TypeLoadException.cs b/src/mscorlib/src/System/TypeLoadException.cs
index 9b5d28dfba..d73a97f9c5 100644
--- a/src/mscorlib/src/System/TypeLoadException.cs
+++ b/src/mscorlib/src/System/TypeLoadException.cs
@@ -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,
@@ -103,7 +100,7 @@ namespace System {
protected TypeLoadException(SerializationInfo info, StreamingContext context) : base(info, context) {
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
ClassName = info.GetString("TypeLoadClassName");
@@ -112,17 +109,15 @@ 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("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
base.GetObjectData(info, context);
diff --git a/src/mscorlib/src/System/TypeNameParser.cs b/src/mscorlib/src/System/TypeNameParser.cs
index fee0f3aa64..844578210f 100644
--- a/src/mscorlib/src/System/TypeNameParser.cs
+++ b/src/mscorlib/src/System/TypeNameParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
+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,
@@ -79,7 +71,7 @@ namespace System
ref StackCrawlMark stackMark)
{
if (typeName == null)
- throw new ArgumentNullException("typeName");
+ throw new ArgumentNullException(nameof(typeName));
if (typeName.Length > 0 && typeName[0] == '\0')
throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
Contract.EndContractBlock();
@@ -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;
diff --git a/src/mscorlib/src/System/TypedReference.cs b/src/mscorlib/src/System/TypedReference.cs
index 7c68c4164f..b65652e590 100644
--- a/src/mscorlib/src/System/TypedReference.cs
+++ b/src/mscorlib/src/System/TypedReference.cs
@@ -23,13 +23,12 @@ 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)
- throw new ArgumentNullException("target");
+ throw new ArgumentNullException(nameof(target));
if (flds == null)
- throw new ArgumentNullException("flds");
+ throw new ArgumentNullException(nameof(flds));
Contract.EndContractBlock();
if (flds.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayZeroError"));
@@ -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);
}
diff --git a/src/mscorlib/src/System/UInt16.cs b/src/mscorlib/src/System/UInt16.cs
index dba7f97b77..399ef02d7d 100644
--- a/src/mscorlib/src/System/UInt16.cs
+++ b/src/mscorlib/src/System/UInt16.cs
@@ -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));
diff --git a/src/mscorlib/src/System/UInt32.cs b/src/mscorlib/src/System/UInt32.cs
index 7010daec43..f3d60092f7 100644
--- a/src/mscorlib/src/System/UInt32.cs
+++ b/src/mscorlib/src/System/UInt32.cs
@@ -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));
diff --git a/src/mscorlib/src/System/UInt64.cs b/src/mscorlib/src/System/UInt64.cs
index 83549cf423..b55cd7ce6a 100644
--- a/src/mscorlib/src/System/UInt64.cs
+++ b/src/mscorlib/src/System/UInt64.cs
@@ -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));
diff --git a/src/mscorlib/src/System/UIntPtr.cs b/src/mscorlib/src/System/UIntPtr.cs
index ac3b811b42..eab424fc69 100644
--- a/src/mscorlib/src/System/UIntPtr.cs
+++ b/src/mscorlib/src/System/UIntPtr.cs
@@ -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,17 +62,15 @@ namespace System {
m_value = (void *)l;
}
- [System.Security.SecurityCritical]
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
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()
diff --git a/src/mscorlib/src/System/UnSafeCharBuffer.cs b/src/mscorlib/src/System/UnSafeCharBuffer.cs
deleted file mode 100644
index 78059b623a..0000000000
--- a/src/mscorlib/src/System/UnSafeCharBuffer.cs
+++ /dev/null
@@ -1,57 +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: A class to detect incorrect usage of UnSafeBuffer
-**
-**
-===========================================================*/
-
-namespace System {
- using System.Security;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- unsafe internal struct UnSafeCharBuffer{
- [SecurityCritical]
- char * m_buffer;
- int m_totalSize;
- int m_length;
-
- [System.Security.SecurityCritical] // auto-generated
- public UnSafeCharBuffer( char *buffer, int bufferSize) {
- Contract.Assert( buffer != null, "buffer pointer can't be null." );
- Contract.Assert( bufferSize >= 0, "buffer size can't be negative." );
- m_buffer = buffer;
- m_totalSize = bufferSize;
- m_length = 0;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public void AppendString(string stringToAppend) {
- if( String.IsNullOrEmpty( stringToAppend ) ) {
- return;
- }
-
- if ( (m_totalSize - m_length) < stringToAppend.Length ) {
- throw new IndexOutOfRangeException();
- }
-
- fixed( char* pointerToString = stringToAppend ) {
- Buffer.Memcpy( (byte*) (m_buffer + m_length), (byte *) pointerToString, stringToAppend.Length * sizeof(char));
- }
-
- m_length += stringToAppend.Length;
- Contract.Assert(m_length <= m_totalSize, "Buffer has been overflowed!");
- }
-
- public int Length {
- get {
- return m_length;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs b/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs
index 7d6531945e..8c2798230c 100644
--- a/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs
+++ b/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs
@@ -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);
diff --git a/src/mscorlib/src/System/UnitySerializationHolder.cs b/src/mscorlib/src/System/UnitySerializationHolder.cs
index ec32fce348..712391a915 100644
--- a/src/mscorlib/src/System/UnitySerializationHolder.cs
+++ b/src/mscorlib/src/System/UnitySerializationHolder.cs
@@ -166,7 +166,7 @@ namespace System {
internal UnitySerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
m_unityType = info.GetInt32("UnityType");
@@ -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
diff --git a/src/mscorlib/src/System/ValueType.cs b/src/mscorlib/src/System/ValueType.cs
index ae08b7d0ba..102a0d2b92 100644
--- a/src/mscorlib/src/System/ValueType.cs
+++ b/src/mscorlib/src/System/ValueType.cs
@@ -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();
diff --git a/src/mscorlib/src/System/Variant.cs b/src/mscorlib/src/System/Variant.cs
index 26e2e4aa1a..2a9593cf42 100644
--- a/src/mscorlib/src/System/Variant.cs
+++ b/src/mscorlib/src/System/Variant.cs
@@ -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,12 +335,11 @@ namespace System {
}
- [System.Security.SecurityCritical] // auto-generated
unsafe public Variant(void* voidPointer,Type pointerType) {
if (pointerType == null)
- throw new ArgumentNullException("pointerType");
+ throw new ArgumentNullException(nameof(pointerType));
if (!pointerType.IsPointer)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),"pointerType");
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(pointerType));
Contract.EndContractBlock();
m_objref = 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;
diff --git a/src/mscorlib/src/System/Version.cs b/src/mscorlib/src/System/Version.cs
index f3520b81a2..f2ef5d4486 100644
--- a/src/mscorlib/src/System/Version.cs
+++ b/src/mscorlib/src/System/Version.cs
@@ -12,6 +12,7 @@
===========================================================*/
namespace System {
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using CultureInfo = System.Globalization.CultureInfo;
@@ -29,24 +30,24 @@ namespace System {
, IComparable<Version>, IEquatable<Version>
{
// AssemblyName depends on the order staying the same
- private int _Major;
- private int _Minor;
- private int _Build = -1;
- private int _Revision = -1;
+ private readonly int _Major;
+ private readonly int _Minor;
+ private readonly int _Build = -1;
+ private readonly int _Revision = -1;
private static readonly char[] SeparatorsArray = new char[] { '.' };
public Version(int major, int minor, int build, int revision) {
if (major < 0)
- throw new ArgumentOutOfRangeException("major",Environment.GetResourceString("ArgumentOutOfRange_Version"));
+ throw new ArgumentOutOfRangeException(nameof(major),Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (minor < 0)
- throw new ArgumentOutOfRangeException("minor",Environment.GetResourceString("ArgumentOutOfRange_Version"));
+ throw new ArgumentOutOfRangeException(nameof(minor),Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (build < 0)
- throw new ArgumentOutOfRangeException("build",Environment.GetResourceString("ArgumentOutOfRange_Version"));
+ throw new ArgumentOutOfRangeException(nameof(build),Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (revision < 0)
- throw new ArgumentOutOfRangeException("revision",Environment.GetResourceString("ArgumentOutOfRange_Version"));
+ throw new ArgumentOutOfRangeException(nameof(revision),Environment.GetResourceString("ArgumentOutOfRange_Version"));
Contract.EndContractBlock();
_Major = major;
@@ -57,13 +58,13 @@ namespace System {
public Version(int major, int minor, int build) {
if (major < 0)
- throw new ArgumentOutOfRangeException("major",Environment.GetResourceString("ArgumentOutOfRange_Version"));
+ throw new ArgumentOutOfRangeException(nameof(major),Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (minor < 0)
- throw new ArgumentOutOfRangeException("minor",Environment.GetResourceString("ArgumentOutOfRange_Version"));
+ throw new ArgumentOutOfRangeException(nameof(minor),Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (build < 0)
- throw new ArgumentOutOfRangeException("build",Environment.GetResourceString("ArgumentOutOfRange_Version"));
+ throw new ArgumentOutOfRangeException(nameof(build),Environment.GetResourceString("ArgumentOutOfRange_Version"));
Contract.EndContractBlock();
@@ -74,10 +75,10 @@ namespace System {
public Version(int major, int minor) {
if (major < 0)
- throw new ArgumentOutOfRangeException("major",Environment.GetResourceString("ArgumentOutOfRange_Version"));
+ throw new ArgumentOutOfRangeException(nameof(major),Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (minor < 0)
- throw new ArgumentOutOfRangeException("minor",Environment.GetResourceString("ArgumentOutOfRange_Version"));
+ throw new ArgumentOutOfRangeException(nameof(minor),Environment.GetResourceString("ArgumentOutOfRange_Version"));
Contract.EndContractBlock();
_Major = major;
@@ -98,6 +99,16 @@ namespace System {
_Minor = 0;
}
+ private Version(Version version)
+ {
+ Debug.Assert(version != null);
+
+ _Major = version._Major;
+ _Minor = version._Minor;
+ _Build = version._Build;
+ _Revision = version._Revision;
+ }
+
// Properties for setting and getting version numbers
public int Major {
get { return _Major; }
@@ -124,12 +135,7 @@ namespace System {
}
public Object Clone() {
- Version v = new Version();
- v._Major = _Major;
- v._Minor = _Minor;
- v._Build = _Build;
- v._Revision = _Revision;
- return(v);
+ return new Version(this);
}
public int CompareTo(Object version)
@@ -145,93 +151,33 @@ namespace System {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeVersion"));
}
- if (this._Major != v._Major)
- if (this._Major > v._Major)
- return 1;
- else
- return -1;
-
- if (this._Minor != v._Minor)
- if (this._Minor > v._Minor)
- return 1;
- else
- return -1;
-
- if (this._Build != v._Build)
- if (this._Build > v._Build)
- return 1;
- else
- return -1;
-
- if (this._Revision != v._Revision)
- if (this._Revision > v._Revision)
- return 1;
- else
- return -1;
-
- return 0;
+ return CompareTo(v);
}
public int CompareTo(Version value)
{
- if (value == null)
- return 1;
-
- if (this._Major != value._Major)
- if (this._Major > value._Major)
- return 1;
- else
- return -1;
-
- if (this._Minor != value._Minor)
- if (this._Minor > value._Minor)
- return 1;
- else
- return -1;
-
- if (this._Build != value._Build)
- if (this._Build > value._Build)
- return 1;
- else
- return -1;
-
- if (this._Revision != value._Revision)
- if (this._Revision > value._Revision)
- return 1;
- else
- return -1;
-
- return 0;
+ return
+ object.ReferenceEquals(value, this) ? 0 :
+ object.ReferenceEquals(value, null) ? 1 :
+ _Major != value._Major ? (_Major > value._Major ? 1 : -1) :
+ _Minor != value._Minor ? (_Minor > value._Minor ? 1 : -1) :
+ _Build != value._Build ? (_Build > value._Build ? 1 : -1) :
+ _Revision != value._Revision ? (_Revision > value._Revision ? 1 : -1) :
+ 0;
}
public override bool Equals(Object obj) {
- Version v = obj as Version;
- if (v == null)
- return false;
-
- // check that major, minor, build & revision numbers match
- if ((this._Major != v._Major) ||
- (this._Minor != v._Minor) ||
- (this._Build != v._Build) ||
- (this._Revision != v._Revision))
- return false;
-
- return true;
+ return Equals(obj as Version);
}
public bool Equals(Version obj)
{
- if (obj == null)
- return false;
-
- // check that major, minor, build & revision numbers match
- if ((this._Major != obj._Major) ||
- (this._Minor != obj._Minor) ||
- (this._Build != obj._Build) ||
- (this._Revision != obj._Revision))
- return false;
-
- return true;
+ return object.ReferenceEquals(obj, this) ||
+ (!object.ReferenceEquals(obj, null) &&
+ _Major == obj._Major &&
+ _Minor == obj._Minor &&
+ _Build == obj._Build &&
+ _Revision == obj._Revision);
}
public override int GetHashCode()
@@ -270,7 +216,7 @@ namespace System {
return StringBuilderCache.GetStringAndRelease(sb);
default:
if (_Build == -1)
- throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "2"), "fieldCount");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "2"), nameof(fieldCount));
if (fieldCount == 3)
{
@@ -284,7 +230,7 @@ namespace System {
}
if (_Revision == -1)
- throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "3"), "fieldCount");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "3"), nameof(fieldCount));
if (fieldCount == 4)
{
@@ -299,7 +245,7 @@ namespace System {
return StringBuilderCache.GetStringAndRelease(sb);
}
- throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "4"), "fieldCount");
+ throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "4"), nameof(fieldCount));
}
}
@@ -307,12 +253,12 @@ namespace System {
// AppendPositiveNumber is an optimization to append a number to a StringBuilder object without
// doing any boxing and not even creating intermediate string.
// Note: as we always have positive numbers then it is safe to convert the number to string
- // regardless of the current culture as we’ll not have any punctuation marks in the number
+ // regardless of the current culture as we'll not have any punctuation marks in the number
//
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;
@@ -327,12 +273,12 @@ namespace System {
public static Version Parse(string input) {
if (input == null) {
- throw new ArgumentNullException("input");
+ throw new ArgumentNullException(nameof(input));
}
Contract.EndContractBlock();
VersionResult r = new VersionResult();
- r.Init("input", true);
+ r.Init(nameof(input), true);
if (!TryParseVersion(input, ref r)) {
throw r.GetVersionParseException();
}
@@ -341,7 +287,7 @@ namespace System {
public static bool TryParse(string input, out Version result) {
VersionResult r = new VersionResult();
- r.Init("input", false);
+ r.Init(nameof(input), false);
bool b = TryParseVersion(input, ref r);
result = r.m_parsedVersion;
return b;
@@ -362,11 +308,11 @@ namespace System {
return false;
}
- if (!TryParseComponent(parsedComponents[0], "version", ref result, out major)) {
+ if (!TryParseComponent(parsedComponents[0], nameof(version), ref result, out major)) {
return false;
}
- if (!TryParseComponent(parsedComponents[1], "version", ref result, out minor)) {
+ if (!TryParseComponent(parsedComponents[1], nameof(version), ref result, out minor)) {
return false;
}
@@ -423,14 +369,14 @@ namespace System {
public static bool operator <(Version v1, Version v2) {
if ((Object) v1 == null)
- throw new ArgumentNullException("v1");
+ throw new ArgumentNullException(nameof(v1));
Contract.EndContractBlock();
return (v1.CompareTo(v2) < 0);
}
public static bool operator <=(Version v1, Version v2) {
if ((Object) v1 == null)
- throw new ArgumentNullException("v1");
+ throw new ArgumentNullException(nameof(v1));
Contract.EndContractBlock();
return (v1.CompareTo(v2) <= 0);
}
@@ -491,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"));
}
}
diff --git a/src/mscorlib/src/System/WeakReference.cs b/src/mscorlib/src/System/WeakReference.cs
index d12ca3e853..d5648527f0 100644
--- a/src/mscorlib/src/System/WeakReference.cs
+++ b/src/mscorlib/src/System/WeakReference.cs
@@ -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.)
@@ -53,7 +49,7 @@ namespace System {
protected WeakReference(SerializationInfo info, StreamingContext context) {
if (info==null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -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,14 +92,12 @@ 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) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
info.AddValue("TrackedObject", Target, typeof(Object));
@@ -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();
}
diff --git a/src/mscorlib/src/System/WeakReferenceOfT.cs b/src/mscorlib/src/System/WeakReferenceOfT.cs
index b8195df6d9..0972e5fb9e 100644
--- a/src/mscorlib/src/System/WeakReferenceOfT.cs
+++ b/src/mscorlib/src/System/WeakReferenceOfT.cs
@@ -46,7 +46,7 @@ namespace System
internal WeakReference(SerializationInfo info, StreamingContext context)
{
if (info == null) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -81,10 +81,8 @@ namespace System
private extern T Target
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
set;
}
@@ -95,14 +93,12 @@ 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) {
- throw new ArgumentNullException("info");
+ throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -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();
}
}
diff --git a/src/mscorlib/src/System/_LocalDataStore.cs b/src/mscorlib/src/System/_LocalDataStore.cs
index a3a312f104..a1fa488076 100644
--- a/src/mscorlib/src/System/_LocalDataStore.cs
+++ b/src/mscorlib/src/System/_LocalDataStore.cs
@@ -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);
diff --git a/src/mscorlib/src/System/_LocalDataStoreMgr.cs b/src/mscorlib/src/System/_LocalDataStoreMgr.cs
index 615413848d..8f60d6f754 100644
--- a/src/mscorlib/src/System/_LocalDataStoreMgr.cs
+++ b/src/mscorlib/src/System/_LocalDataStoreMgr.cs
@@ -58,7 +58,7 @@ namespace System {
get
{
return m_cookie;
- }
+ }
}
// Release the slot reserved by this object when this object goes away.
@@ -70,8 +70,8 @@ namespace System {
int slot = m_slot;
- // Mark the slot as free.
- m_slot = -1;
+ // Mark the slot as free.
+ m_slot = -1;
mgr.FreeDataSlot(slot, m_cookie);
}
@@ -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;
diff --git a/src/mscorlib/src/System/__ComObject.cs b/src/mscorlib/src/System/__ComObject.cs
index a5923707b6..9f9bac6084 100644
--- a/src/mscorlib/src/System/__ComObject.cs
+++ b/src/mscorlib/src/System/__ComObject.cs
@@ -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.
diff --git a/src/mscorlib/src/System/cominterfaces.cs b/src/mscorlib/src/System/cominterfaces.cs
index 7d3620a22d..a83943d586 100644
--- a/src/mscorlib/src/System/cominterfaces.cs
+++ b/src/mscorlib/src/System/cominterfaces.cs
@@ -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
}
}
diff --git a/src/mscorlib/src/System/mda.cs b/src/mscorlib/src/System/mda.cs
index 089039c73c..f750e99a8b 100644
--- a/src/mscorlib/src/System/mda.cs
+++ b/src/mscorlib/src/System/mda.cs
@@ -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);
}
diff --git a/src/mscorlib/src/mscorlib.Friends.cs b/src/mscorlib/src/mscorlib.Friends.cs
index fc8ed53fff..0e55301656 100644
--- a/src/mscorlib/src/mscorlib.Friends.cs
+++ b/src/mscorlib/src/mscorlib.Friends.cs
@@ -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.
diff --git a/src/mscorlib/src/mscorlib.txt b/src/mscorlib/src/mscorlib.txt
deleted file mode 100644
index 01d593b778..0000000000
--- a/src/mscorlib/src/mscorlib.txt
+++ /dev/null
@@ -1,3494 +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.
-
-; These are the managed resources for mscorlib.dll.
-; See those first three bytes in the file? This is in UTF-8. Leave the
-; Unicode byte order mark (U+FEFF) written in UTF-8 at the start of this file.
-
-; For resource info, see the ResourceManager documentation and the ResGen tool,
-; which is a managed app using ResourceWriter.
-; ResGen now supports limited preprocessing of txt files, you can use
-; #if SYMBOL and #if !SYMBOL to control what sets of resources are included in
-; the resulting resources.
-
-; The naming scheme is: [Namespace.] ExceptionName _ Reason
-; We'll suppress "System." where possible.
-; Examples:
-; Argument_Null
-; Reflection.TargetInvokation_someReason
-
-; Usage Notes:
-; * Keep exceptions in alphabetical order by package
-; * A single space may exist on either side of the equal sign.
-; * Follow the naming conventions.
-; * Any lines starting with a '#' or ';' are ignored
-; * Equal signs aren't legal characters for keys, but may occur in values.
-; * Correctly punctuate all sentences. Most resources should end in a period.
-; Remember, your mother will probably read some of these messages.
-; * You may use " (quote), \n and \t. Use \\ for a single '\' character.
-; * String inserts work. i.e., BadNumber_File = Wrong number in file "{0}".
-
-; Real words, used by code like Environment.StackTrace
-#if INCLUDE_RUNTIME
-Word_At = at
-StackTrace_InFileLineNumber = in {0}:line {1}
-UnknownError_Num = Unknown error "{0}".
-AllocatedFrom = Allocated from:
-
-; Note this one is special, used as a divider between stack traces!
-Exception_EndOfInnerExceptionStack = --- End of inner exception stack trace ---
-Exception_WasThrown = Exception of type '{0}' was thrown.
-
-; The following are used in the implementation of ExceptionDispatchInfo
-Exception_EndStackTraceFromPreviousThrow = --- End of stack trace from previous location where exception was thrown ---
-
-Arg_ParamName_Name = Parameter name: {0}
-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
-AssumptionFailed = Assumption failed.
-AssumptionFailed_Cnd = Assumption failed: {0}
-AssertionFailed = Assertion failed.
-AssertionFailed_Cnd = Assertion failed: {0}
-PreconditionFailed = Precondition failed.
-PreconditionFailed_Cnd = Precondition failed: {0}
-PostconditionFailed = Postcondition failed.
-PostconditionFailed_Cnd = Postcondition failed: {0}
-PostconditionOnExceptionFailed = Postcondition failed after throwing an exception.
-PostconditionOnExceptionFailed_Cnd = Postcondition failed after throwing an exception: {0}
-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.
-IdentityReference_MustBeIdentityReference = The targetType parameter must be of IdentityReference type.
-IdentityReference_AccountNameTooLong = Account name is too long.
-IdentityReference_DomainNameTooLong = Domain name is too long.
-IdentityReference_InvalidNumberOfSubauthorities = The number of sub-authorities must not exceed {0}.
-IdentityReference_IdentifierAuthorityTooLarge = The size of the identifier authority must not exceed 6 bytes.
-IdentityReference_InvalidSidRevision = SIDs with revision other than '1' are not supported.
-IdentityReference_CannotCreateLogonIdsSid = Well-known SIDs of type LogonIdsSid cannot be created.
-IdentityReference_DomainSidRequired = The domainSid parameter must be specified for creating well-known SID of type {0}.
-IdentityReference_NotAWindowsDomain = The domainSid parameter is not a valid Windows domain SID.
-#endif // FEATURE_IDENTITY_REFERENCE
-
-; AccessException
-Acc_CreateGeneric = Cannot create a type for which Type.ContainsGenericParameters is true.
-Acc_CreateAbst = Cannot create an abstract class.
-Acc_CreateInterface = Cannot create an instance of an interface.
-Acc_NotClassInit = Type initializer was not callable.
-Acc_CreateGenericEx = Cannot create an instance of {0} because Type.ContainsGenericParameters is true.
-Acc_CreateArgIterator = Cannot dynamically create an instance of ArgIterator.
-Acc_CreateAbstEx = Cannot create an instance of {0} because it is an abstract class.
-Acc_CreateInterfaceEx = Cannot create an instance of {0} because it is an interface.
-Acc_CreateVoid = Cannot dynamically create an instance of System.Void.
-Acc_ReadOnly = Cannot set a constant field.
-Acc_RvaStatic = SkipVerification permission is needed to modify an image-based (RVA) static field.
-Access_Void = Cannot create an instance of void.
-
-; ArgumentException
-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.
-Argument_ApplicationTrustShouldHaveIdentity = An ApplicationTrust must have an application identity before it can be persisted.
-Argument_ConversionOverflow = Conversion buffer overflow.
-Argument_CodepageNotSupported = {0} is not a supported code page.
-Argument_CultureNotSupported = Culture is not supported.
-Argument_CultureInvalidIdentifier = {0} is an invalid culture identifier.
-Argument_OneOfCulturesNotSupported = Culture name {0} or {1} is not supported.
-Argument_CultureIetfNotSupported = Culture IETF Name {0} is not a recognized IETF name.
-Argument_CultureIsNeutral = Culture ID {0} (0x{0:X4}) is a neutral culture; a region cannot be created from it.
-Argument_InvalidNeutralRegionName = The region name {0} should not correspond to neutral culture; a specific culture name is required.
-Argument_InvalidGenericInstArray = Generic arguments must be provided for each generic parameter and each generic argument must be a RuntimeType.
-Argument_GenericArgsCount = The number of generic arguments provided doesn't equal the arity of the generic type definition.
-Argument_CultureInvalidFormat = Culture '{0}' is a neutral culture. It cannot be used in formatting and parsing and therefore cannot be set as the thread's current culture.
-Argument_CompareOptionOrdinal = CompareOption.Ordinal cannot be used with other options.
-Argument_CustomCultureCannotBePassedByNumber = Customized cultures cannot be passed by LCID, only by name.
-Argument_EncodingConversionOverflowChars = The output char buffer is too small to contain the decoded characters, encoding '{0}' fallback '{1}'.
-Argument_EncodingConversionOverflowBytes = The output byte buffer is too small to contain the encoded data, encoding '{0}' fallback '{1}'.
-Argument_EncoderFallbackNotEmpty = Must complete Convert() operation or call Encoder.Reset() before calling GetBytes() or GetByteCount(). Encoder '{0}' fallback '{1}'.
-Argument_EmptyFileName = Empty file name is not legal.
-Argument_EmptyPath = Empty path name is not legal.
-Argument_EmptyName = Empty name is not legal.
-Argument_ImplementIComparable = At least one object must implement IComparable.
-Argument_InvalidType = The type of arguments passed into generic comparer methods is invalid.
-Argument_InvalidTypeForCA=Cannot build type parameter for custom attribute with a type that does not support the AssemblyQualifiedName property. The type instance supplied was of type '{0}'.
-Argument_IllegalEnvVarName = Environment variable name cannot contain equal character.
-Argument_IllegalAppId = Application identity does not have same number of components as manifest paths.
-Argument_IllegalAppBase = The application base specified is not valid.
-Argument_UnableToParseManifest = Unexpected error while parsing the specified manifest.
-Argument_IllegalAppIdMismatch = Application identity does not match identities in manifests.
-Argument_InvalidAppId = Invalid identity: no deployment or application identity specified.
-Argument_InvalidGenericArg = The generic type parameter was not valid
-Argument_InvalidArrayLength = Length of the array must be {0}.
-Argument_InvalidArrayType = Target array type is not compatible with the type of items in the collection.
-Argument_InvalidAppendMode = Append access can be requested only in write-only mode.
-Argument_InvalidEnumValue = The value '{0}' is not valid for this usage of the type {1}.
-Argument_EnumIsNotIntOrShort = The underlying type of enum argument must be Int32 or Int16.
-Argument_InvalidEnum = The Enum type should contain one and only one instance field.
-Argument_InvalidKeyStore = '{0}' is not a valid KeyStore name.
-Argument_InvalidFileMode&AccessCombo = Combining FileMode: {0} with FileAccess: {1} is invalid.
-Argument_InvalidFileMode&RightsCombo = Combining FileMode: {0} with FileSystemRights: {1} is invalid.
-Argument_InvalidFileModeTruncate&RightsCombo = Combining FileMode: {0} with FileSystemRights: {1} is invalid. FileMode.Truncate is valid only when used with FileSystemRights.Write.
-Argument_InvalidFlag = Value of flags is invalid.
-Argument_InvalidAnyFlag = No flags can be set.
-Argument_InvalidHandle = The handle is invalid.
-Argument_InvalidRegistryKeyPermissionCheck = The specified RegistryKeyPermissionCheck value is invalid.
-Argument_InvalidRegistryOptionsCheck = The specified RegistryOptions value is invalid.
-Argument_InvalidRegistryViewCheck = The specified RegistryView value is invalid.
-Argument_InvalidSubPath = The directory specified, '{0}', is not a subdirectory of '{1}'.
-Argument_NoRegionInvariantCulture = There is no region associated with the Invariant Culture (Culture ID: 0x7F).
-Argument_ResultCalendarRange = The result is out of the supported range for this calendar. The result should be between {0} (Gregorian date) and {1} (Gregorian date), inclusive.
-Argument_ResultIslamicCalendarRange = The date is out of the supported range for the Islamic calendar. The date should be greater than July 18th, 622 AD (Gregorian date).
-Argument_NeverValidGenericArgument = The type '{0}' may not be used as a type argument.
-Argument_NotEnoughGenArguments = The type or method has {1} generic parameter(s), but {0} generic argument(s) were provided. A generic argument must be provided for each generic parameter.
-Argument_NullFullTrustAssembly = A null StrongName was found in the full trust assembly list.
-Argument_GenConstraintViolation = GenericArguments[{0}], '{1}', on '{2}' violates the constraint of type '{3}'.
-Argument_InvalidToken = Token {0:x} is not valid in the scope of module {1}.
-Argument_InvalidTypeToken = Token {0:x} is not a valid Type token.
-Argument_ResolveType = Token {0:x} is not a valid Type token in the scope of module {1}.
-Argument_ResolveMethod = Token {0:x} is not a valid MethodBase token in the scope of module {1}.
-Argument_ResolveField = Token {0:x} is not a valid FieldInfo token in the scope of module {1}.
-Argument_ResolveMember = Token {0:x} is not a valid MemberInfo token in the scope of module {1}.
-Argument_ResolveString = Token {0:x} is not a valid string token in the scope of module {1}.
-Argument_ResolveModuleType = Token {0} resolves to the special module type representing this module.
-Argument_ResolveMethodHandle = Type handle '{0}' and method handle with declaring type '{1}' are incompatible. Get RuntimeMethodHandle and declaring RuntimeTypeHandle off the same MethodBase.
-Argument_ResolveFieldHandle = Type handle '{0}' and field handle with declaring type '{1}' are incompatible. Get RuntimeFieldHandle and declaring RuntimeTypeHandle off the same FieldInfo.
-Argument_ResourceScopeWrongDirection = Resource type in the ResourceScope enum is going from a more restrictive resource type to a more general one. From: "{0}" To: "{1}"
-Argument_BadResourceScopeTypeBits = Unknown value for the ResourceScope: {0} Too many resource type bits may be set.
-Argument_BadResourceScopeVisibilityBits = Unknown value for the ResourceScope: {0} Too many resource visibility bits may be set.
-Argument_WaitHandleNameTooLong = The name can be no more than 260 characters in length.
-Argument_EnumTypeDoesNotMatch = The argument type, '{0}', is not the same as the enum type '{1}'.
-InvalidOperation_MethodBuilderBaked = The signature of the MethodBuilder can no longer be modified because an operation on the MethodBuilder caused the methodDef token to be created. For example, a call to SetCustomAttribute requires the methodDef token to emit the CustomAttribute token.
-InvalidOperation_GenericParametersAlreadySet = The generic parameters are already defined on this MethodBuilder.
-Arg_AccessException = Cannot access member.
-Arg_AppDomainUnloadedException = Attempted to access an unloaded AppDomain.
-Arg_ApplicationException = Error in the application.
-Arg_ArgumentOutOfRangeException = Specified argument was out of the range of valid values.
-Arg_ArithmeticException = Overflow or underflow in the arithmetic operation.
-Arg_ArrayLengthsDiffer = Array lengths must be the same.
-Arg_ArrayPlusOffTooSmall = Destination array is not long enough to copy all the items in the collection. Check array index and length.
-Arg_ArrayTypeMismatchException = Attempted to access an element as a type incompatible with the array.
-Arg_BadImageFormatException = Format of the executable (.exe) or library (.dll) is invalid.
-Argument_BadImageFormatExceptionResolve = A BadImageFormatException has been thrown while parsing the signature. This is likely due to lack of a generic context. Ensure genericTypeArguments and genericMethodArguments are provided and contain enough context.
-Arg_BufferTooSmall = Not enough space available in the buffer.
-Arg_CATypeResolutionFailed = Failed to resolve type from string "{0}" which was embedded in custom attribute blob.
-Arg_CannotHaveNegativeValue = String cannot contain a minus sign if the base is not 10.
-Arg_CannotUnloadAppDomainException = Attempt to unload the AppDomain failed.
-Arg_CannotMixComparisonInfrastructure = The usage of IKeyComparer and IHashCodeProvider/IComparer interfaces cannot be mixed; use one or the other.
-Arg_ContextMarshalException = Attempted to marshal an object across a context boundary.
-Arg_DataMisalignedException = A datatype misalignment was detected in a load or store instruction.
-Arg_DevicesNotSupported = FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of "\\\\.\\" in the path.
-Arg_DuplicateWaitObjectException = Duplicate objects in argument.
-Arg_EntryPointNotFoundException = Entry point was not found.
-Arg_DllNotFoundException = Dll was not found.
-Arg_ExecutionEngineException = Internal error in the runtime.
-Arg_FieldAccessException = Attempted to access a field that is not accessible by the caller.
-Arg_FileIsDirectory_Name = The target file "{0}" is a directory, not a file.
-Arg_FormatException = One of the identified items was in an invalid format.
-Arg_IndexOutOfRangeException = Index was outside the bounds of the array.
-Arg_InsufficientExecutionStackException = Insufficient stack to continue executing the program safely. This can happen from having too many functions on the call stack or function on the stack using too much stack space.
-Arg_InvalidCastException = Specified cast is not valid.
-Arg_InvalidOperationException = Operation is not valid due to the current state of the object.
-Arg_CorruptedCustomCultureFile = The file of the custom culture {0} is corrupt. Try to unregister this culture.
-Arg_InvokeMember = InvokeMember can be used only for COM objects.
-Arg_InvalidNeutralResourcesLanguage_Asm_Culture = The NeutralResourcesLanguageAttribute on the assembly "{0}" specifies an invalid culture name: "{1}".
-Arg_InvalidNeutralResourcesLanguage_FallbackLoc = The NeutralResourcesLanguageAttribute specifies an invalid or unrecognized ultimate resource fallback location: "{0}".
-Arg_InvalidSatelliteContract_Asm_Ver = Satellite contract version attribute on the assembly '{0}' specifies an invalid version: {1}.
-Arg_MethodAccessException = Attempt to access the method failed.
-Arg_MethodAccessException_WithMethodName = Attempt to access the method "{0}" on type "{1}" failed.
-Arg_MethodAccessException_WithCaller = Attempt by security transparent method '{0}' to access security critical method '{1}' failed.
-Arg_MissingFieldException = Attempted to access a non-existing field.
-Arg_MissingMemberException = Attempted to access a missing member.
-Arg_MissingMethodException = Attempted to access a missing method.
-Arg_MulticastNotSupportedException = Attempted to add multiple callbacks to a delegate that does not support multicast.
-Arg_NotFiniteNumberException = Number encountered was not a finite quantity.
-Arg_NotSupportedException = Specified method is not supported.
-Arg_UnboundGenParam = Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.
-Arg_UnboundGenField = Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
-Arg_NotGenericParameter = Method may only be called on a Type for which Type.IsGenericParameter is true.
-Arg_GenericParameter = Method must be called on a Type for which Type.IsGenericParameter is false.
-Arg_NotGenericTypeDefinition = {0} is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.
-Arg_NotGenericMethodDefinition = {0} is not a GenericMethodDefinition. MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.
-Arg_BadLiteralFormat = Encountered an invalid type for a default value.
-Arg_MissingActivationArguments = The AppDomainSetup must specify the activation arguments for this call.
-Argument_BadParameterTypeForCAB = Cannot emit a CustomAttribute with argument of type {0}.
-Argument_InvalidMemberForNamedArgument = The member must be either a field or a property.
-Argument_InvalidTypeName = The name of the type is invalid.
-
-; Note - don't change the NullReferenceException default message. This was
-; negotiated carefully with the VB team to avoid saying "null" or "nothing".
-Arg_NullReferenceException = Object reference not set to an instance of an object.
-
-Arg_AccessViolationException = Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
-Arg_OverflowException = Arithmetic operation resulted in an overflow.
-Arg_PathGlobalRoot = Paths that begin with \\\\?\\GlobalRoot are internal to the kernel and should not be opened by managed applications.
-Arg_PathIllegal = The path is not of a legal form.
-Arg_PathIllegalUNC = The UNC path should be of the form \\\\server\\share.
-Arg_RankException = Attempted to operate on an array with the incorrect number of dimensions.
-Arg_RankMultiDimNotSupported = Only single dimensional arrays are supported for the requested action.
-Arg_NonZeroLowerBound = The lower bound of target array must be zero.
-Arg_RegSubKeyValueAbsent = No value exists with that name.
-Arg_ResourceFileUnsupportedVersion = The ResourceReader class does not know how to read this version of .resources files. Expected version: {0} This file: {1}
-Arg_ResourceNameNotExist = The specified resource name "{0}" does not exist in the resource file.
-Arg_SecurityException = Security error.
-Arg_SerializationException = Serialization error.
-Arg_StackOverflowException = Operation caused a stack overflow.
-Arg_SurrogatesNotAllowedAsSingleChar = Unicode surrogate characters must be written out as pairs together in the same call, not individually. Consider passing in a character array instead.
-Arg_SynchronizationLockException = Object synchronization method was called from an unsynchronized block of code.
-Arg_RWLockRestoreException = ReaderWriterLock.RestoreLock was called without releasing all locks acquired since the call to ReleaseLock.
-Arg_SystemException = System error.
-Arg_TimeoutException = The operation has timed out.
-Arg_UnauthorizedAccessException = Attempted to perform an unauthorized operation.
-Arg_ArgumentException = Value does not fall within the expected range.
-Arg_DirectoryNotFoundException = Attempted to access a path that is not on the disk.
-Arg_DriveNotFoundException = Attempted to access a drive that is not available.
-Arg_EndOfStreamException = Attempted to read past the end of the stream.
-Arg_HexStyleNotSupported = The number style AllowHexSpecifier is not supported on floating point data types.
-Arg_IOException = I/O error occurred.
-Arg_InvalidHexStyle = With the AllowHexSpecifier bit set in the enum bit field, the only other valid bits that can be combined into the enum value must be a subset of those in HexNumber.
-Arg_KeyNotFound = The given key was not present in the dictionary.
-Argument_InvalidNumberStyles = An undefined NumberStyles value is being used.
-Argument_InvalidDateTimeStyles = An undefined DateTimeStyles value is being used.
-Argument_InvalidTimeSpanStyles = An undefined TimeSpanStyles value is being used.
-Argument_DateTimeOffsetInvalidDateTimeStyles = The DateTimeStyles value 'NoCurrentDateDefault' is not allowed when parsing DateTimeOffset.
-Argument_NativeResourceAlreadyDefined = Native resource has already been defined.
-Argument_BadObjRef = Invalid ObjRef provided to '{0}'.
-Argument_InvalidCultureName = Culture name '{0}' is not supported.
-Argument_NameTooLong = The name '{0}' is too long to be a Culture or Region name, which is limited to {1} characters.
-Argument_NameContainsInvalidCharacters = The name '{0}' contains characters that are not valid for a Culture or Region.
-Argument_InvalidRegionName = Region name '{0}' is not supported.
-Argument_CannotCreateTypedReference = Cannot use function evaluation to create a TypedReference object.
-Arg_ArrayZeroError = Array must not be of length zero.
-Arg_BogusIComparer = Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.
-Arg_CreatInstAccess = Cannot specify both CreateInstance and another access type.
-Arg_CryptographyException = Error occurred during a cryptographic operation.
-Arg_DateTimeRange = Combination of arguments to the DateTime constructor is out of the legal range.
-Arg_DecBitCtor = Decimal byte array constructor requires an array of length four containing valid decimal bytes.
-Arg_DlgtTargMeth = Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
-Arg_DlgtTypeMis = Delegates must be of the same type.
-Arg_DlgtNullInst = Delegate to an instance method cannot have null 'this'.
-Arg_DllInitFailure = One machine may not have remote administration enabled, or both machines may not be running the remote registry service.
-Arg_EmptyArray = Array may not be empty.
-Arg_EmptyOrNullArray = Array may not be empty or null.
-Arg_EmptyCollection = Collection must not be empty.
-Arg_EmptyOrNullString = String may not be empty or null.
-Argument_ItemNotExist = The specified item does not exist in this KeyedCollection.
-Argument_EncodingNotSupported = '{0}' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
-Argument_FallbackBufferNotEmpty = Cannot change fallback when buffer is not empty. Previous Convert() call left data in the fallback buffer.
-Argument_InvalidCodePageConversionIndex = Unable to translate Unicode character \\u{0:X4} at index {1} to specified code page.
-Argument_InvalidCodePageBytesIndex = Unable to translate bytes {0} at index {1} from specified code page to Unicode.
-Argument_RecursiveFallback = Recursive fallback not allowed for character \\u{0:X4}.
-Argument_RecursiveFallbackBytes = Recursive fallback not allowed for bytes {0}.
-Arg_EnumAndObjectMustBeSameType = Object must be the same type as the enum. The type passed in was '{0}'; the enum type was '{1}'.
-Arg_EnumIllegalVal = Illegal enum value: {0}.
-Arg_EnumNotSingleFlag = Must set exactly one flag.
-Arg_EnumAtLeastOneFlag = Must set at least one flag.
-Arg_EnumUnderlyingTypeAndObjectMustBeSameType = Enum underlying type and the object must be same type or object must be a String. Type passed in was '{0}'; the enum underlying type was '{1}'.
-Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType = Enum underlying type and the object must be same type or object. Type passed in was '{0}'; the enum underlying type was '{1}'.
-Arg_EnumMustHaveUnderlyingValueField = All enums must have an underlying value__ field.
-Arg_COMAccess = Must specify property Set or Get or method call for a COM Object.
-Arg_COMPropSetPut = Only one of the following binding flags can be set: BindingFlags.SetProperty, BindingFlags.PutDispProperty, BindingFlags.PutRefDispProperty.
-Arg_FldSetGet = Cannot specify both Get and Set on a field.
-Arg_PropSetGet = Cannot specify both Get and Set on a property.
-Arg_CannotBeNaN = TimeSpan does not accept floating point Not-a-Number values.
-Arg_FldGetPropSet = Cannot specify both GetField and SetProperty.
-Arg_FldSetPropGet = Cannot specify both SetField and GetProperty.
-Arg_FldSetInvoke = Cannot specify Set on a Field and Invoke on a method.
-Arg_FldGetArgErr = No arguments can be provided to Get a field value.
-Arg_FldSetArgErr = Only the field value can be specified to set a field value.
-Arg_GetMethNotFnd = Property Get method was not found.
-Arg_GuidArrayCtor = Byte array for GUID must be exactly {0} bytes long.
-Arg_HandleNotAsync = Handle does not support asynchronous operations. The parameters to the FileStream constructor may need to be changed to indicate that the handle was opened synchronously (that is, it was not opened for overlapped I/O).
-Arg_HandleNotSync = Handle does not support synchronous operations. The parameters to the FileStream constructor may need to be changed to indicate that the handle was opened asynchronously (that is, it was opened explicitly for overlapped I/O).
-Arg_HTCapacityOverflow = Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.
-Arg_IndexMustBeInt = All indexes must be of type Int32.
-Arg_InvalidConsoleColor = The ConsoleColor enum value was not defined on that enum. Please use a defined color from the enum.
-Arg_InvalidFileAttrs = Invalid File or Directory attributes value.
-Arg_InvalidHandle = Invalid handle.
-Arg_InvalidTypeInSignature = The signature Type array contains some invalid type (i.e. null, void)
-Arg_InvalidTypeInRetType = The return Type contains some invalid type (i.e. null, ByRef)
-Arg_EHClauseNotFilter = This ExceptionHandlingClause is not a filter.
-Arg_EHClauseNotClause = This ExceptionHandlingClause is not a clause.
-Arg_ReflectionOnlyCA = It is illegal to reflect on the custom attributes of a Type loaded via ReflectionOnlyGetType (see Assembly.ReflectionOnly) -- use CustomAttributeData instead.
-Arg_ReflectionOnlyInvoke = It is illegal to invoke a method on a Type loaded via ReflectionOnlyGetType.
-Arg_ReflectionOnlyField = It is illegal to get or set the value on a field on a Type loaded via ReflectionOnlyGetType.
-Arg_MemberInfoNullModule = The Module object containing the member cannot be null.
-Arg_ParameterInfoNullMember = The MemberInfo object defining the parameter cannot be null.
-Arg_ParameterInfoNullModule = The Module object containing the parameter cannot be null.
-Arg_AssemblyNullModule = The manifest module of the assembly cannot be null.
-Arg_LongerThanSrcArray = Source array was not long enough. Check srcIndex and length, and the array's lower bounds.
-Arg_LongerThanDestArray = Destination array was not long enough. Check destIndex and length, and the array's lower bounds.
-Arg_LowerBoundsMustMatch = The arrays' lower bounds must be identical.
-Arg_MustBeBoolean = Object must be of type Boolean.
-Arg_MustBeByte = Object must be of type Byte.
-Arg_MustBeChar = Object must be of type Char.
-Arg_MustBeDateTime = Object must be of type DateTime.
-Arg_MustBeDateTimeOffset = Object must be of type DateTimeOffset.
-Arg_MustBeDecimal = Object must be of type Decimal.
-Arg_MustBeDelegate = Type must derive from Delegate.
-Arg_MustBeDouble = Object must be of type Double.
-Arg_MustBeDriveLetterOrRootDir = Object must be a root directory ("C:\\") or a drive letter ("C").
-Arg_MustBeEnum = Type provided must be an Enum.
-Arg_MustBeEnumBaseTypeOrEnum = The value passed in must be an enum base or an underlying type for an enum, such as an Int32.
-Arg_MustBeGuid = Object must be of type GUID.
-Arg_MustBeIdentityReferenceType = Type must be an IdentityReference, such as NTAccount or SecurityIdentifier.
-Arg_MustBeInterface = Type passed must be an interface.
-Arg_MustBeInt16 = Object must be of type Int16.
-Arg_MustBeInt32 = Object must be of type Int32.
-Arg_MustBeInt64 = Object must be of type Int64.
-Arg_MustBePrimArray = Object must be an array of primitives.
-Arg_MustBePointer = Type must be a Pointer.
-Arg_MustBeStatic = Method must be a static method.
-Arg_MustBeString = Object must be of type String.
-Arg_MustBeStringPtrNotAtom = The pointer passed in as a String must not be in the bottom 64K of the process's address space.
-Arg_MustBeSByte = Object must be of type SByte.
-Arg_MustBeSingle = Object must be of type Single.
-Arg_MustBeTimeSpan = Object must be of type TimeSpan.
-Arg_MustBeType = Type must be a type provided by the runtime.
-Arg_MustBeUInt16 = Object must be of type UInt16.
-Arg_MustBeUInt32 = Object must be of type UInt32.
-Arg_MustBeUInt64 = Object must be of type UInt64.
-Arg_MustBeVersion = Object must be of type Version.
-Arg_MustBeTrue = Argument must be true.
-Arg_MustAllBeRuntimeType = At least one type argument is not a runtime type.
-Arg_NamedParamNull = Named parameter value must not be null.
-Arg_NamedParamTooBig = Named parameter array cannot be bigger than argument array.
-Arg_Need1DArray = Array was not a one-dimensional array.
-Arg_Need2DArray = Array was not a two-dimensional array.
-Arg_Need3DArray = Array was not a three-dimensional array.
-Arg_NeedAtLeast1Rank = Must provide at least one rank.
-Arg_NoDefCTor = No parameterless constructor defined for this object.
-Arg_BitArrayTypeUnsupported = Only supported array types for CopyTo on BitArrays are Boolean[], Int32[] and Byte[].
-Arg_DivideByZero = Attempted to divide by zero.
-Arg_NoAccessSpec = Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty).
-Arg_NoStaticVirtual = Method cannot be both static and virtual.
-Arg_NotFoundIFace = Interface not found.
-Arg_ObjObjEx = Object of type '{0}' cannot be converted to type '{1}'.
-Arg_ObjObj = Object type cannot be converted to target type.
-Arg_FieldDeclTarget = Field '{0}' defined on type '{1}' is not a field on the target object which is of type '{2}'.
-Arg_OleAutDateInvalid = Not a legal OleAut date.
-Arg_OleAutDateScale = OleAut date did not convert to a DateTime correctly.
-Arg_PlatformNotSupported = Operation is not supported on this platform.
-Arg_PlatformSecureString = SecureString is only supported on Windows 2000 SP3 and higher platforms.
-Arg_ParmCnt = Parameter count mismatch.
-Arg_ParmArraySize = Must specify one or more parameters.
-Arg_Path2IsRooted = Second path fragment must not be a drive or UNC name.
-Arg_PathIsVolume = Path must not be a drive.
-Arg_PrimWiden = Cannot widen from source type to target type either because the source type is a not a primitive type or the conversion cannot be accomplished.
-Arg_NullIndex = Arrays indexes must be set to an object instance.
-Arg_VarMissNull = Missing parameter does not have a default value.
-Arg_PropSetInvoke = Cannot specify Set on a property and Invoke on a method.
-Arg_PropNotFound = Could not find the specified property.
-Arg_RankIndices = Indices length does not match the array rank.
-Arg_RanksAndBounds = Number of lengths and lowerBounds must match.
-Arg_RegSubKeyAbsent = Cannot delete a subkey tree because the subkey does not exist.
-Arg_RemoveArgNotFound = Cannot remove the specified item because it was not found in the specified Collection.
-Arg_RegKeyDelHive = Cannot delete a registry hive's subtree.
-Arg_RegKeyNoRemoteConnect = No remote connection to '{0}' while trying to read the registry.
-Arg_RegKeyOutOfRange = Registry HKEY was out of the legal range.
-Arg_RegKeyNotFound = The specified registry key does not exist.
-Arg_RegKeyStrLenBug = Registry key names should not be greater than 255 characters.
-Arg_RegValStrLenBug = Registry value names should not be greater than 16,383 characters.
-Arg_RegBadKeyKind = The specified RegistryValueKind is an invalid value.
-Arg_RegGetOverflowBug = RegistryKey.GetValue does not allow a String that has a length greater than Int32.MaxValue.
-Arg_RegSetMismatchedKind = The type of the value object did not match the specified RegistryValueKind or the object could not be properly converted.
-Arg_RegSetBadArrType = RegistryKey.SetValue does not support arrays of type '{0}'. Only Byte[] and String[] are supported.
-Arg_RegSetStrArrNull = RegistryKey.SetValue does not allow a String[] that contains a null String reference.
-Arg_RegInvalidKeyName = Registry key name must start with a valid base key name.
-Arg_ResMgrNotResSet = Type parameter must refer to a subclass of ResourceSet.
-Arg_SetMethNotFnd = Property set method not found.
-Arg_TypeRefPrimitve = TypedReferences cannot be redefined as primitives.
-Arg_UnknownTypeCode = Unknown TypeCode value.
-Arg_VersionString = Version string portion was too short or too long.
-Arg_NoITypeInfo = Specified TypeInfo was invalid because it did not support the ITypeInfo interface.
-Arg_NoITypeLib = Specified TypeLib was invalid because it did not support the ITypeLib interface.
-Arg_NoImporterCallback = Specified type library importer callback was invalid because it did not support the ITypeLibImporterNotifySink interface.
-Arg_ImporterLoadFailure = The type library importer encountered an error during type verification. Try importing without class members.
-Arg_InvalidBase = Invalid Base.
-Arg_EnumValueNotFound = Requested value '{0}' was not found.
-Arg_EnumLitValueNotFound = Literal value was not found.
-Arg_MustContainEnumInfo = Must specify valid information for parsing in the string.
-Arg_InvalidSearchPattern = Search pattern cannot contain ".." to move up directories and can be contained only internally in file/directory names, as in "a..b".
-Arg_NegativeArgCount = Argument count must not be negative.
-Arg_InvalidAccessEntry = Specified access entry is invalid because it is unrestricted. The global flags should be specified instead.
-Arg_InvalidFileName = Specified file name was invalid.
-Arg_InvalidFileExtension = Specified file extension was not a valid extension.
-Arg_COMException = Error HRESULT E_FAIL has been returned from a call to a COM component.
-Arg_ExternalException = External component has thrown an exception.
-Arg_InvalidComObjectException = Attempt has been made to use a COM object that does not have a backing class factory.
-Arg_InvalidOleVariantTypeException = Specified OLE variant was invalid.
-Arg_MarshalDirectiveException = Marshaling directives are invalid.
-Arg_MarshalAsAnyRestriction = AsAny cannot be used on return types, ByRef parameters, ArrayWithOffset, or parameters passed from unmanaged to managed.
-Arg_NDirectBadObject = No PInvoke conversion exists for value passed to Object-typed parameter.
-Arg_SafeArrayTypeMismatchException = Specified array was not of the expected type.
-Arg_VTableCallsNotSupportedException = Attempted to make an early bound call on a COM dispatch-only interface.
-Arg_SafeArrayRankMismatchException = Specified array was not of the expected rank.
-Arg_AmbiguousMatchException = Ambiguous match found.
-Arg_CustomAttributeFormatException = Binary format of the specified custom attribute was invalid.
-Arg_InvalidFilterCriteriaException = Specified filter criteria was invalid.
-Arg_TypeLoadNullStr = A null or zero length string does not represent a valid Type.
-Arg_TargetInvocationException = Exception has been thrown by the target of an invocation.
-Arg_TargetParameterCountException = Number of parameters specified does not match the expected number.
-Arg_TypeAccessException = Attempt to access the type failed.
-Arg_TypeLoadException = Failure has occurred while loading a type.
-Arg_TypeUnloadedException = Type had been unloaded.
-Arg_ThreadStateException = Thread was in an invalid state for the operation being executed.
-Arg_ThreadStartException = Thread failed to start.
-Arg_WrongAsyncResult = IAsyncResult object did not come from the corresponding async method on this type.
-Arg_WrongType = The value "{0}" is not of type "{1}" and cannot be used in this generic collection.
-Argument_InvalidArgumentForComparison = Type of argument is not compatible with the generic comparer.
-Argument_ALSInvalidCapacity = Specified capacity must not be less than the current capacity.
-Argument_ALSInvalidSlot = Specified slot number was invalid.
-Argument_IdnIllegalName = Decoded string is not a valid IDN name.
-Argument_IdnBadBidi = Left to right characters may not be mixed with right to left characters in IDN labels.
-Argument_IdnBadLabelSize = IDN labels must be between 1 and 63 characters long.
-Argument_IdnBadNameSize = IDN names must be between 1 and {0} characters long.
-Argument_IdnBadPunycode = Invalid IDN encoded string.
-Argument_IdnBadStd3 = Label contains character '{0}' not allowed with UseStd3AsciiRules
-Arg_InvalidANSIString = The ANSI string passed in could not be converted from the default ANSI code page to Unicode.
-Arg_InvalidUTF8String = The UTF8 string passed in could not be converted to Unicode.
-Argument_InvalidCharSequence = Invalid Unicode code point found at index {0}.
-Argument_InvalidCharSequenceNoIndex = String contains invalid Unicode code points.
-Argument_InvalidCalendar = Not a valid calendar for the given culture.
-Argument_InvalidNormalizationForm = Invalid or unsupported normalization form.
-Argument_InvalidPathChars = Illegal characters in path.
-Argument_InvalidOffLen = Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
-Argument_InvalidSeekOrigin = Invalid seek origin.
-Argument_SeekOverflow = The specified seek offset '{0}' would result in a negative Stream position.
-Argument_InvalidUnity = Invalid Unity type.
-Argument_LongEnvVarName = Environment variable name cannot contain 1024 or more characters.
-Argument_LongEnvVarValue = Environment variable name or value is too long.
-Argument_StringFirstCharIsZero = The first char in the string is the null character.
-Argument_OnlyMscorlib = Only mscorlib's assembly is valid.
-Argument_PathEmpty = Path cannot be the empty string or all whitespace.
-Argument_PathFormatNotSupported = The given path's format is not supported.
-Argument_PathUriFormatNotSupported = URI formats are not supported.
-Argument_TypeNameTooLong = Type name was too long. The fully qualified type name must be less than 1,024 characters.
-Argument_StreamNotReadable = Stream was not readable.
-Argument_StreamNotWritable = Stream was not writable.
-Argument_InvalidNumberOfMembers = MemberData contains an invalid number of members.
-Argument_InvalidValue = Value was invalid.
-Argument_InvalidKey = Key was invalid.
-Argument_MinMaxValue = '{0}' cannot be greater than {1}.
-Argument_InvalidGroupSize = Every element in the value array should be between one and nine, except for the last element, which can be zero.
-Argument_MustHaveAttributeBaseClass = Type passed in must be derived from System.Attribute or System.Attribute itself.
-Argument_NoUninitializedStrings = Uninitialized Strings cannot be created.
-Argument_UnequalMembers = Supplied MemberInfo does not match the expected type.
-Argument_BadFormatSpecifier = Format specifier was invalid.
-Argument_InvalidHighSurrogate = Found a high surrogate char without a following low surrogate at index: {0}. The input may not be in this encoding, or may not contain valid Unicode (UTF-16) characters.
-Argument_InvalidLowSurrogate = Found a low surrogate char without a preceding high surrogate at index: {0}. The input may not be in this encoding, or may not contain valid Unicode (UTF-16) characters.
-Argument_UnmatchingSymScope = Non-matching symbol scope.
-Argument_NotInExceptionBlock = Not currently in an exception block.
-Argument_BadExceptionCodeGen = Incorrect code generation for exception block.
-Argument_NotExceptionType = Does not extend Exception.
-Argument_DuplicateResourceName = Duplicate resource name within an assembly.
-Argument_BadPersistableModuleInTransientAssembly = Cannot have a persistable module in a transient assembly.
-Argument_InvalidPermissionState = Invalid permission state.
-Argument_UnrestrictedIdentityPermission = Identity permissions cannot be unrestricted.
-Argument_WrongType = Operation on type '{0}' attempted with target of incorrect type.
-Argument_IllegalZone = Illegal security permission zone specified.
-Argument_HasToBeArrayClass = Must be an array type.
-Argument_InvalidDirectory = Invalid directory, '{0}'.
-Argument_DataLengthDifferent = Parameters 'members' and 'data' must have the same length.
-Argument_SigIsFinalized = Completed signature cannot be modified.
-Argument_ArraysInvalid = Array or pointer types are not valid.
-Argument_GenericsInvalid = Generic types are not valid.
-Argument_LargeInteger = Integer or token was too large to be encoded.
-Argument_BadSigFormat = Incorrect signature format.
-Argument_UnmatchedMethodForLocal = Local passed in does not belong to this ILGenerator.
-Argument_DuplicateName = Tried to add NamedPermissionSet with non-unique name.
-Argument_InvalidXMLElement = Invalid XML. Missing required tag <{0}> for type '{1}'.
-Argument_InvalidXMLMissingAttr = Invalid XML. Missing required attribute '{0}'.
-Argument_CannotGetTypeTokenForByRef = Cannot get TypeToken for a ByRef type.
-Argument_NotASimpleNativeType = The UnmanagedType passed to DefineUnmanagedMarshal is not a simple type. None of the following values may be used: UnmanagedType.ByValTStr, UnmanagedType.SafeArray, UnmanagedType.ByValArray, UnmanagedType.LPArray, UnmanagedType.CustomMarshaler.
-Argument_NotACustomMarshaler = Not a custom marshal.
-Argument_NoUnmanagedElementCount = Unmanaged marshal does not have ElementCount.
-Argument_NoNestedMarshal = Only LPArray or SafeArray has nested unmanaged marshal.
-Argument_InvalidXML = Invalid Xml.
-Argument_NoUnderlyingCCW = The object has no underlying COM data associated with it.
-Argument_BadFieldType = Bad field type in defining field.
-Argument_InvalidXMLBadVersion = Invalid Xml - can only parse elements of version one.
-Argument_NotAPermissionElement = 'elem' was not a permission element.
-Argument_NPMSInvalidName = Name can be neither null nor empty.
-Argument_InvalidElementTag = Invalid element tag '{0}'.
-Argument_InvalidElementText = Invalid element text '{0}'.
-Argument_InvalidElementName = Invalid element name '{0}'.
-Argument_InvalidElementValue = Invalid element value '{0}'.
-Argument_AttributeNamesMustBeUnique = Attribute names must be unique.
-#if FEATURE_CAS_POLICY
-Argument_UninitializedCertificate = Uninitialized certificate object.
-Argument_MembershipConditionElement = Element must be a <IMembershipCondition> element.
-Argument_ReservedNPMS = Cannot remove or modify reserved permissions set '{0}'.
-Argument_NPMSInUse = Permission set '{0}' was in use and could not be deleted.
-Argument_StrongNameGetPublicKey = Unable to obtain public key for StrongNameKeyPair.
-Argument_SiteCannotBeNull = Site name must be specified.
-Argument_BlobCannotBeNull = Public key must be specified.
-Argument_ZoneCannotBeNull = Zone must be specified.
-Argument_UrlCannotBeNull = URL must be specified.
-Argument_NoNPMS = Unable to find a permission set with the provided name.
-Argument_FailedCodeGroup = Failed to create a code group of type '{0}'.
-Argument_CodeGroupChildrenMustBeCodeGroups = All objects in the input list must have a parent type of 'CodeGroup'.
-#endif // FEATURE_CAS_POLICY
-#if FEATURE_IMPERSONATION
-Argument_InvalidPrivilegeName = Privilege '{0}' is not valid on this system.
-Argument_TokenZero = Token cannot be zero.
-Argument_InvalidImpersonationToken = Invalid token for impersonation - it cannot be duplicated.
-Argument_ImpersonateUser = Unable to impersonate user.
-#endif // FEATURE_IMPERSONATION
-Argument_InvalidHexFormat = Improperly formatted hex string.
-Argument_InvalidSite = Invalid site.
-Argument_InterfaceMap = 'this' type cannot be an interface itself.
-Argument_ArrayGetInterfaceMap = Interface maps for generic interfaces on arrays cannot be retrieved.
-Argument_InvalidName = Invalid name.
-Argument_InvalidDirectoryOnUrl = Invalid directory on URL.
-Argument_InvalidUrl = Invalid URL.
-Argument_InvalidKindOfTypeForCA = This type cannot be represented as a custom attribute.
-Argument_MustSupplyContainer = When supplying a FieldInfo for fixing up a nested type, a valid ID for that containing object must also be supplied.
-Argument_MustSupplyParent = When supplying the ID of a containing object, the FieldInfo that identifies the current field within that object must also be supplied.
-Argument_NoClass = Element does not specify a class.
-Argument_WrongElementType = '{0}' element required.
-Argument_UnableToGeneratePermissionSet = Unable to generate permission set; input XML may be malformed.
-Argument_NoEra = No Era was supplied.
-Argument_AssemblyAlreadyFullTrust = Assembly was already fully trusted.
-Argument_AssemblyNotFullTrust = Assembly was not fully trusted.
-Argument_AssemblyWinMD = Assembly must not be a Windows Runtime assembly.
-Argument_MemberAndArray = Cannot supply both a MemberInfo and an Array to indicate the parent of a value type.
-Argument_ObjNotComObject = The object's type must be __ComObject or derived from __ComObject.
-Argument_ObjIsWinRTObject = The object's type must not be a Windows Runtime type.
-Argument_TypeNotComObject = The type must be __ComObject or be derived from __ComObject.
-Argument_TypeIsWinRTType = The type must not be a Windows Runtime type.
-Argument_CantCallSecObjFunc = Cannot evaluate a security function.
-Argument_StructMustNotBeValueClass = The structure must not be a value class.
-Argument_NoSpecificCulture = Please select a specific culture, such as zh-CN, zh-HK, zh-TW, zh-MO, zh-SG.
-Argument_InvalidResourceCultureName = The given culture name '{0}' cannot be used to locate a resource file. Resource filenames must consist of only letters, numbers, hyphens or underscores.
-Argument_InvalidParamInfo = Invalid type for ParameterInfo member in Attribute class.
-Argument_EmptyDecString = Decimal separator cannot be the empty string.
-Argument_OffsetOfFieldNotFound = Field passed in is not a marshaled member of the type '{0}'.
-Argument_EmptyStrongName = StrongName cannot have an empty string for the assembly name.
-Argument_NotSerializable = Argument passed in is not serializable.
-Argument_EmptyApplicationName = ApplicationId cannot have an empty string for the name.
-Argument_NoDomainManager = The domain manager specified by the host could not be instantiated.
-Argument_NoMain = Main entry point not defined.
-Argument_InvalidDateTimeKind = Invalid DateTimeKind value.
-Argument_ConflictingDateTimeStyles = The DateTimeStyles values AssumeLocal and AssumeUniversal cannot be used together.
-Argument_ConflictingDateTimeRoundtripStyles = The DateTimeStyles value RoundtripKind cannot be used with the values AssumeLocal, AssumeUniversal or AdjustToUniversal.
-Argument_InvalidDigitSubstitution = The DigitSubstitution property must be of a valid member of the DigitShapes enumeration. Valid entries include Context, NativeNational or None.
-Argument_InvalidNativeDigitCount = The NativeDigits array must contain exactly ten members.
-Argument_InvalidNativeDigitValue = Each member of the NativeDigits array must be a single text element (one or more UTF16 code points) with a Unicode Nd (Number, Decimal Digit) property indicating it is a digit.
-ArgumentException_InvalidAceBinaryForm = The binary form of an ACE object is invalid.
-ArgumentException_InvalidAclBinaryForm = The binary form of an ACL object is invalid.
-ArgumentException_InvalidSDSddlForm = The SDDL form of a security descriptor object is invalid.
-Argument_InvalidSafeHandle = The SafeHandle is invalid.
-Argument_CannotPrepareAbstract = Abstract methods cannot be prepared.
-Argument_ArrayTooLarge = The input array length must not exceed Int32.MaxValue / {0}. Otherwise BitArray.Length would exceed Int32.MaxValue.
-Argument_RelativeUrlMembershipCondition = UrlMembershipCondition requires an absolute URL.
-Argument_EmptyWaithandleArray = Waithandle array may not be empty.
-Argument_InvalidSafeBufferOffLen = Offset and length were greater than the size of the SafeBuffer.
-Argument_NotEnoughBytesToRead = There are not enough bytes remaining in the accessor to read at this position.
-Argument_NotEnoughBytesToWrite = There are not enough bytes remaining in the accessor to write at this position.
-Argument_OffsetAndLengthOutOfBounds = Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
-Argument_OffsetAndCapacityOutOfBounds = Offset and capacity were greater than the size of the view.
-Argument_UnmanagedMemAccessorWrapAround = The UnmanagedMemoryAccessor capacity and offset would wrap around the high end of the address space.
-Argument_UnrecognizedLoaderOptimization = Unrecognized LOADER_OPTIMIZATION property value. Supported values may include "SingleDomain", "MultiDomain", "MultiDomainHost", and "NotSpecified".
-ArgumentException_NotAllCustomSortingFuncsDefined = Implementations of all the NLS functions must be provided.
-ArgumentException_MinSortingVersion = The runtime does not support a version of "{0}" less than {1}.
-
-;
-; =====================================================
-; Reflection Emit resource strings
-Arugment_EmitMixedContext1 = Type '{0}' was loaded in the ReflectionOnly context but the AssemblyBuilder was not created as AssemblyBuilderAccess.ReflectionOnly.
-Arugment_EmitMixedContext2 = Type '{0}' was not loaded in the ReflectionOnly context but the AssemblyBuilder was created as AssemblyBuilderAccess.ReflectionOnly.
-Argument_BadSizeForData = Data size must be > 0 and < 0x3f0000
-Argument_InvalidLabel = Invalid Label.
-Argument_RedefinedLabel = Label multiply defined.
-Argument_UnclosedExceptionBlock = The IL Generator cannot be used while there are unclosed exceptions.
-Argument_MissingDefaultConstructor = was missing default constructor.
-Argument_TooManyFinallyClause = Exception blocks may have at most one finally clause.
-Argument_NotInTheSameModuleBuilder = The argument passed in was not from the same ModuleBuilder.
-Argument_BadCurrentLocalVariable = Bad current local variable for setting symbol information.
-Argument_DuplicateModuleName = Duplicate dynamic module name within an assembly.
-Argument_DuplicateTypeName = Duplicate type name within an assembly.
-Argument_InvalidAssemblyName = Assembly names may not begin with whitespace or contain the characters '/', or '\\' or ':'.
-Argument_InvalidGenericInstantiation = The given generic instantiation was invalid.
-Argument_DuplicatedFileName = Duplicate file names.
-Argument_GlobalFunctionHasToBeStatic = Global members must be static.
-Argument_BadPInvokeOnInterface = PInvoke methods cannot exist on interfaces.
-Argument_BadPInvokeMethod = PInvoke methods must be static and native and cannot be abstract.
-Argument_MethodRedefined = Method has been already defined.
-Argument_BadTypeAttrAbstractNFinal = Bad type attributes. A type cannot be both abstract and final.
-Argument_BadTypeAttrNestedVisibilityOnNonNestedType = Bad type attributes. Nested visibility flag set on a non-nested type.
-Argument_BadTypeAttrNonNestedVisibilityNestedType = Bad type attributes. Non-nested visibility flag set on a nested type.
-Argument_BadTypeAttrInvalidLayout = Bad type attributes. Invalid layout attribute specified.
-Argument_BadTypeAttrReservedBitsSet = Bad type attributes. Reserved bits set on the type.
-Argument_BadFieldSig = Field signatures do not have return types.
-Argument_ShouldOnlySetVisibilityFlags = Should only set visibility flags when creating EnumBuilder.
-Argument_BadNestedTypeFlags = Visibility of interfaces must be one of the following: NestedAssembly, NestedFamANDAssem, NestedFamily, NestedFamORAssem, NestedPrivate or NestedPublic.
-Argument_ShouldNotSpecifyExceptionType = Should not specify exception type for catch clause for filter block.
-Argument_BadLabel = Bad label in ILGenerator.
-Argument_BadLabelContent = Bad label content in ILGenerator.
-Argument_EmitWriteLineType = EmitWriteLine does not support this field or local type.
-Argument_ConstantNull = Null is not a valid constant value for this type.
-Argument_ConstantDoesntMatch = Constant does not match the defined type.
-Argument_ConstantNotSupported = {0} is not a supported constant type.
-Argument_BadConstructor = Cannot have private or static constructor.
-Argument_BadConstructorCallConv = Constructor must have standard calling convention.
-Argument_BadPropertyForConstructorBuilder = Property must be on the same type of the given ConstructorInfo.
-Argument_NotAWritableProperty = Not a writable property.
-Argument_BadFieldForConstructorBuilder = Field must be on the same type of the given ConstructorInfo.
-Argument_BadAttributeOnInterfaceMethod = Interface method must be abstract and virtual.
-ArgumentException_BadMethodImplBody = MethodOverride's body must be from this type.
-Argument_BadParameterCountsForConstructor = Parameter count does not match passed in argument value count.
-Argument_BadParameterTypeForConstructor = Passed in argument value at index {0} does not match the parameter type.
-Argument_BadTypeInCustomAttribute = An invalid type was used as a custom attribute constructor argument, field or property.
-Argument_DateTimeBadBinaryData = The binary data must result in a DateTime with ticks between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.
-Argument_VerStringTooLong = The unmanaged Version information is too large to persist.
-Argument_UnknownUnmanagedCallConv = Unknown unmanaged calling convention for function signature.
-Argument_BadConstantValue = Bad default value.
-Argument_IllegalName = Illegal name.
-Argument_cvtres_NotFound = Cannot find cvtres.exe
-Argument_BadCAForUnmngRSC = Bad '{0}' while generating unmanaged resource information.
-Argument_MustBeInterfaceMethod = The MemberInfo must be an interface method.
-Argument_CORDBBadVarArgCallConv = Cannot evaluate a VarArgs function.
-Argument_CORDBBadMethod = Cannot find the method on the object instance.
-Argument_InvalidOpCodeOnDynamicMethod = Ldtoken, Ldftn and Ldvirtftn OpCodes cannot target DynamicMethods.
-Argument_InvalidTypeForDynamicMethod = Invalid type owner for DynamicMethod.
-Argument_NeedGenericMethodDefinition = Method must represent a generic method definition on a generic type definition.
-Argument_MethodNeedGenericDeclaringType = The specified method cannot be dynamic or global and must be declared on a generic type definition.
-Argument_ConstructorNeedGenericDeclaringType = The specified constructor must be declared on a generic type definition.
-Argument_FieldNeedGenericDeclaringType = The specified field must be declared on a generic type definition.
-Argument_InvalidMethodDeclaringType = The specified method must be declared on the generic type definition of the specified type.
-Argument_InvalidConstructorDeclaringType = The specified constructor must be declared on the generic type definition of the specified type.
-Argument_InvalidFieldDeclaringType = The specified field must be declared on the generic type definition of the specified type.
-Argument_NeedNonGenericType = The specified Type must not be a generic type definition.
-Argument_MustBeTypeBuilder = 'type' must contain a TypeBuilder as a generic argument.
-Argument_CannotSetParentToInterface = Cannot set parent to an interface.
-Argument_MismatchedArrays = Two arrays, {0} and {1}, must be of the same size.
-Argument_NeedNonGenericObject = The specified object must not be an instance of a generic type.
-Argument_NeedStructWithNoRefs = The specified Type must be a struct containing no references.
-Argument_NotMethodCallOpcode = The specified opcode cannot be passed to EmitCall.
-
-; =====================================================
-;
-Argument_ModuleAlreadyLoaded = The specified module has already been loaded.
-Argument_MustHaveLayoutOrBeBlittable = The specified structure must be blittable or have layout information.
-Argument_NotSimpleFileName = The filename must not include a path specification.
-Argument_TypeMustBeVisibleFromCom = The specified type must be visible from COM.
-Argument_TypeMustBeComCreatable = The type must be creatable from COM.
-Argument_TypeMustNotBeComImport = The type must not be imported from COM.
-Argument_PolicyFileDoesNotExist = The requested policy file does not exist.
-Argument_NonNullObjAndCtx = Either obj or ctx must be null.
-Argument_NoModuleFileExtension = Module file name '{0}' must have file extension.
-Argument_TypeDoesNotContainMethod = Type does not contain the given method.
-Argument_StringZeroLength = String cannot be of zero length.
-Argument_MustBeString = String is too long or has invalid contents.
-Argument_AbsolutePathRequired = Absolute path information is required.
-Argument_ManifestFileDoesNotExist = The specified manifest file does not exist.
-Argument_MustBeRuntimeType = Type must be a runtime Type object.
-Argument_TypeNotValid = The Type object is not valid.
-Argument_MustBeRuntimeMethodInfo = MethodInfo must be a runtime MethodInfo object.
-Argument_MustBeRuntimeFieldInfo = FieldInfo must be a runtime FieldInfo object.
-Argument_InvalidFieldInfo = The FieldInfo object is not valid.
-Argument_InvalidConstructorInfo = The ConstructorInfo object is not valid.
-Argument_MustBeRuntimeAssembly = Assembly must be a runtime Assembly object.
-Argument_MustBeRuntimeModule = Module must be a runtime Module object.
-Argument_MustBeRuntimeParameterInfo = ParameterInfo must be a runtime ParameterInfo object.
-Argument_InvalidParameterInfo = The ParameterInfo object is not valid.
-Argument_MustBeRuntimeReflectionObject = The object must be a runtime Reflection object.
-Argument_InvalidMarshalByRefObject = The MarshalByRefObject is not valid.
-Argument_TypedReferenceInvalidField = Field in TypedReferences cannot be static or init only.
-Argument_HandleLeak = Cannot pass a GCHandle across AppDomains.
-Argument_ArgumentZero = Argument cannot be zero.
-Argument_ImproperType = Improper types in collection.
-Argument_NotAMembershipCondition = The type does not implement IMembershipCondition
-Argument_NotAPermissionType = The type does not implement IPermission
-Argument_NotACodeGroupType = The type does not inherit from CodeGroup
-Argument_NotATP = Type must be a TransparentProxy
-Argument_AlreadyACCW = The object already has a CCW associated with it.
-Argument_OffsetLocalMismatch = The UTC Offset of the local dateTime parameter does not match the offset argument.
-Argument_OffsetUtcMismatch = The UTC Offset for Utc DateTime instances must be 0.
-Argument_UTCOutOfRange = The UTC time represented when the offset is applied must be between year 0 and 10,000.
-Argument_OffsetOutOfRange = Offset must be within plus or minus 14 hours.
-Argument_OffsetPrecision = Offset must be specified in whole minutes.
-Argument_FlagNotSupported = One or more flags are not supported.
-Argument_MustBeFalse = Argument must be initialized to false
-Argument_ToExclusiveLessThanFromExclusive = fromInclusive must be less than or equal to toExclusive.
-Argument_FrameworkNameTooShort=FrameworkName cannot have less than two components or more than three components.
-Argument_FrameworkNameInvalid=FrameworkName is invalid.
-Argument_FrameworkNameMissingVersion=FrameworkName version component is missing.
-#if FEATURE_COMINTEROP
-Argument_TypeNotActivatableViaWindowsRuntime = Type '{0}' does not have an activation factory because it is not activatable by Windows Runtime.
-Argument_WinRTSystemRuntimeType = Cannot marshal type '{0}' to Windows Runtime. Only 'System.RuntimeType' is supported.
-Argument_Unexpected_TypeSource = Unexpected TypeKind when marshaling Windows.Foundation.TypeName.
-#endif // FEATURE_COMINTEROP
-
-; ArgumentNullException
-ArgumentNull_Array = Array cannot be null.
-ArgumentNull_ArrayValue = Found a null value within an array.
-ArgumentNull_ArrayElement = At least one element in the specified array was null.
-ArgumentNull_Assembly = Assembly cannot be null.
-ArgumentNull_AssemblyName = AssemblyName cannot be null.
-ArgumentNull_AssemblyNameName = AssemblyName.Name cannot be null or an empty string.
-ArgumentNull_Buffer = Buffer cannot be null.
-ArgumentNull_Collection = Collection cannot be null.
-ArgumentNull_CultureInfo = CultureInfo cannot be null.
-ArgumentNull_Dictionary = Dictionary cannot be null.
-ArgumentNull_FileName = File name cannot be null.
-ArgumentNull_Key = Key cannot be null.
-ArgumentNull_Graph = Object Graph cannot be null.
-ArgumentNull_Path = Path cannot be null.
-ArgumentNull_Stream = Stream cannot be null.
-ArgumentNull_String = String reference not set to an instance of a String.
-ArgumentNull_Type = Type cannot be null.
-ArgumentNull_Obj = Object cannot be null.
-ArgumentNull_GUID = GUID cannot be null.
-ArgumentNull_NullMember = Member at position {0} was null.
-ArgumentNull_Generic = Value cannot be null.
-ArgumentNull_WithParamName = Parameter '{0}' cannot be null.
-ArgumentNull_Child = Cannot have a null child.
-ArgumentNull_SafeHandle = SafeHandle cannot be null.
-ArgumentNull_CriticalHandle = CriticalHandle cannot be null.
-ArgumentNull_TypedRefType = Type in TypedReference cannot be null.
-ArgumentNull_ApplicationTrust = The application trust cannot be null.
-ArgumentNull_TypeRequiredByResourceScope = The type parameter cannot be null when scoping the resource's visibility to Private or Assembly.
-ArgumentNull_Waithandles = The waitHandles parameter cannot be null.
-
-; ArgumentOutOfRangeException
-ArgumentOutOfRange_AddressSpace = The number of bytes cannot exceed the virtual address space on a 32 bit machine.
-ArgumentOutOfRange_ArrayLB = Number was less than the array's lower bound in the first dimension.
-ArgumentOutOfRange_ArrayLBAndLength = Higher indices will exceed Int32.MaxValue because of large lower bound and/or length.
-ArgumentOutOfRange_ArrayLength = The length of the array must be between {0} and {1}, inclusive.
-ArgumentOutOfRange_ArrayLengthMultiple = The length of the array must be a multiple of {0}.
-ArgumentOutOfRange_ArrayListInsert = Insertion index was out of range. Must be non-negative and less than or equal to size.
-ArgumentOutOfRange_ArrayTooSmall = Destination array is not long enough to copy all the required data. Check array length and offset.
-ArgumentOutOfRange_BeepFrequency = Console.Beep's frequency must be between {0} and {1}.
-ArgumentOutOfRange_BiggerThanCollection = Larger than collection size.
-ArgumentOutOfRange_Bounds_Lower_Upper = Argument must be between {0} and {1}.
-ArgumentOutOfRange_Count = Count must be positive and count must refer to a location within the string/array/collection.
-ArgumentOutOfRange_CalendarRange = Specified time is not supported in this calendar. It should be between {0} (Gregorian date) and {1} (Gregorian date), inclusive.
-ArgumentOutOfRange_ConsoleBufferBoundaries = The value must be greater than or equal to zero and less than the console's buffer size in that dimension.
-ArgumentOutOfRange_ConsoleBufferLessThanWindowSize = The console buffer size must not be less than the current size and position of the console window, nor greater than or equal to Int16.MaxValue.
-ArgumentOutOfRange_ConsoleWindowBufferSize = The new console window size would force the console buffer size to be too large.
-ArgumentOutOfRange_ConsoleTitleTooLong = The console title is too long.
-ArgumentOutOfRange_ConsoleWindowPos = The window position must be set such that the current window size fits within the console's buffer, and the numbers must not be negative.
-ArgumentOutOfRange_ConsoleWindowSize_Size = The value must be less than the console's current maximum window size of {0} in that dimension. Note that this value depends on screen resolution and the console font.
-ArgumentOutOfRange_ConsoleKey = Console key values must be between 0 and 255.
-ArgumentOutOfRange_CursorSize = The cursor size is invalid. It must be a percentage between 1 and 100.
-ArgumentOutOfRange_BadYearMonthDay = Year, Month, and Day parameters describe an un-representable DateTime.
-ArgumentOutOfRange_BadHourMinuteSecond = Hour, Minute, and Second parameters describe an un-representable DateTime.
-ArgumentOutOfRange_DateArithmetic = The added or subtracted value results in an un-representable DateTime.
-ArgumentOutOfRange_DateTimeBadMonths = Months value must be between +/-120000.
-ArgumentOutOfRange_DateTimeBadYears = Years value must be between +/-10000.
-ArgumentOutOfRange_DateTimeBadTicks = Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.
-ArgumentOutOfRange_Day = Day must be between 1 and {0} for month {1}.
-ArgumentOutOfRange_DecimalRound = Decimal can only round to between 0 and 28 digits of precision.
-ArgumentOutOfRange_DecimalScale = Decimal's scale value must be between 0 and 28, inclusive.
-ArgumentOutOfRange_Era = Time value was out of era range.
-ArgumentOutOfRange_Enum = Enum value was out of legal range.
-ArgumentOutOfRange_FileLengthTooBig = Specified file length was too large for the file system.
-ArgumentOutOfRange_FileTimeInvalid = Not a valid Win32 FileTime.
-ArgumentOutOfRange_GetByteCountOverflow = Too many characters. The resulting number of bytes is larger than what can be returned as an int.
-ArgumentOutOfRange_GetCharCountOverflow = Too many bytes. The resulting number of chars is larger than what can be returned as an int.
-ArgumentOutOfRange_HashtableLoadFactor = Load factor needs to be between 0.1 and 1.0.
-ArgumentOutOfRange_HugeArrayNotSupported = Arrays larger than 2GB are not supported.
-ArgumentOutOfRange_InvalidHighSurrogate = A valid high surrogate character is between 0xd800 and 0xdbff, inclusive.
-ArgumentOutOfRange_InvalidLowSurrogate = A valid low surrogate character is between 0xdc00 and 0xdfff, inclusive.
-ArgumentOutOfRange_InvalidEraValue = Era value was not valid.
-ArgumentOutOfRange_InvalidUserDefinedAceType = User-defined ACEs must not have a well-known ACE type.
-ArgumentOutOfRange_InvalidUTF32 = A valid UTF32 value is between 0x000000 and 0x10ffff, inclusive, and should not include surrogate codepoint values (0x00d800 ~ 0x00dfff).
-ArgumentOutOfRange_Index = Index was out of range. Must be non-negative and less than the size of the collection.
-ArgumentOutOfRange_IndexString = Index was out of range. Must be non-negative and less than the length of the string.
-ArgumentOutOfRange_StreamLength = Stream length must be non-negative and less than 2^31 - 1 - origin.
-ArgumentOutOfRange_LessEqualToIntegerMaxVal = Argument must be less than or equal to 2^31 - 1 milliseconds.
-ArgumentOutOfRange_Month = Month must be between one and twelve.
-ArgumentOutOfRange_MustBeNonNegInt32 = Value must be non-negative and less than or equal to Int32.MaxValue.
-ArgumentOutOfRange_NeedNonNegNum = Non-negative number required.
-ArgumentOutOfRange_NeedNonNegOrNegative1 = Number must be either non-negative and less than or equal to Int32.MaxValue or -1.
-ArgumentOutOfRange_NeedPosNum = Positive number required.
-ArgumentOutOfRange_NegativeCapacity = Capacity must be positive.
-ArgumentOutOfRange_NegativeCount = Count cannot be less than zero.
-ArgumentOutOfRange_NegativeLength = Length cannot be less than zero.
-ArgumentOutOfRange_NegFileSize = Length must be non-negative.
-ArgumentOutOfRange_ObjectID = objectID cannot be less than or equal to zero.
-ArgumentOutOfRange_SmallCapacity = capacity was less than the current size.
-ArgumentOutOfRange_QueueGrowFactor = Queue grow factor must be between {0} and {1}.
-ArgumentOutOfRange_RoundingDigits = Rounding digits must be between 0 and 15, inclusive.
-ArgumentOutOfRange_StartIndex = StartIndex cannot be less than zero.
-ArgumentOutOfRange_MustBePositive = '{0}' must be greater than zero.
-ArgumentOutOfRange_MustBeNonNegNum = '{0}' must be non-negative.
-ArgumentOutOfRange_LengthGreaterThanCapacity = The length cannot be greater than the capacity.
-ArgumentOutOfRange_ListInsert = Index must be within the bounds of the List.
-ArgumentOutOfRange_StartIndexLessThanLength = startIndex must be less than length of string.
-ArgumentOutOfRange_StartIndexLargerThanLength = startIndex cannot be larger than length of string.
-ArgumentOutOfRange_EndIndexStartIndex = endIndex cannot be greater than startIndex.
-ArgumentOutOfRange_IndexCount = Index and count must refer to a location within the string.
-ArgumentOutOfRange_IndexCountBuffer = Index and count must refer to a location within the buffer.
-ArgumentOutOfRange_IndexLength = Index and length must refer to a location within the string.
-ArgumentOutOfRange_InvalidThreshold = The specified threshold for creating dictionary is out of range.
-ArgumentOutOfRange_Capacity = Capacity exceeds maximum capacity.
-ArgumentOutOfRange_Length = The specified length exceeds maximum capacity of SecureString.
-ArgumentOutOfRange_LengthTooLarge = The specified length exceeds the maximum value of {0}.
-ArgumentOutOfRange_SmallMaxCapacity = MaxCapacity must be one or greater.
-ArgumentOutOfRange_GenericPositive = Value must be positive.
-ArgumentOutOfRange_Range = Valid values are between {0} and {1}, inclusive.
-ArgumentOutOfRange_AddValue = Value to add was out of range.
-ArgumentOutOfRange_OffsetLength = Offset and length must refer to a position in the string.
-ArgumentOutOfRange_OffsetOut = Either offset did not refer to a position in the string, or there is an insufficient length of destination character array.
-ArgumentOutOfRange_PartialWCHAR = Pointer startIndex and length do not refer to a valid string.
-ArgumentOutOfRange_ParamSequence = The specified parameter index is not in range.
-ArgumentOutOfRange_Version = Version's parameters must be greater than or equal to zero.
-ArgumentOutOfRange_TimeoutTooLarge = Time-out interval must be less than 2^32-2.
-ArgumentOutOfRange_UIntPtrMax-1 = The length of the buffer must be less than the maximum UIntPtr value for your platform.
-ArgumentOutOfRange_UnmanagedMemStreamLength = UnmanagedMemoryStream length must be non-negative and less than 2^63 - 1 - baseAddress.
-ArgumentOutOfRange_UnmanagedMemStreamWrapAround = The UnmanagedMemoryStream capacity would wrap around the high end of the address space.
-ArgumentOutOfRange_PeriodTooLarge = Period must be less than 2^32-2.
-ArgumentOutOfRange_Year = Year must be between 1 and 9999.
-ArgumentOutOfRange_BinaryReaderFillBuffer = The number of bytes requested does not fit into BinaryReader's internal buffer.
-ArgumentOutOfRange_PositionLessThanCapacityRequired = The position may not be greater or equal to the capacity of the accessor.
-
-; ArithmeticException
-Arithmetic_NaN = Function does not accept floating point Not-a-Number values.
-
-; ArrayTypeMismatchException
-ArrayTypeMismatch_CantAssignType = Source array type cannot be assigned to destination array type.
-ArrayTypeMismatch_ConstrainedCopy = Array.ConstrainedCopy will only work on array types that are provably compatible, without any form of boxing, unboxing, widening, or casting of each array element. Change the array types (i.e., copy a Derived[] to a Base[]), or use a mitigation strategy in the CER for Array.Copy's less powerful reliability contract, such as cloning the array or throwing away the potentially corrupt destination array.
-
-; BadImageFormatException
-BadImageFormat_ResType&SerBlobMismatch = The type serialized in the .resources file was not the same type that the .resources file said it contained. Expected '{0}' but read '{1}'.
-BadImageFormat_ResourcesIndexTooLong = Corrupt .resources file. String for name index '{0}' extends past the end of the file.
-BadImageFormat_ResourcesNameTooLong = Corrupt .resources file. Resource name extends past the end of the file.
-BadImageFormat_ResourcesNameInvalidOffset = Corrupt .resources file. Invalid offset '{0}' into name section.
-BadImageFormat_ResourcesHeaderCorrupted = Corrupt .resources file. Unable to read resources from this file because of invalid header information. Try regenerating the .resources file.
-BadImageFormat_ResourceNameCorrupted = Corrupt .resources file. A resource name extends past the end of the stream.
-BadImageFormat_ResourceNameCorrupted_NameIndex = Corrupt .resources file. The resource name for name index {0} extends past the end of the stream.
-BadImageFormat_ResourceDataLengthInvalid = Corrupt .resources file. The specified data length '{0}' is not a valid position in the stream.
-BadImageFormat_TypeMismatch = Corrupt .resources file. The specified type doesn't match the available data in the stream.
-BadImageFormat_InvalidType = Corrupt .resources file. The specified type doesn't exist.
-BadImageFormat_ResourcesIndexInvalid = Corrupt .resources file. The resource index '{0}' is outside the valid range.
-BadImageFormat_StreamPositionInvalid = Corrupt .resources file. The specified position '{0}' is not a valid position in the stream.
-BadImageFormat_ResourcesDataInvalidOffset = Corrupt .resources file. Invalid offset '{0}' into data section.
-BadImageFormat_NegativeStringLength = Corrupt .resources file. String length must be non-negative.
-BadImageFormat_ParameterSignatureMismatch = The parameters and the signature of the method don't match.
-
-; Cryptography
-; These strings still appear in bcl.small but should go away eventually
-Cryptography_CSSM_Error = Error 0x{0} from the operating system security framework: '{1}'.
-Cryptography_CSSM_Error_Unknown = Error 0x{0} from the operating system security framework.
-Cryptography_InvalidDSASignatureSize = Length of the DSA signature was not 40 bytes.
-Cryptography_InvalidHandle = {0} is an invalid handle.
-Cryptography_InvalidOID = Object identifier (OID) is unknown.
-Cryptography_OAEPDecoding = Error occurred while decoding OAEP padding.
-Cryptography_PasswordDerivedBytes_InvalidIV = The Initialization vector should have the same length as the algorithm block size in bytes.
-Cryptography_SSE_InvalidDataSize = Length of the data to encrypt is invalid.
-Cryptography_X509_ExportFailed = The certificate export operation failed.
-Cryptography_X509_InvalidContentType = Invalid content type.
-Cryptography_CryptoStream_FlushFinalBlockTwice = FlushFinalBlock() method was called twice on a CryptoStream. It can only be called once.
-Cryptography_HashKeySet = Hash key cannot be changed after the first write to the stream.
-Cryptography_HashNotYetFinalized = Hash must be finalized before the hash value is retrieved.
-Cryptography_InsufficientBuffer = Input buffer contains insufficient data.
-Cryptography_InvalidBlockSize = Specified block size is not valid for this algorithm.
-Cryptography_InvalidCipherMode = Specified cipher mode is not valid for this algorithm.
-Cryptography_InvalidIVSize = Specified initialization vector (IV) does not match the block size for this algorithm.
-Cryptography_InvalidKeySize = Specified key is not a valid size for this algorithm.
-Cryptography_PasswordDerivedBytes_FewBytesSalt = Salt is not at least eight bytes.
-Cryptography_PKCS7_InvalidPadding = Padding is invalid and cannot be removed.
-Cryptography_UnknownHashAlgorithm='{0}' is not a known hash algorithm.
-
-#if FEATURE_CRYPTO
-Cryptography_Config_EncodedOIDError = Encoded OID length is too large (greater than 0x7f bytes).
-Cryptography_CSP_AlgKeySizeNotAvailable = Algorithm implementation does not support a key size of {0}.
-Cryptography_CSP_AlgorithmNotAvailable = Cryptographic service provider (CSP) could not be found for this algorithm.
-Cryptography_CSP_CFBSizeNotSupported = Feedback size for the cipher feedback mode (CFB) must be 8 bits.
-Cryptography_CSP_NotFound = The requested key container was not found.
-Cryptography_CSP_NoPrivateKey = Object contains only the public half of a key pair. A private key must also be provided.
-Cryptography_CSP_OFBNotSupported = Output feedback mode (OFB) is not supported by this implementation.
-Cryptography_CSP_WrongKeySpec = The specified cryptographic service provider (CSP) does not support this key algorithm.
-Cryptography_HashNameSet = Hash name cannot be changed after the first write to the stream.
-Cryptography_HashAlgorithmNameNullOrEmpty = The hash algorithm name cannot be null or empty.
-Cryptography_InvalidHashSize = {0} algorithm hash size is {1} bytes.
-Cryptography_InvalidKey_Weak = Specified key is a known weak key for '{0}' and cannot be used.
-Cryptography_InvalidKey_SemiWeak = Specified key is a known semi-weak key for '{0}' and cannot be used.
-Cryptography_InvalidKeyParameter = Parameter '{0}' is not a valid key parameter.
-Cryptography_InvalidFeedbackSize = Specified feedback size is invalid.
-Cryptography_InvalidOperation = This operation is not supported for this class.
-Cryptography_InvalidPaddingMode = Specified padding mode is not valid for this algorithm.
-Cryptography_InvalidFromXmlString = Input string does not contain a valid encoding of the '{0}' '{1}' parameter.
-Cryptography_MissingKey = No asymmetric key object has been associated with this formatter object.
-Cryptography_MissingOID = Required object identifier (OID) cannot be found.
-Cryptography_NotInteractive = The current session is not interactive.
-Cryptography_NonCompliantFIPSAlgorithm = This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.
-Cryptography_Padding_Win2KEnhOnly = Direct Encryption and decryption using RSA are not available on this platform.
-Cryptography_Padding_EncDataTooBig = The data to be encrypted exceeds the maximum for this modulus of {0} bytes.
-Cryptography_Padding_DecDataTooBig = The data to be decrypted exceeds the maximum for this modulus of {0} bytes.
-Cryptography_PasswordDerivedBytes_ValuesFixed = Value of '{0}' cannot be changed after the bytes have been retrieved.
-Cryptography_PasswordDerivedBytes_TooManyBytes = Requested number of bytes exceeds the maximum.
-Cryptography_PasswordDerivedBytes_InvalidAlgorithm = Algorithm is unavailable or is not supported for this operation.
-Cryptography_PKCS1Decoding = Error occurred while decoding PKCS1 padding.
-Cryptography_RC2_EKSKS = EffectiveKeySize value must be at least as large as the KeySize value.
-Cryptography_RC2_EKSKS2 = EffectiveKeySize must be the same as KeySize in this implementation.
-Cryptography_RC2_EKS40 = EffectiveKeySize value must be at least 40 bits.
-Cryptography_SSD_InvalidDataSize = Length of the data to decrypt is invalid.
-Cryptography_AddNullOrEmptyName = CryptoConfig cannot add a mapping for a null or empty name.
-Cryptography_AlgorithmTypesMustBeVisible = Algorithms added to CryptoConfig must be accessable from outside their assembly.
-#endif // FEATURE_CRYPTO
-
-; EventSource
-EventSource_ToString = EventSource({0}, {1})
-EventSource_EventSourceGuidInUse = An instance of EventSource with Guid {0} already exists.
-EventSource_KeywordNeedPowerOfTwo = Value {0} for keyword {1} needs to be a power of 2.
-EventSource_UndefinedKeyword = Use of undefined keyword value {0} for event {1}.
-EventSource_UnsupportedEventTypeInManifest = Unsupported type {0} in event source.
-EventSource_ListenerNotFound = Listener not found.
-EventSource_ListenerCreatedInsideCallback = Creating an EventListener inside a EventListener callback.
-EventSource_AttributeOnNonVoid = Event attribute placed on method {0} which does not return 'void'.
-EventSource_NeedPositiveId = Event IDs must be positive integers.
-EventSource_ReservedOpcode = Opcode values less than 11 are reserved for system use.
-EventSource_ReservedKeywords = Keywords values larger than 0x0000100000000000 are reserved for system use
-EventSource_PayloadTooBig=The payload for a single event is too large.
-EventSource_NoFreeBuffers=No Free Buffers available from the operating system (e.g. event rate too fast).
-EventSource_NullInput=Null passed as a event argument.
-EventSource_TooManyArgs=Too many arguments.
-EventSource_SessionIdError=Bit position in AllKeywords ({0}) must equal the command argument named "EtwSessionKeyword" ({1}).
-EventSource_EnumKindMismatch = The type of {0} is not expected in {1}.
-EventSource_MismatchIdToWriteEvent = Event {0} is givien event ID {1} but {2} was passed to WriteEvent.
-EventSource_EventIdReused = Event {0} has ID {1} which is already in use.
-EventSource_EventNameReused = Event name {0} used more than once. If you wish to overload a method, the overloaded method should have a NonEvent attribute.
-EventSource_UndefinedChannel = Use of undefined channel value {0} for event {1}.
-EventSource_UndefinedOpcode = Use of undefined opcode value {0} for event {1}.
-ArgumentOutOfRange_MaxArgExceeded = The total number of parameters must not exceed {0}.
-ArgumentOutOfRange_MaxStringsExceeded = The number of String parameters must not exceed {0}.
-ArgumentOutOfRange_NeedValidId = The ID parameter must be in the range {0} through {1}.
-EventSource_NeedGuid = The Guid of an EventSource must be non zero.
-EventSource_NeedName = The name of an EventSource must not be null.
-EventSource_EtwAlreadyRegistered = The provider has already been registered with the operating system.
-EventSource_ListenerWriteFailure = An error occurred when writing to a listener.
-EventSource_TypeMustDeriveFromEventSource = Event source types must derive from EventSource.
-EventSource_TypeMustBeSealedOrAbstract = Event source types must be sealed or abstract.
-EventSource_TaskOpcodePairReused = Event {0} (with ID {1}) has the same task/opcode pair as event {2} (with ID {3}).
-EventSource_EventMustHaveTaskIfNonDefaultOpcode = Event {0} (with ID {1}) has a non-default opcode but not a task.
-EventSource_EventNameDoesNotEqualTaskPlusOpcode = Event {0} (with ID {1}) has a name that is not the concatenation of its task name and opcode.
-EventSource_PeriodIllegalInProviderName = Period character ('.') is illegal in an ETW provider name ({0}).
-EventSource_IllegalOpcodeValue = Opcode {0} has a value of {1} which is outside the legal range (11-238).
-EventSource_OpcodeCollision = Opcodes {0} and {1} are defined with the same value ({2}).
-EventSource_IllegalTaskValue = Task {0} has a value of {1} which is outside the legal range (1-65535).
-EventSource_TaskCollision = Tasks {0} and {1} are defined with the same value ({2}).
-EventSource_IllegalKeywordsValue = Keyword {0} has a value of {1} which is outside the legal range (0-0x0000080000000000).
-EventSource_KeywordCollision = Keywords {0} and {1} are defined with the same value ({2}).
-EventSource_EventChannelOutOfRange = Channel {0} has a value of {1} which is outside the legal range (16-254).
-EventSource_ChannelTypeDoesNotMatchEventChannelValue = Channel {0} does not match event channel value {1}.
-EventSource_MaxChannelExceeded = Attempt to define more than the maximum limit of 8 channels for a provider.
-EventSource_DuplicateStringKey = Multiple definitions for string "{0}".
-EventSource_EventWithAdminChannelMustHaveMessage = Event {0} specifies an Admin channel {1}. It must specify a Message property.
-EventSource_UnsupportedMessageProperty = Event {0} specifies an illegal or unsupported formatting message ("{1}").
-EventSource_AbstractMustNotDeclareKTOC = Abstract event source must not declare {0} nested type.
-EventSource_AbstractMustNotDeclareEventMethods = Abstract event source must not declare event methods ({0} with ID {1}).
-EventSource_EventMustNotBeExplicitImplementation = Event method {0} (with ID {1}) is an explicit interface method implementation. Re-write method as implicit implementation.
-EventSource_EventParametersMismatch = Event {0} was called with {1} argument(s), but it is defined with {2} parameter(s).
-EventSource_InvalidCommand = Invalid command value.
-EventSource_InvalidEventFormat = Can't specify both etw event format flags.
-EventSource_AddScalarOutOfRange = Getting out of bounds during scalar addition.
-EventSource_PinArrayOutOfRange = Pins are out of range.
-EventSource_DataDescriptorsOutOfRange = Data descriptors are out of range.
-EventSource_NotSupportedArrayOfNil = Arrays of Nil are not supported.
-EventSource_NotSupportedArrayOfBinary = Arrays of Binary are not supported.
-EventSource_NotSupportedArrayOfNullTerminatedString = Arrays of null-terminated string are not supported.
-EventSource_TooManyFields = Too many fields in structure.
-EventSource_RecursiveTypeDefinition = Recursive type definition is not supported.
-EventSource_NotSupportedEnumType = Enum type {0} underlying type {1} is not supported for serialization.
-EventSource_NonCompliantTypeError = The API supports only anonymous types or types decorated with the EventDataAttribute. Non-compliant type: {0} dataType.
-EventSource_NotSupportedNestedArraysEnums = Nested arrays/enumerables are not supported.
-EventSource_IncorrentlyAuthoredTypeInfo = Incorrectly-authored TypeInfo - a type should be serialized as one field or as one group
-EventSource_NotSupportedCustomSerializedData = Enumerables of custom-serialized data are not supported
-EventSource_StopsFollowStarts = An event with stop suffix must follow a corresponding event with a start suffix.
-EventSource_NoRelatedActivityId = EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId.
-EventSource_VarArgsParameterMismatch = The parameters to the Event method do not match the parameters to the WriteEvent method. This may cause the event to be displayed incorrectly.
-
-; ExecutionEngineException
-ExecutionEngine_InvalidAttribute = Attribute cannot have multiple definitions.
-ExecutionEngine_MissingSecurityDescriptor = Unable to retrieve security descriptor for this frame.
-
-;;ExecutionContext
-ExecutionContext_UndoFailed = Undo operation on a component context threw an exception
-ExecutionContext_ExceptionInAsyncLocalNotification = An exception was not handled in an AsyncLocal<T> notification callback.
-
-
-; FieldAccessException
-FieldAccess_InitOnly = InitOnly (aka ReadOnly) fields can only be initialized in the type/instance constructor.
-
-; FormatException
-Format_AttributeUsage = Duplicate AttributeUsageAttribute found on attribute type {0}.
-Format_Bad7BitInt32 = Too many bytes in what should have been a 7 bit encoded Int32.
-Format_BadBase = Invalid digits for the specified base.
-Format_BadBase64Char = The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
-Format_BadBase64CharArrayLength = Invalid length for a Base-64 char array or string.
-Format_BadBoolean = String was not recognized as a valid Boolean.
-Format_BadDateTime = String was not recognized as a valid DateTime.
-Format_BadDateTimeCalendar = The DateTime represented by the string is not supported in calendar {0}.
-Format_BadDayOfWeek = String was not recognized as a valid DateTime because the day of week was incorrect.
-Format_DateOutOfRange = The DateTime represented by the string is out of range.
-Format_BadDatePattern = Could not determine the order of year, month, and date from '{0}'.
-Format_BadFormatSpecifier = Format specifier was invalid.
-Format_BadTimeSpan = String was not recognized as a valid TimeSpan.
-Format_BadQuote = Cannot find a matching quote character for the character '{0}'.
-Format_EmptyInputString = Input string was either empty or contained only whitespace.
-Format_ExtraJunkAtEnd = Additional non-parsable characters are at the end of the string.
-Format_GuidBrace = Expected {0xdddddddd, etc}.
-Format_GuidComma = Could not find a comma, or the length between the previous token and the comma was zero (i.e., '0x,'etc.).
-Format_GuidBraceAfterLastNumber = Could not find a brace, or the length between the previous token and the brace was zero (i.e., '0x,'etc.).
-Format_GuidDashes = Dashes are in the wrong position for GUID parsing.
-Format_GuidEndBrace = Could not find the ending brace.
-Format_GuidHexPrefix = Expected hex 0x in '{0}'.
-Format_GuidInvLen = Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
-Format_GuidInvalidChar = Guid string should only contain hexadecimal characters.
-Format_GuidUnrecognized = Unrecognized Guid format.
-Format_InvalidEnumFormatSpecification = Format String can be only "G", "g", "X", "x", "F", "f", "D" or "d".
-Format_InvalidGuidFormatSpecification = Format String can be only "D", "d", "N", "n", "P", "p", "B", "b", "X" or "x".
-Format_InvalidString = Input string was not in a correct format.
-Format_IndexOutOfRange = Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
-Format_UnknowDateTimeWord = The string was not recognized as a valid DateTime. There is an unknown word starting at index {0}.
-Format_NeedSingleChar = String must be exactly one character long.
-Format_NoParsibleDigits = Could not find any recognizable digits.
-Format_RepeatDateTimePattern = DateTime pattern '{0}' appears more than once with different values.
-Format_StringZeroLength = String cannot have zero length.
-Format_TwoTimeZoneSpecifiers = The String being parsed cannot contain two TimeZone specifiers.
-Format_UTCOutOfRange= The UTC representation of the date falls outside the year range 1-9999.
-Format_OffsetOutOfRange=The time zone offset must be within plus or minus 14 hours.
-Format_MissingIncompleteDate=There must be at least a partial date with a year present in the input.
-
-; IndexOutOfRangeException
-IndexOutOfRange_ArrayRankIndex = Array does not have that many dimensions.
-IndexOutOfRange_IORaceCondition = Probable I/O race condition detected while copying memory. The I/O package is not thread safe by default. In multithreaded applications, a stream must be accessed in a thread-safe way, such as a thread-safe wrapper returned by TextReader's or TextWriter's Synchronized methods. This also applies to classes like StreamWriter and StreamReader.
-IndexOutOfRange_UMSPosition = Unmanaged memory stream position was beyond the capacity of the stream.
-
-; InsufficientMemoryException
-InsufficientMemory_MemFailPoint = Insufficient available memory to meet the expected demands of an operation at this time. Please try again later.
-InsufficientMemory_MemFailPoint_TooBig = Insufficient memory to meet the expected demands of an operation, and this system is likely to never satisfy this request. If this is a 32 bit system, consider booting in 3 GB mode.
-InsufficientMemory_MemFailPoint_VAFrag = Insufficient available memory to meet the expected demands of an operation at this time, possibly due to virtual address space fragmentation. Please try again later.
-
-
-; InvalidCastException
-InvalidCast_DBNull = Object cannot be cast to DBNull.
-InvalidCast_DownCastArrayElement = At least one element in the source array could not be cast down to the destination array type.
-InvalidCast_Empty = Object cannot be cast to Empty.
-InvalidCast_FromDBNull = Object cannot be cast from DBNull to other types.
-InvalidCast_FromTo = Invalid cast from '{0}' to '{1}'.
-InvalidCast_IConvertible = Object must implement IConvertible.
-InvalidCast_OATypeMismatch = OleAut reported a type mismatch.
-InvalidCast_StoreArrayElement = Object cannot be stored in an array of this type.
-InvalidCast_CannotCoerceByRefVariant = Object cannot be coerced to the original type of the ByRef VARIANT it was obtained from.
-InvalidCast_CannotCastNullToValueType = Null object cannot be converted to a value type.
-#if FEATURE_COMINTEROP
-InvalidCast_WinRTIPropertyValueElement = Object in an IPropertyValue is of type '{0}', which cannot be converted to a '{1}'.
-InvalidCast_WinRTIPropertyValueCoersion = Object in an IPropertyValue is of type '{0}' with value '{1}', which cannot be converted to a '{2}'.
-InvalidCast_WinRTIPropertyValueArrayCoersion = Object in an IPropertyValue is of type '{0}' which cannot be convereted to a '{1}' due to array element '{2}': {3}.
-#endif // FEATURE_COMINTEROP
-
-; InvalidOperationException
-InvalidOperation_ActivationArgsAppTrustMismatch = The activation arguments and application trust for the AppDomain must correspond to the same application identity.
-InvalidOperation_AddContextFrozen = Attempted to add properties to a frozen context.
-InvalidOperation_AppDomainSandboxAPINeedsExplicitAppBase = This API requires the ApplicationBase to be specified explicitly in the AppDomainSetup parameter.
-InvalidOperation_CantCancelCtrlBreak = Applications may not prevent control-break from terminating their process.
-InvalidOperation_CalledTwice = The method cannot be called twice on the same instance.
-InvalidOperation_CollectionCorrupted = A prior operation on this collection was interrupted by an exception. Collection's state is no longer trusted.
-InvalidOperation_CriticalTransparentAreMutuallyExclusive = SecurityTransparent and SecurityCritical attributes cannot be applied to the assembly scope at the same time.
-InvalidOperation_SubclassedObject = Cannot set sub-classed {0} object to {1} object.
-InvalidOperation_ExceptionStateCrossAppDomain = Thread.ExceptionState cannot access an ExceptionState from a different AppDomain.
-InvalidOperation_DebuggerLaunchFailed = Debugger unable to launch.
-InvalidOperation_ApartmentStateSwitchFailed = Failed to set the specified COM apartment state.
-InvalidOperation_EmptyQueue = Queue empty.
-InvalidOperation_EmptyStack = Stack empty.
-InvalidOperation_CannotRemoveFromStackOrQueue = Removal is an invalid operation for Stack or Queue.
-InvalidOperation_EnumEnded = Enumeration already finished.
-InvalidOperation_EnumFailedVersion = Collection was modified; enumeration operation may not execute.
-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.
-InvalidOperation_RegRemoveSubKey = Registry key has subkeys and recursive removes are not supported by this method.
-InvalidOperation_IComparerFailed = Failed to compare two elements in the array.
-InvalidOperation_InternalState = Invalid internal state.
-InvalidOperation_DuplicatePropertyName = Another property by this name already exists.
-InvalidOperation_NotCurrentDomain = You can only define a dynamic assembly on the current AppDomain.
-InvalidOperation_ContextAlreadyFrozen = Context is already frozen.
-InvalidOperation_WriteOnce = This property has already been set and cannot be modified.
-InvalidOperation_MethodBaked = Type definition of the method is complete.
-InvalidOperation_MethodHasBody = Method already has a body.
-InvalidOperation_ModificationOfNonCanonicalAcl = This access control list is not in canonical form and therefore cannot be modified.
-InvalidOperation_Method = This method is not supported by the current object.
-InvalidOperation_NotADebugModule = Not a debug ModuleBuilder.
-InvalidOperation_NoMultiModuleAssembly = You cannot have more than one dynamic module in each dynamic assembly in this version of the runtime.
-InvalidOperation_OpenLocalVariableScope = Local variable scope was not properly closed.
-InvalidOperation_SetVolumeLabelFailed = Volume labels can only be set for writable local volumes.
-InvalidOperation_SetData = An additional permission should not be supplied for setting loader information.
-InvalidOperation_SetData_OnlyOnce = SetData can only be used to set the value of a given name once.
-InvalidOperation_SetData_OnlyLocationURI = SetData cannot be used to set the value for '{0}'.
-InvalidOperation_TypeHasBeenCreated = Unable to change after type has been created.
-InvalidOperation_TypeNotCreated = Type has not been created.
-InvalidOperation_NoUnderlyingTypeOnEnum = Underlying type information on enumeration is not specified.
-InvalidOperation_ResMgrBadResSet_Type = '{0}': ResourceSet derived classes must provide a constructor that takes a String file name and a constructor that takes a Stream.
-InvalidOperation_AssemblyHasBeenSaved = Assembly '{0}' has been saved.
-InvalidOperation_ModuleHasBeenSaved = Module '{0}' has been saved.
-InvalidOperation_CannotAlterAssembly = Unable to alter assembly information.
-InvalidOperation_BadTransientModuleReference = Unable to make a reference to a transient module from a non-transient module.
-InvalidOperation_BadILGeneratorUsage = ILGenerator usage is invalid.
-InvalidOperation_BadInstructionOrIndexOutOfBound = MSIL instruction is invalid or index is out of bounds.
-InvalidOperation_ShouldNotHaveMethodBody = Method body should not exist.
-InvalidOperation_EntryMethodNotDefinedInAssembly = Entry method is not defined in the same assembly.
-InvalidOperation_CantSaveTransientAssembly = Cannot save a transient assembly.
-InvalidOperation_BadResourceContainer = Unable to add resource to transient module or transient assembly.
-InvalidOperation_CantInstantiateAbstractClass = Instances of abstract classes cannot be created.
-InvalidOperation_CantInstantiateFunctionPointer = Instances of function pointers cannot be created.
-InvalidOperation_BadTypeAttributesNotAbstract = Type must be declared abstract if any of its methods are abstract.
-InvalidOperation_BadInterfaceNotAbstract = Interface must be declared abstract.
-InvalidOperation_ConstructorNotAllowedOnInterface = Interface cannot have constructors.
-InvalidOperation_BadMethodBody = Method '{0}' cannot have a method body.
-InvalidOperation_MetaDataError = Metadata operation failed.
-InvalidOperation_BadEmptyMethodBody = Method '{0}' does not have a method body.
-InvalidOperation_EndInvokeCalledMultiple = EndInvoke can only be called once for each asynchronous operation.
-InvalidOperation_EndReadCalledMultiple = EndRead can only be called once for each asynchronous operation.
-InvalidOperation_EndWriteCalledMultiple = EndWrite can only be called once for each asynchronous operation.
-InvalidOperation_AsmLoadedForReflectionOnly = Assembly has been loaded as ReflectionOnly. This API requires an assembly capable of execution.
-InvalidOperation_NoAsmName = Assembly does not have an assembly name. In order to be registered for use by COM, an assembly must have a valid assembly name.
-InvalidOperation_NoAsmCodeBase = Assembly does not have a code base.
-InvalidOperation_HandleIsNotInitialized = Handle is not initialized.
-InvalidOperation_HandleIsNotPinned = Handle is not pinned.
-InvalidOperation_SlotHasBeenFreed = LocalDataStoreSlot storage has been freed.
-InvalidOperation_GlobalsHaveBeenCreated = Type definition of the global function has been completed.
-InvalidOperation_NotAVarArgCallingConvention = Calling convention must be VarArgs.
-InvalidOperation_CannotImportGlobalFromDifferentModule = Unable to import a global method or field from a different module.
-InvalidOperation_NonStaticComRegFunction = COM register function must be static.
-InvalidOperation_NonStaticComUnRegFunction = COM unregister function must be static.
-InvalidOperation_InvalidComRegFunctionSig = COM register function must have a System.Type parameter and a void return type.
-InvalidOperation_InvalidComUnRegFunctionSig = COM unregister function must have a System.Type parameter and a void return type.
-InvalidOperation_MultipleComRegFunctions = Type '{0}' has more than one COM registration function.
-InvalidOperation_MultipleComUnRegFunctions = Type '{0}' has more than one COM unregistration function.
-InvalidOperation_MustCallInitialize = You must call Initialize on this object instance before using it.
-InvalidOperation_MustLockForReadOrWrite = Object must be locked for read or write.
-InvalidOperation_MustLockForWrite = Object must be locked for read.
-InvalidOperation_NoValue = Nullable object must have a value.
-InvalidOperation_ResourceNotStream_Name = Resource '{0}' was not a Stream - call GetObject instead.
-InvalidOperation_ResourceNotString_Name = Resource '{0}' was not a String - call GetObject instead.
-InvalidOperation_ResourceNotString_Type = Resource was of type '{0}' instead of String - call GetObject instead.
-InvalidOperation_ResourceWriterSaved = The resource writer has already been closed and cannot be edited.
-InvalidOperation_UnderlyingArrayListChanged = This range in the underlying list is invalid. A possible cause is that elements were removed.
-InvalidOperation_AnonymousCannotImpersonate = An anonymous identity cannot perform an impersonation.
-InvalidOperation_DefaultConstructorILGen = Unable to access ILGenerator on a constructor created with DefineDefaultConstructor.
-InvalidOperation_DefaultConstructorDefineBody = The method body of the default constructor cannot be changed.
-InvalidOperation_ComputerName = Computer name could not be obtained.
-InvalidOperation_MismatchedAsyncResult = The IAsyncResult object provided does not match this delegate.
-InvalidOperation_PIAMustBeStrongNamed = Primary interop assemblies must be strongly named.
-InvalidOperation_HashInsertFailed = Hashtable insert failed. Load factor too high. The most common cause is multiple threads writing to the Hashtable simultaneously.
-InvalidOperation_UnknownEnumType = Unknown enum type.
-InvalidOperation_GetVersion = OSVersion's call to GetVersionEx failed.
-InvalidOperation_DateTimeParsing = Internal Error in DateTime and Calendar operations.
-InvalidOperation_UserDomainName = UserDomainName native call failed.
-InvalidOperation_WaitOnTransparentProxy = Cannot wait on a transparent proxy.
-InvalidOperation_NoPublicAddMethod = Cannot add the event handler since no public add method exists for the event.
-InvalidOperation_NoPublicRemoveMethod = Cannot remove the event handler since no public remove method exists for the event.
-InvalidOperation_NotSupportedOnWinRTEvent = Adding or removing event handlers dynamically is not supported on WinRT events.
-InvalidOperation_ConsoleKeyAvailableOnFile = Cannot see if a key has been pressed when either application does not have a console or when console input has been redirected from a file. Try Console.In.Peek.
-InvalidOperation_ConsoleReadKeyOnFile = Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.
-InvalidOperation_ThreadWrongThreadStart = The thread was created with a ThreadStart delegate that does not accept a parameter.
-InvalidOperation_ThreadAPIsNotSupported = Use CompressedStack.(Capture/Run) or ExecutionContext.(Capture/Run) APIs instead.
-InvalidOperation_NotNewCaptureContext = Cannot apply a context that has been marshaled across AppDomains, that was not acquired through a Capture operation or that has already been the argument to a Set call.
-InvalidOperation_NullContext = Cannot call Set on a null context
-InvalidOperation_CannotCopyUsedContext = Only newly captured contexts can be copied
-InvalidOperation_CannotUseSwitcherOtherThread = Undo operation must be performed on the thread where the corresponding context was Set.
-InvalidOperation_SwitcherCtxMismatch = The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
-InvalidOperation_CannotOverrideSetWithoutRevert = Must override both HostExecutionContextManager.SetHostExecutionContext and HostExecutionContextManager.Revert.
-InvalidOperation_CannotUseAFCOtherThread = AsyncFlowControl object must be used on the thread where it was created.
-InvalidOperation_CannotRestoreUnsupressedFlow = Cannot restore context flow when it is not suppressed.
-InvalidOperation_CannotSupressFlowMultipleTimes = Context flow is already suppressed.
-InvalidOperation_CannotUseAFCMultiple = AsyncFlowControl object can be used only once to call Undo().
-InvalidOperation_AsyncFlowCtrlCtxMismatch = AsyncFlowControl objects can be used to restore flow only on the Context that had its flow suppressed.
-InvalidOperation_TimeoutsNotSupported = Timeouts are not supported on this stream.
-InvalidOperation_Overlapped_Pack = Cannot pack a packed Overlapped again.
-InvalidOperation_OnlyValidForDS = Adding ACEs with Object Flags and Object GUIDs is only valid for directory-object ACLs.
-InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple = Either the IAsyncResult object did not come from the corresponding async method on this type, or EndRead was called multiple times with the same IAsyncResult.
-InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple = Either the IAsyncResult object did not come from the corresponding async method on this type, or EndWrite was called multiple times with the same IAsyncResult.
-InvalidOperation_WrongAsyncResultOrEndCalledMultiple = Either the IAsyncResult object did not come from the corresponding async method on this type, or the End method was called multiple times with the same IAsyncResult.
-InvalidOperation_NoSecurityDescriptor = The object does not contain a security descriptor.
-InvalidOperation_NotAllowedInReflectionOnly = The requested operation is invalid in the ReflectionOnly context.
-InvalidOperation_NotAllowedInDynamicMethod = The requested operation is invalid for DynamicMethod.
-InvalidOperation_PropertyInfoNotAvailable = This API does not support PropertyInfo tokens.
-InvalidOperation_EventInfoNotAvailable = This API does not support EventInfo tokens.
-InvalidOperation_UnexpectedWin32Error = Unexpected error when calling an operating system function. The returned error code is 0x{0:x}.
-InvalidOperation_AssertTransparentCode = Cannot perform CAS Asserts in Security Transparent methods
-InvalidOperation_NullModuleHandle = The requested operation is invalid when called on a null ModuleHandle.
-InvalidOperation_NotWithConcurrentGC = This API is not available when the concurrent GC is enabled.
-InvalidOperation_WithoutARM = This API is not available when AppDomain Resource Monitoring is not turned on.
-InvalidOperation_NotGenericType = This operation is only valid on generic types.
-InvalidOperation_TypeCannotBeBoxed = The given type cannot be boxed.
-InvalidOperation_HostModifiedSecurityState = The security state of an AppDomain was modified by an AppDomainManager configured with the NoSecurityChanges flag.
-InvalidOperation_StrongNameKeyPairRequired = A strong name key pair is required to emit a strong-named dynamic assembly.
-#if FEATURE_COMINTEROP
-InvalidOperation_EventTokenTableRequiresDelegate = Type '{0}' is not a delegate type. EventTokenTable may only be used with delegate types.
-#endif // FEATURE_COMINTEROP
-InvalidOperation_NullArray = The underlying array is null.
-;system.security.claims
-InvalidOperation_ClaimCannotBeRemoved = The Claim '{0}' was not able to be removed. It is either not part of this Identity or it is a claim that is owned by the Principal that contains this Identity. For example, the Principal will own the claim when creating a GenericPrincipal with roles. The roles will be exposed through the Identity that is passed in the constructor, but not actually owned by the Identity. Similar logic exists for a RolePrincipal.
-InvalidOperationException_ActorGraphCircular = Actor cannot be set so that circular directed graph will exist chaining the subjects together.
-InvalidOperation_AsyncIOInProgress = The stream is currently in use by a previous operation on the stream.
-InvalidOperation_APIInvalidForCurrentContext = The API '{0}' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information.
-
-; InvalidProgramException
-InvalidProgram_Default = Common Language Runtime detected an invalid program.
-
-; Isolated Storage
-#if FEATURE_ISOSTORE
-IsolatedStorage_AssemblyMissingIdentity = Unable to determine assembly of the caller.
-IsolatedStorage_ApplicationMissingIdentity = Unable to determine application identity of the caller.
-IsolatedStorage_DomainMissingIdentity = Unable to determine domain of the caller.
-IsolatedStorage_AssemblyGrantSet = Unable to determine granted permission for assembly.
-IsolatedStorage_DomainGrantSet = Unable to determine granted permission for domain.
-IsolatedStorage_ApplicationGrantSet = Unable to determine granted permission for application.
-IsolatedStorage_Init = Initialization failed.
-IsolatedStorage_ApplicationNoEvidence = Unable to determine identity of application.
-IsolatedStorage_AssemblyNoEvidence = Unable to determine identity of assembly.
-IsolatedStorage_DomainNoEvidence = Unable to determine the identity of domain.
-IsolatedStorage_DeleteDirectories = Unable to delete; directory or files in the directory could be in use.
-IsolatedStorage_DeleteFile = Unable to delete file.
-IsolatedStorage_CreateDirectory = Unable to create directory.
-IsolatedStorage_DeleteDirectory = Unable to delete, directory not empty or does not exist.
-IsolatedStorage_Operation_ISFS = Operation not permitted on IsolatedStorageFileStream.
-IsolatedStorage_Operation = Operation not permitted.
-IsolatedStorage_Path = Path must be a valid file name.
-IsolatedStorage_FileOpenMode = Invalid mode, see System.IO.FileMode.
-IsolatedStorage_SeekOrigin = Invalid origin, see System.IO.SeekOrigin.
-IsolatedStorage_Scope_U_R_M = Invalid scope, expected User, User|Roaming or Machine.
-IsolatedStorage_Scope_Invalid = Invalid scope.
-IsolatedStorage_Exception = An error occurred while accessing IsolatedStorage.
-IsolatedStorage_QuotaIsUndefined = {0} is not defined for this store. An operation was performed that requires access to {0}. Stores obtained using enumeration APIs do not have a well-defined {0}, since partial evidence is used to open the store.
-IsolatedStorage_CurrentSizeUndefined = Current size cannot be determined for this store.
-IsolatedStorage_DomainUndefined = Domain cannot be determined on an Assembly or Application store.
-IsolatedStorage_ApplicationUndefined = Application cannot be determined on an Assembly or Domain store.
-IsolatedStorage_AssemblyUndefined = Assembly cannot be determined for an Application store.
-IsolatedStorage_StoreNotOpen = Store must be open for this operation.
-IsolatedStorage_OldQuotaLarger = The new quota must be larger than the old quota.
-IsolatedStorage_UsageWillExceedQuota = There is not enough free space to perform the operation.
-IsolatedStorage_NotValidOnDesktop = The Site scope is currently not supported.
-IsolatedStorage_OnlyIncreaseUserApplicationStore = Increasing the quota of this scope is not supported. Only the user application scope’s quota can be increased.
-#endif // FEATURE_ISOSTORE
-
-; Verification Exception
-Verification_Exception = Operation could destabilize the runtime.
-
-; IL stub marshaler exceptions
-Marshaler_StringTooLong = Marshaler restriction: Excessively long string.
-
-; Missing (General)
-MissingConstructor_Name = Constructor on type '{0}' not found.
-MissingField = Field not found.
-MissingField_Name = Field '{0}' not found.
-MissingMember = Member not found.
-MissingMember_Name = Member '{0}' not found.
-MissingMethod_Name = Method '{0}' not found.
-MissingModule = Module '{0}' not found.
-MissingType = Type '{0}' not found.
-
-; MissingManifestResourceException
-Arg_MissingManifestResourceException = Unable to find manifest resource.
-MissingManifestResource_LooselyLinked = Could not find a manifest resource entry called "{0}" in assembly "{1}". Please check spelling, capitalization, and build rules to ensure "{0}" is being linked into the assembly.
-MissingManifestResource_NoNeutralAsm = Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "{0}" was correctly embedded or linked into assembly "{1}" at compile time, or that all the satellite assemblies required are loadable and fully signed.
-MissingManifestResource_NoNeutralDisk = Could not find any resources appropriate for the specified culture (or the neutral culture) on disk.
-MissingManifestResource_MultipleBlobs = A case-insensitive lookup for resource file "{0}" in assembly "{1}" found multiple entries. Remove the duplicates or specify the exact case.
-MissingManifestResource_ResWFileNotLoaded = Unable to load resources for resource file "{0}" in package "{1}".
-MissingManifestResource_NoPRIresources = Unable to open Package Resource Index.
-
-; MissingMember
-MissingMemberTypeRef = FieldInfo does not match the target Type.
-MissingMemberNestErr = TypedReference can only be made on nested value Types.
-
-; MissingSatelliteAssemblyException
-MissingSatelliteAssembly_Default = Resource lookup fell back to the ultimate fallback resources in a satellite assembly, but that satellite either was not found or could not be loaded. Please consider reinstalling or repairing the application.
-MissingSatelliteAssembly_Culture_Name = The satellite assembly named "{1}" for fallback culture "{0}" either could not be found or could not be loaded. This is generally a setup problem. Please consider reinstalling or repairing the application.
-
-; MulticastNotSupportedException
-Multicast_Combine = Delegates that are not of type MulticastDelegate may not be combined.
-
-; NotImplementedException
-Arg_NotImplementedException = The method or operation is not implemented.
-NotImplemented_ResourcesLongerThan2^63 = Resource files longer than 2^63 bytes are not currently implemented.
-
-; NotSupportedException
-NotSupported_NYI = This feature is not currently implemented.
-NotSupported_AbstractNonCLS = This non-CLS method is not implemented.
-NotSupported_ChangeType = ChangeType operation is not supported.
-NotSupported_ByRefLike = Cannot create boxed ByRef-like values.
-NotSupported_ByRefLike[] = Cannot create arrays of ByRef-like values.
-NotSupported_OpenType = Cannot create arrays of open type.
-NotSupported_DBNullSerial = Only one DBNull instance may exist, and calls to DBNull deserialization methods are not allowed.
-NotSupported_DelegateSerHolderSerial = DelegateSerializationHolder objects are designed to represent a delegate during serialization and are not serializable themselves.
-NotSupported_DelegateCreationFromPT = Application code cannot use Activator.CreateInstance to create types that derive from System.Delegate. Delegate.CreateDelegate can be used instead.
-NotSupported_EncryptionNeedsNTFS = File encryption support only works on NTFS partitions.
-NotSupported_FileStreamOnNonFiles = FileStream was asked to open a device that was not a file. For support for devices like 'com1:' or 'lpt1:', call CreateFile, then use the FileStream constructors that take an OS handle as an IntPtr.
-NotSupported_FixedSizeCollection = Collection was of a fixed size.
-NotSupported_KeyCollectionSet = Mutating a key collection derived from a dictionary is not allowed.
-NotSupported_ValueCollectionSet = Mutating a value collection derived from a dictionary is not allowed.
-NotSupported_MemStreamNotExpandable = Memory stream is not expandable.
-NotSupported_ObsoleteResourcesFile = Found an obsolete .resources file in assembly '{0}'. Rebuild that .resources file then rebuild that assembly.
-NotSupported_OleAutBadVarType = The given Variant type is not supported by this OleAut function.
-NotSupported_PopulateData = This Surrogate does not support PopulateData().
-NotSupported_ReadOnlyCollection = Collection is read-only.
-NotSupported_RangeCollection = The specified operation is not supported on Ranges.
-NotSupported_SortedListNestedWrite = This operation is not supported on SortedList nested types because they require modifying the original SortedList.
-NotSupported_SubclassOverride = Derived classes must provide an implementation.
-NotSupported_TypeCannotDeserialized = Direct deserialization of type '{0}' is not supported.
-NotSupported_UnreadableStream = Stream does not support reading.
-NotSupported_UnseekableStream = Stream does not support seeking.
-NotSupported_UnwritableStream = Stream does not support writing.
-NotSupported_CannotWriteToBufferedStreamIfReadBufferCannotBeFlushed = Cannot write to a BufferedStream while the read buffer is not empty if the underlying stream is not seekable. Ensure that the stream underlying this BufferedStream can seek or avoid interleaving read and write operations on this BufferedStream.
-NotSupported_Method = Method is not supported.
-NotSupported_Constructor = Object cannot be created through this constructor.
-NotSupported_DynamicModule = The invoked member is not supported in a dynamic module.
-NotSupported_TypeNotYetCreated = The invoked member is not supported before the type is created.
-NotSupported_SymbolMethod = Not supported in an array method of a type definition that is not complete.
-NotSupported_NotDynamicModule = The MethodRental.SwapMethodBody method can only be called to swap the method body of a method in a dynamic module.
-NotSupported_DynamicAssembly = The invoked member is not supported in a dynamic assembly.
-NotSupported_NotAllTypesAreBaked = Type '{0}' was not completed.
-NotSupported_CannotSaveModuleIndividually = Unable to save a ModuleBuilder if it was created underneath an AssemblyBuilder. Call Save on the AssemblyBuilder instead.
-NotSupported_MaxWaitHandles = The number of WaitHandles must be less than or equal to 64.
-NotSupported_IllegalOneByteBranch = Illegal one-byte branch at position: {0}. Requested branch was: {1}.
-NotSupported_OutputStreamUsingTypeBuilder = Output streams do not support TypeBuilders.
-NotSupported_ValueClassCM = Custom marshalers for value types are not currently supported.
-NotSupported_Void[] = Arrays of System.Void are not supported.
-NotSupported_NoParentDefaultConstructor = Parent does not have a default constructor. The default constructor must be explicitly defined.
-NotSupported_NonReflectedType = Not supported in a non-reflected type.
-NotSupported_GlobalFunctionNotBaked = The type definition of the global function is not completed.
-NotSupported_SecurityPermissionUnion = Union is not implemented.
-NotSupported_UnitySerHolder = The UnitySerializationHolder object is designed to transmit information about other types and is not serializable itself.
-NotSupported_UnknownTypeCode = TypeCode '{0}' was not valid.
-NotSupported_WaitAllSTAThread = WaitAll for multiple handles on a STA thread is not supported.
-NotSupported_SignalAndWaitSTAThread = SignalAndWait on a STA thread is not supported.
-NotSupported_CreateInstanceWithTypeBuilder = CreateInstance cannot be used with an object of type TypeBuilder.
-NotSupported_NonUrlAttrOnMBR = UrlAttribute is the only attribute supported for MarshalByRefObject.
-NotSupported_ActivAttrOnNonMBR = Activation Attributes are not supported for types not deriving from MarshalByRefObject.
-NotSupported_ActivForCom = Activation Attributes not supported for COM Objects.
-NotSupported_NoCodepageData = No data is available for encoding {0}. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
-NotSupported_CodePage50229 = The ISO-2022-CN Encoding (Code page 50229) is not supported.
-NotSupported_DynamicAssemblyNoRunAccess = Cannot execute code on a dynamic assembly without run access.
-NotSupported_IDispInvokeDefaultMemberWithNamedArgs = Invoking default method with named arguments is not supported.
-NotSupported_Type = Type is not supported.
-NotSupported_GetMethod = The 'get' method is not supported on this property.
-NotSupported_SetMethod = The 'set' method is not supported on this property.
-NotSupported_DeclarativeUnion = Declarative unionizing of these permissions is not supported.
-NotSupported_StringComparison = The string comparison type passed in is currently not supported.
-NotSupported_WrongResourceReader_Type = This .resources file should not be read with this reader. The resource reader type is "{0}".
-NotSupported_MustBeModuleBuilder = Module argument must be a ModuleBuilder.
-NotSupported_CallToVarArg = Vararg calling convention not supported.
-NotSupported_TooManyArgs = Stack size too deep. Possibly too many arguments.
-NotSupported_DeclSecVarArg = Assert, Deny, and PermitOnly are not supported on methods with a Vararg calling convention.
-NotSupported_AmbiguousIdentity = The operation is ambiguous because the permission represents multiple identities.
-NotSupported_DynamicMethodFlags = Wrong MethodAttributes or CallingConventions for DynamicMethod. Only public, static, standard supported
-NotSupported_GlobalMethodSerialization = Serialization of global methods (including implicit serialization via the use of asynchronous delegates) is not supported.
-NotSupported_InComparableType = A type must implement IComparable<T> or IComparable to support comparison.
-NotSupported_ManagedActivation = Cannot create uninitialized instances of types requiring managed activation.
-NotSupported_ByRefReturn = ByRef return value not supported in reflection invocation.
-NotSupported_DelegateMarshalToWrongDomain = Delegates cannot be marshaled from native code into a domain other than their home domain.
-NotSupported_ResourceObjectSerialization = Cannot read resources that depend on serialization.
-NotSupported_One = The arithmetic type '{0}' cannot represent the number one.
-NotSupported_Zero = The arithmetic type '{0}' cannot represent the number zero.
-NotSupported_MaxValue = The arithmetic type '{0}' does not have a maximum value.
-NotSupported_MinValue = The arithmetic type '{0}' does not have a minimum value.
-NotSupported_PositiveInfinity = The arithmetic type '{0}' cannot represent positive infinity.
-NotSupported_NegativeInfinity = The arithmetic type '{0}' cannot represent negative infinity.
-NotSupported_UmsSafeBuffer = This operation is not supported for an UnmanagedMemoryStream created from a SafeBuffer.
-NotSupported_Reading = Accessor does not support reading.
-NotSupported_Writing = Accessor does not support writing.
-NotSupported_UnsafePointer = This accessor was created with a SafeBuffer; use the SafeBuffer to gain access to the pointer.
-NotSupported_CollectibleCOM = COM Interop is not supported for collectible types.
-NotSupported_CollectibleAssemblyResolve = Resolving to a collectible assembly is not supported.
-NotSupported_CollectibleBoundNonCollectible = A non-collectible assembly may not reference a collectible assembly.
-NotSupported_CollectibleDelegateMarshal = Delegate marshaling for types within collectible assemblies is not supported.
-NotSupported_NonStaticMethod = Non-static methods with NativeCallableAttribute are not supported.
-NotSupported_NativeCallableTarget = Methods with NativeCallableAttribute cannot be used as delegate target.
-NotSupported_GenericMethod = Generic methods with NativeCallableAttribute are not supported.
-NotSupported_NonBlittableTypes = Non-blittable parameter types are not supported for NativeCallable methods.
-
-#if FEATURE_WINDOWSPHONE
-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.
-#endif
-#if FEATURE_COMINTEROP
-NotSupported_WinRT_PartialTrust = Windows Runtime is not supported in partial trust.
-#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
-#if FEATURE_WINDOWSPHONE
-; Not referring to "Windows Phone" in the messages, as FEATURE_WINDOWSPHONE is defined for .NET Core as well.
-NotSupported_WindowsPhone = {0} is not supported.
-NotSupported_AssemblyLoadCodeBase = Assembly.Load with a Codebase is not supported.
-#endif
-
-; TypeLoadException
-TypeLoad_ResolveType = Could not resolve type '{0}'.
-TypeLoad_ResolveTypeFromAssembly = Could not resolve type '{0}' in assembly '{1}'.
-TypeLoad_ResolveNestedType = Could not resolve nested type '{0}' in type "{1}'.
-FileNotFound_ResolveAssembly = Could not resolve assembly '{0}'.
-
-; NullReferenceException
-NullReference_This = The pointer for this method was null.
-
-; ObjectDisposedException
-ObjectDisposed_Generic = Cannot access a disposed object.
-ObjectDisposed_FileClosed = Cannot access a closed file.
-ObjectDisposed_ObjectName_Name = Object name: '{0}'.
-ObjectDisposed_ReaderClosed = Cannot read from a closed TextReader.
-ObjectDisposed_ResourceSet = Cannot access a closed resource set.
-ObjectDisposed_RegKeyClosed = Cannot access a closed registry key.
-ObjectDisposed_StreamClosed = Cannot access a closed Stream.
-ObjectDisposed_WriterClosed = Cannot write to a closed TextWriter.
-ObjectDisposed_ViewAccessorClosed = Cannot access a closed accessor.
-
-; OperationCanceledException
-OperationCanceled = The operation was canceled.
-
-; OutOfMemoryException
-OutOfMemory_GCHandleMDA = The GCHandle MDA has run out of available cookies.
-
-; OverflowException
-Overflow_Byte = Value was either too large or too small for an unsigned byte.
-Overflow_Char = Value was either too large or too small for a character.
-Overflow_Currency = Value was either too large or too small for a Currency.
-Overflow_Decimal = Value was either too large or too small for a Decimal.
-Overflow_Int16 = Value was either too large or too small for an Int16.
-Overflow_Int32 = Value was either too large or too small for an Int32.
-Overflow_Int64 = Value was either too large or too small for an Int64.
-Overflow_NegateTwosCompNum = Negating the minimum value of a twos complement number is invalid.
-Overflow_NegativeUnsigned = The string was being parsed as an unsigned number and could not have a negative sign.
-Overflow_SByte = Value was either too large or too small for a signed byte.
-Overflow_Single = Value was either too large or too small for a Single.
-Overflow_Double = Value was either too large or too small for a Double.
-Overflow_TimeSpanTooLong = TimeSpan overflowed because the duration is too long.
-Overflow_TimeSpanElementTooLarge = The TimeSpan could not be parsed because at least one of the numeric components is out of range or contains too many digits.
-Overflow_Duration = The duration cannot be returned for TimeSpan.MinValue because the absolute value of TimeSpan.MinValue exceeds the value of TimeSpan.MaxValue.
-Overflow_UInt16 = Value was either too large or too small for a UInt16.
-Overflow_UInt32 = Value was either too large or too small for a UInt32.
-Overflow_UInt64 = Value was either too large or too small for a UInt64.
-
-; PlatformNotsupportedException
-PlatformNotSupported_RequiresLonghorn = This operation is only supported on Windows Vista and above.
-PlatformNotSupported_RequiresNT = This operation is only supported on Windows 2000, Windows XP, and higher.
-PlatformNotSupported_RequiresW2kSP3 = This operation is only supported on Windows 2000 SP3 or later operating systems.
-#if FEATURE_COMINTEROP
-PlatformNotSupported_WinRT = Windows Runtime is not supported on this operating system.
-#endif // FEATURE_COMINTEROP
-
-; PolicyException
-; This still appears in bcl.small but should go away eventually
-Policy_Default = Error occurred while performing a policy operation.
-Policy_CannotLoadSemiTrustAssembliesDuringInit = All assemblies loaded as part of AppDomain initialization must be fully trusted.
-#if FEATURE_IMPERSONATION
-Policy_PrincipalTwice = Default principal object cannot be set twice.
-#endif // FEATURE_IMPERSONATION
-#if FEATURE_CAS_POLICY
-Policy_PolicyAlreadySet = Policy for this domain cannot be set twice.
-Policy_NoExecutionPermission = Execution permission cannot be acquired.
-Policy_NoRequiredPermission = Required permissions cannot be acquired.
-Policy_MultipleExclusive = More than one exclusive group is not allowed.
-Policy_RecoverNotFileBased = PolicyLevel object not based on a file cannot be recovered.
-Policy_RecoverNoConfigFile = No old configuration file exists to recover.
-Policy_UnableToSave = Policy level '{0}' could not be saved: {1}.
-Policy_BadXml = Policy configuration XML is invalid. The required tag '{0}' is missing.
-Policy_NonFullTrustAssembly = Policy references an assembly not in the full trust assemblies list.
-Policy_MissingActivationContextInAppEvidence = The application evidence does not contain a Fusion activation context.
-Policy_NoTrustManager = A trust manager could not be loaded for this application.
-Policy_GrantSetDoesNotMatchDomain = An assembly was provided an invalid grant set by runtime host '{0}'. In a homogenous AppDomain, the only valid grant sets are FullTrust and the AppDomain's sandbox grant set.
-#endif // FEATURE_CAS_POLICY
-Policy_SaveNotFileBased = PolicyLevel object not based on a file cannot be saved.
-Policy_AppTrustMustGrantAppRequest = ApplicationTrust grant set does not contain ActivationContext's minimum request set.
-
-Error_SecurityPolicyFileParse = Error occurred while parsing the '{0}' policy level. The default policy level was used instead.
-Error_SecurityPolicyFileParseEx = Error '{1}' occurred while parsing the '{0}' policy level. The default policy level was used instead.
-
-#if FEATURE_CAS_POLICY
-Policy_EvidenceMustBeSerializable = Objects used as evidence must be serializable.
-Policy_DuplicateEvidence = The evidence collection already contains evidence of type '{0}'. Multiple pieces of the same type of evidence are not allowed.
-Policy_IncorrectHostEvidence = Runtime host '{0}' returned evidence of type '{1}' from a request for evidence of type '{2}'.
-Policy_NullHostEvidence = Runtime host '{0}' returned null when asked for assembly evidence for assembly '{1}'.
-Policy_NullHostGrantSet = Runtime host '{0}' returned a null grant set from ResolvePolicy.
-#endif // FEATURE_CAS_POLICY
-
-; Policy codegroup and permission set names and descriptions
-#if FEATURE_CAS_POLICY
-Policy_AllCode_Name = All_Code
-Policy_AllCode_DescriptionFullTrust = Code group grants all code full trust and forms the root of the code group tree.
-Policy_AllCode_DescriptionNothing = Code group grants no permissions and forms the root of the code group tree.
-Policy_MyComputer_Name = My_Computer_Zone
-Policy_MyComputer_Description = Code group grants full trust to all code originating on the local computer
-Policy_Intranet_Name = LocalIntranet_Zone
-Policy_Intranet_Description = Code group grants the intranet permission set to code from the intranet zone. This permission set grants intranet code the right to use isolated storage, full UI access, some capability to do reflection, and limited access to environment variables.
-Policy_IntranetNet_Name = Intranet_Same_Site_Access
-Policy_IntranetNet_Description = All intranet code gets the right to connect back to the site of its origin.
-Policy_IntranetFile_Name = Intranet_Same_Directory_Access
-Policy_IntranetFile_Description = All intranet code gets the right to read from its install directory.
-Policy_Internet_Name = Internet_Zone
-Policy_Internet_Description = Code group grants code from the Internet zone the Internet permission set. This permission set grants Internet code the right to use isolated storage and limited UI access.
-Policy_InternetNet_Name = Internet_Same_Site_Access
-Policy_InternetNet_Description = All Internet code gets the right to connect back to the site of its origin.
-Policy_Trusted_Name = Trusted_Zone
-Policy_Trusted_Description = Code from a trusted zone is granted the Internet permission set. This permission set grants the right to use isolated storage and limited UI access.
-Policy_TrustedNet_Name = Trusted_Same_Site_Access
-Policy_TrustedNet_Description = All Trusted Code gets the right to connect back to the site of its origin.
-Policy_Untrusted_Name = Restricted_Zone
-Policy_Untrusted_Description = Code coming from a restricted zone does not receive any permissions.
-Policy_Microsoft_Name = Microsoft_Strong_Name
-Policy_Microsoft_Description = Code group grants full trust to code signed with the Microsoft strong name.
-Policy_Ecma_Name = ECMA_Strong_Name
-Policy_Ecma_Description = Code group grants full trust to code signed with the ECMA strong name.
-
-; Policy permission set descriptions
-Policy_PS_FullTrust = Allows full access to all resources
-Policy_PS_Everything = Allows unrestricted access to all resources covered by built-in permissions
-Policy_PS_Nothing = Denies all resources, including the right to execute
-Policy_PS_Execution = Permits execution
-Policy_PS_SkipVerification = Grants right to bypass the verification
-Policy_PS_Internet = Default rights given to Internet applications
-Policy_PS_LocalIntranet = Default rights given to applications on the local intranet
-
-; default Policy level names
-Policy_PL_Enterprise = Enterprise
-Policy_PL_Machine = Machine
-Policy_PL_User = User
-Policy_PL_AppDomain = AppDomain
-#endif // FEATURE_CAS_POLICY
-
-; RankException
-Rank_MultiDimNotSupported = Only single dimension arrays are supported here.
-Rank_MustMatch = The specified arrays must have the same number of dimensions.
-
-; TypeInitializationException
-TypeInitialization_Default = Type constructor threw an exception.
-TypeInitialization_Type = The type initializer for '{0}' threw an exception.
-
-; TypeLoadException
-
-
-;
-; Reflection exceptions
-;
-RtType.InvalidCaller = Caller is not a friend.
-
-;CustomAttributeFormatException
-RFLCT.InvalidPropFail = '{0}' property specified was not found.
-RFLCT.InvalidFieldFail = '{0}' field specified was not found.
-
-;InvalidFilterCriteriaException
-RFLCT.FltCritString = A String must be provided for the filter criteria.
-RFLCT.FltCritInt = An Int32 must be provided for the filter criteria.
-
-; TargetException
-RFLCT.Targ_ITargMismatch = Object does not match target type.
-RFLCT.Targ_StatMethReqTarg = Non-static method requires a target.
-RFLCT.Targ_StatFldReqTarg = Non-static field requires a target.
-
-;AmbiguousMatchException
-RFLCT.Ambiguous = Ambiguous match found.
-RFLCT.AmbigCust = Multiple custom attributes of the same type found.
-
-;
-; Remoting exceptions
-;
-Remoting_AppDomainUnloaded_ThreadUnwound = The application domain in which the thread was running has been unloaded.
-Remoting_AppDomainUnloaded = The target application domain has been unloaded.
-Remoting_CantRemotePointerType = Pointer types cannot be passed in a remote call.
-Remoting_TypeCantBeRemoted = The given type cannot be passed in a remote call.
-Remoting_Delegate_TooManyTargets = The delegate must have only one target.
-Remoting_InvalidContext = The context is not valid.
-Remoting_InvalidValueTypeFieldAccess = An attempt was made to calculate the address of a value type field on a remote object. This was likely caused by an attempt to directly get or set the value of a field within this embedded value type. Avoid this and instead provide and use access methods for each field in the object that will be accessed remotely.
-Remoting_Message_BadRetValOrOutArg = Bad return value or out-argument inside the return message.
-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
-;
-Resources_StreamNotValid = Stream is not a valid resource file.
-ResourceReaderIsClosed = ResourceReader is closed.
-
-; RuntimeWrappedException
-RuntimeWrappedException = An object that does not derive from System.Exception has been wrapped in a RuntimeWrappedException.
-
-; UnauthorizedAccessException
-UnauthorizedAccess_MemStreamBuffer = MemoryStream's internal buffer cannot be accessed.
-UnauthorizedAccess_IODenied_Path = Access to the path '{0}' is denied.
-UnauthorizedAccess_IODenied_NoPathName = Access to the path is denied.
-UnauthorizedAccess_RegistryKeyGeneric_Key = Access to the registry key '{0}' is denied.
-UnauthorizedAccess_RegistryNoWrite = Cannot write to the registry key.
-UnauthorizedAccess_SystemDomain = Cannot execute an assembly in the system domain.
-
-;
-; Security exceptions
-;
-
-;SecurityException
-; These still appear in bcl.small but should go away eventually
-Security_Generic = Request for the permission of type '{0}' failed.
-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
-;
-
-HostProtection_HostProtection = Attempted to perform an operation that was forbidden by the CLR host.
-HostProtection_ProtectedResources = The protected resources (only available with full trust) were:
-HostProtection_DemandedResources = The demanded resources were:
-
-;
-; IO exceptions
-;
-
-; EOFException
-IO.EOF_ReadBeyondEOF = Unable to read beyond the end of the stream.
-
-; FileNotFoundException
-IO.FileNotFound = Unable to find the specified file.
-IO.FileNotFound_FileName = Could not find file '{0}'.
-IO.FileName_Name = File name: '{0}'
-IO.FileLoad = Could not load the specified file.
-
-; IOException
-IO.IO_AlreadyExists_Name = Cannot create "{0}" because a file or directory with the same name already exists.
-IO.IO_BindHandleFailed = BindHandle for ThreadPool failed on this handle.
-IO.IO_FileExists_Name = The file '{0}' already exists.
-IO.IO_FileStreamHandlePosition = The OS handle's position is not what FileStream expected. Do not use a handle simultaneously in one FileStream and in Win32 code or another FileStream. This may cause data loss.
-IO.IO_FileTooLong2GB = The file is too long. This operation is currently limited to supporting files less than 2 gigabytes in size.
-IO.IO_FileTooLongOrHandleNotSync = IO operation will not work. Most likely the file will become too long or the handle was not opened to support synchronous IO operations.
-IO.IO_FixedCapacity = Unable to expand length of this stream beyond its capacity.
-IO.IO_InvalidStringLen_Len = BinaryReader encountered an invalid string length of {0} characters.
-IO.IO_NoConsole = There is no console.
-IO.IO_NoPermissionToDirectoryName = <Path discovery permission to the specified directory was denied.>
-IO.IO_SeekBeforeBegin = An attempt was made to move the position before the beginning of the stream.
-IO.IO_SeekAppendOverwrite = Unable seek backward to overwrite data that previously existed in a file opened in Append mode.
-IO.IO_SetLengthAppendTruncate = Unable to truncate data that previously existed in a file opened in Append mode.
-IO.IO_SharingViolation_File = The process cannot access the file '{0}' because it is being used by another process.
-IO.IO_SharingViolation_NoFileName = The process cannot access the file because it is being used by another process.
-IO.IO_StreamTooLong = Stream was too long.
-IO.IO_CannotCreateDirectory = The specified directory '{0}' cannot be created.
-IO.IO_SourceDestMustBeDifferent = Source and destination path must be different.
-IO.IO_SourceDestMustHaveSameRoot = Source and destination path must have identical roots. Move will not work across volumes.
-
-; DirectoryNotFoundException
-IO.DriveNotFound_Drive = Could not find the drive '{0}'. The drive might not be ready or might not be mapped.
-IO.PathNotFound_Path = Could not find a part of the path '{0}'.
-IO.PathNotFound_NoPathName = Could not find a part of the path.
-
-; PathTooLongException
-IO.PathTooLong = The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
-
-#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.
-PrivilegeNotHeld_Named = The process does not possess the '{0}' privilege which is required for this operation.
-
-; General strings used in the IO package
-IO_UnknownFileName = [Unknown]
-IO_StreamWriterBufferedDataLost = A StreamWriter was not closed and all buffered data within that StreamWriter was not flushed to the underlying stream. (This was detected when the StreamWriter was finalized with data in its buffer.) A portion of the data was lost. Consider one of calling Close(), Flush(), setting the StreamWriter's AutoFlush property to true, or allocating the StreamWriter with a "using" statement. Stream type: {0}\r\nFile name: {1}\r\nAllocated from:\r\n {2}
-IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled = callstack information is not captured by default for performance reasons. Please enable captureAllocatedCallStack config switch for streamWriterBufferedDataLost MDA (refer to MSDN MDA documentation for how to do this).
-
-;
-; Serialization Exceptions
-;
-; SerializationException
-Serialization_InvalidData=An error occurred while deserializing the object. The serialized data is corrupt.
-Serialization_InvalidPtrValue = An IntPtr or UIntPtr with an eight byte value cannot be deserialized on a machine with a four byte word size.
-Serialization_MemberTypeNotRecognized = Unknown member type.
-Serialization_InsufficientState = Insufficient state to return the real object.
-Serialization_InvalidFieldState = Object fields may not be properly initialized.
-Serialization_MissField = Field {0} is missing.
-Serialization_NullSignature = The method signature cannot be null.
-Serialization_UnknownMember = Cannot get the member '{0}'.
-Serialization_InsufficientDeserializationState = Insufficient state to deserialize the object. Missing field '{0}'. More information is needed.
-Serialization_UnableToFindModule = The given module {0} cannot be found within the assembly {1}.
-Serialization_InvalidOnDeser = OnDeserialization method was called while the object was not being deserialized.
-Serialization_MissingKeys = The Keys for this Hashtable are missing.
-Serialization_MissingValues = The values for this dictionary are missing.
-Serialization_NullKey = One of the serialized keys is null.
-Serialization_KeyValueDifferentSizes = The keys and values arrays have different sizes.
-Serialization_SameNameTwice = Cannot add the same member twice to a SerializationInfo object.
-Serialization_BadParameterInfo = Non existent ParameterInfo. Position bigger than member's parameters length.
-Serialization_NoParameterInfo = Serialized member does not have a ParameterInfo.
-Serialization_NotFound = Member '{0}' was not found.
-Serialization_StringBuilderMaxCapacity = The serialized MaxCapacity property of StringBuilder must be positive and greater than or equal to the String length.
-Serialization_StringBuilderCapacity = The serialized Capacity property of StringBuilder must be positive, less than or equal to MaxCapacity and greater than or equal to the String length.
-Serialization_InvalidDelegateType = Cannot serialize delegates over unmanaged function pointers, dynamic methods or methods outside the delegate creator's assembly.
-Serialization_OptionalFieldVersionValue = Version value must be positive.
-Serialization_MissingDateTimeData = Invalid serialized DateTime data. Unable to find 'ticks' or 'dateData'.
-Serialization_DateTimeTicksOutOfRange = Invalid serialized DateTime data. Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.
-; The following serialization exception messages appear in native resources too (mscorrc.rc)
-Serialization_MemberOutOfRange = The deserialized value of the member "{0}" in the class "{1}" is out of range.
-
-#if FEATURE_SERIALIZATION
-Serialization_NoID = Object has never been assigned an objectID.
-Serialization_UnknownMemberInfo = Only FieldInfo, PropertyInfo, and SerializationMemberInfo are recognized.
-Serialization_UnableToFixup = Cannot perform fixup.
-Serialization_NoType = Object does not specify a type.
-Serialization_ValueTypeFixup = ValueType fixup on Arrays is not implemented.
-Serialization_PartialValueTypeFixup = Fixing up a partially available ValueType chain is not implemented.
-Serialization_InvalidID = Object specifies an invalid ID.
-Serialization_DuplicateSelector = Selector is already on the list of checked selectors.
-Serialization_NoBaseType = Object does not specify a base type.
-Serialization_ArrayNoLength = Array does not specify a length.
-Serialization_CannotGetType = Cannot get the type '{0}'.
-Serialization_AssemblyNotFound = Unable to find assembly '{0}'.
-Serialization_ArrayInvalidLength = Array specifies an invalid length.
-Serialization_MalformedArray = The array information in the stream is invalid.
-Serialization_MultipleMembers = Cannot resolve multiple members with the same name.
-Serialization_ObjectUsedBeforeDeserCallback = An object was used before its deserialization callback ran, which may break higher-level consistency guarantees in the application.
-Serialization_RegisterTwice = An object cannot be registered twice.
-Serialization_IdTooSmall = Object IDs must be greater than zero.
-Serialization_TooManyReferences = The implementation of the IObjectReference interface returns too many nested references to other objects that implement IObjectReference.
-Serialization_NotISer = The given object does not implement the ISerializable interface.
-Serialization_MissingKeyValuePairs = The KeyValuePairs for this Dictionary are missing.
-Serialization_SurrogateCycleInArgument = Selector contained a cycle.
-Serialization_SurrogateCycle = Adding selector will introduce a cycle.
-Serialization_NeverSeen = A fixup is registered to the object with ID {0}, but the object does not appear in the graph.
-Serialization_IORIncomplete = The object with ID {0} implements the IObjectReference interface for which all dependencies cannot be resolved. The likely cause is two instances of IObjectReference that have a mutual dependency on each other.
-Serialization_NotCyclicallyReferenceableSurrogate = {0}.SetObjectData returns a value that is neither null nor equal to the first parameter. Such Surrogates cannot be part of cyclical reference.
-Serialization_ObjectNotSupplied = The object with ID {0} was referenced in a fixup but does not exist.
-Serialization_TooManyElements = The internal array cannot expand to greater than Int32.MaxValue elements.
-Serialization_InvalidType = Only system-provided types can be passed to the GetUninitializedObject method. '{0}' is not a valid instance of a type.
-Serialization_MissingObject = The object with ID {0} was referenced in a fixup but has not been registered.
-Serialization_InvalidFixupType = A member fixup was registered for an object which implements ISerializable or has a surrogate. In this situation, a delayed fixup must be used.
-Serialization_InvalidFixupDiscovered = A fixup on an object implementing ISerializable or having a surrogate was discovered for an object which does not have a SerializationInfo available.
-Serialization_InvalidFormat = The input stream is not a valid binary format. The starting contents (in bytes) are: {0} ...
-Serialization_ParentChildIdentical = The ID of the containing object cannot be the same as the object ID.
-Serialization_IncorrectNumberOfFixups = The ObjectManager found an invalid number of fixups. This usually indicates a problem in the Formatter.
-; The following serialization exception messages appear in native resources too (mscorrc.rc)
-Serialization_NonSerType = Type '{0}' in Assembly '{1}' is not marked as serializable.
-Serialization_ConstructorNotFound = The constructor to deserialize an object of type '{0}' was not found.
-
-; SerializationException used by Formatters
-Serialization_ArrayType = Invalid array type '{0}'.
-Serialization_ArrayTypeObject = Array element type is Object, 'dt' attribute is null.
-Serialization_Assembly = No assembly information is available for object on the wire, '{0}'.
-Serialization_AssemblyId = No assembly ID for object type '{0}'.
-Serialization_BinaryHeader = Binary stream '{0}' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.
-Serialization_CrossAppDomainError = Cross-AppDomain BinaryFormatter error; expected '{0}' but received '{1}'.
-Serialization_CorruptedStream = Invalid BinaryFormatter stream.
-Serialization_HeaderReflection = Header reflection error: number of value members: {0}.
-Serialization_ISerializableTypes = Types not available for ISerializable object '{0}'.
-Serialization_ISerializableMemberInfo = MemberInfo requested for ISerializable type.
-Serialization_MBRAsMBV = Type {0} must be marshaled by reference in this context.
-Serialization_Map = No map for object '{0}'.
-Serialization_MemberInfo = MemberInfo cannot be obtained for ISerialized Object '{0}'.
-Serialization_Method = Invalid MethodCall or MethodReturn stream format.
-Serialization_MissingMember = Member '{0}' in class '{1}' is not present in the serialized stream and is not marked with {2}.
-Serialization_NoMemberInfo = No MemberInfo for Object {0}.
-Serialization_ObjNoID = Object {0} has never been assigned an objectID.
-Serialization_ObjectTypeEnum = Invalid ObjectTypeEnum {0}.
-Serialization_ParseError = Parse error. Current element is not compatible with the next element, {0}.
-Serialization_SerMemberInfo = MemberInfo type {0} cannot be serialized.
-Serialization_Stream = Attempting to deserialize an empty stream.
-Serialization_StreamEnd = End of Stream encountered before parsing was completed.
-Serialization_TopObject = No top object.
-Serialization_TopObjectInstantiate = Top object cannot be instantiated for element '{0}'.
-Serialization_TypeCode = Invalid type code in stream '{0}'.
-Serialization_TypeExpected = Invalid expected type.
-Serialization_TypeMissing = Type is missing for member of type Object '{0}'.
-Serialization_TypeRead = Invalid read type request '{0}'.
-Serialization_TypeSecurity = Type {0} and the types derived from it (such as {1}) are not permitted to be deserialized at this security level.
-Serialization_TypeWrite = Invalid write type request '{0}'.
-Serialization_XMLElement = Invalid element '{0}'.
-Serialization_Security = Because of security restrictions, the type {0} cannot be accessed.
-Serialization_TypeLoadFailure = Unable to load type {0} required for deserialization.
-Serialization_RequireFullTrust = A type '{0}' that is defined in a partially trusted assembly cannot be type forwarded from an assembly with a different Public Key Token or without a public key token. To fix this, please either turn on unsafeTypeForwarding flag in the configuration file or remove the TypeForwardedFrom attribute.
-; The following serialization exception messages appear in native resources too (mscorrc.rc)
-Serialization_TypeResolved = Type is not resolved for member '{0}'.
-#endif // FEATURE_SERIALIZATION
-
-;
-; StringBuilder Exceptions
-;
-Arg_LongerThanSrcString = Source string was not long enough. Check sourceIndex and count.
-
-
-;
-; System.Threading
-;
-
-;
-; Thread Exceptions
-;
-ThreadState_NoAbortRequested = Unable to reset abort because no abort was requested.
-Threading.WaitHandleTooManyPosts = The WaitHandle cannot be signaled because it would exceed its maximum count.
-;
-; WaitHandleCannotBeOpenedException
-;
-Threading.WaitHandleCannotBeOpenedException = No handle of the given name exists.
-Threading.WaitHandleCannotBeOpenedException_InvalidHandle = A WaitHandle with system-wide name '{0}' cannot be created. A WaitHandle of a different type might have the same name.
-
-;
-; AbandonedMutexException
-;
-Threading.AbandonedMutexException = The wait completed due to an abandoned mutex.
-
-; AggregateException
-AggregateException_ctor_DefaultMessage=One or more errors occurred.
-AggregateException_ctor_InnerExceptionNull=An element of innerExceptions was null.
-AggregateException_DeserializationFailure=The serialization stream contains no inner exceptions.
-AggregateException_ToString={0}{1}---> (Inner Exception #{2}) {3}{4}{5}
-
-; Cancellation
-CancellationToken_CreateLinkedToken_TokensIsEmpty=No tokens were supplied.
-CancellationTokenSource_Disposed=The CancellationTokenSource has been disposed.
-CancellationToken_SourceDisposed=The CancellationTokenSource associated with this CancellationToken has been disposed.
-
-; Exceptions shared by all concurrent collection
-ConcurrentCollection_SyncRoot_NotSupported=The SyncRoot property may not be used for the synchronization of concurrent collections.
-
-; Exceptions shared by ConcurrentStack and ConcurrentQueue
-ConcurrentStackQueue_OnDeserialization_NoData=The serialization stream contains no elements.
-
-; ConcurrentStack<T>
-ConcurrentStack_PushPopRange_StartOutOfRange=The startIndex argument must be greater than or equal to zero.
-ConcurrentStack_PushPopRange_CountOutOfRange=The count argument must be greater than or equal to zero.
-ConcurrentStack_PushPopRange_InvalidCount=The sum of the startIndex and count arguments must be less than or equal to the collection's Count.
-
-; ConcurrentDictionary<TKey, TValue>
-ConcurrentDictionary_ItemKeyIsNull=TKey is a reference type and item.Key is null.
-ConcurrentDictionary_SourceContainsDuplicateKeys=The source argument contains duplicate keys.
-ConcurrentDictionary_IndexIsNegative=The index argument is less than zero.
-ConcurrentDictionary_ConcurrencyLevelMustBePositive=The concurrencyLevel argument must be positive.
-ConcurrentDictionary_CapacityMustNotBeNegative=The capacity argument must be greater than or equal to zero.
-ConcurrentDictionary_ArrayNotLargeEnough=The index is equal to or greater than the length of the array, or the number of elements in the dictionary is greater than the available space from index to the end of the destination array.
-ConcurrentDictionary_ArrayIncorrectType=The array is multidimensional, or the type parameter for the set cannot be cast automatically to the type of the destination array.
-ConcurrentDictionary_KeyAlreadyExisted=The key already existed in the dictionary.
-ConcurrentDictionary_TypeOfKeyIncorrect=The key was of an incorrect type for this dictionary.
-ConcurrentDictionary_TypeOfValueIncorrect=The value was of an incorrect type for this dictionary.
-
-; Partitioner
-Partitioner_DynamicPartitionsNotSupported=Dynamic partitions are not supported by this partitioner.
-
-; OrderablePartitioner
-OrderablePartitioner_GetPartitions_WrongNumberOfPartitions=GetPartitions returned an incorrect number of partitions.
-
-; PartitionerStatic
-PartitionerStatic_CurrentCalledBeforeMoveNext=MoveNext must be called at least once before calling Current.
-PartitionerStatic_CanNotCallGetEnumeratorAfterSourceHasBeenDisposed=Can not call GetEnumerator on partitions after the source enumerable is disposed
-
-; CDSCollectionETWBCLProvider events
-event_ConcurrentStack_FastPushFailed=Push to ConcurrentStack spun {0} time(s).
-event_ConcurrentStack_FastPopFailed=Pop from ConcurrentStack spun {0} time(s).
-event_ConcurrentDictionary_AcquiringAllLocks=ConcurrentDictionary acquiring all locks on {0} bucket(s).
-event_ConcurrentBag_TryTakeSteals=ConcurrentBag stealing in TryTake.
-event_ConcurrentBag_TryPeekSteals=ConcurrentBag stealing in TryPeek.
-
-; CountdownEvent
-CountdownEvent_Decrement_BelowZero=Invalid attempt made to decrement the event's count below zero.
-CountdownEvent_Increment_AlreadyZero=The event is already signaled and cannot be incremented.
-CountdownEvent_Increment_AlreadyMax=The increment operation would cause the CurrentCount to overflow.
-
-; Parallel
-Parallel_Invoke_ActionNull=One of the actions was null.
-Parallel_ForEach_OrderedPartitionerKeysNotNormalized=This method requires the use of an OrderedPartitioner with the KeysNormalized property set to true.
-Parallel_ForEach_PartitionerNotDynamic=The Partitioner used here must support dynamic partitioning.
-Parallel_ForEach_PartitionerReturnedNull=The Partitioner used here returned a null partitioner source.
-Parallel_ForEach_NullEnumerator=The Partitioner source returned a null enumerator.
-
-; Semaphore
-Argument_SemaphoreInitialMaximum=The initial count for the semaphore must be greater than or equal to zero and less than the maximum count.
-
-; SemaphoreFullException
-Threading_SemaphoreFullException=Adding the specified count to the semaphore would cause it to exceed its maximum count.
-
-; Lazy
-Lazy_ctor_ValueSelectorNull=The valueSelector argument is null.
-Lazy_ctor_InfoNull=The info argument is null.
-Lazy_ctor_deserialization_ValueInvalid=The Value cannot be null.
-Lazy_ctor_ModeInvalid=The mode argument specifies an invalid value.
-Lazy_CreateValue_NoParameterlessCtorForT=The lazily-initialized type does not have a public, parameterless constructor.
-Lazy_StaticInit_InvalidOperation=ValueFactory returned null.
-Lazy_Value_RecursiveCallsToValue=ValueFactory attempted to access the Value property of this instance.
-Lazy_ToString_ValueNotCreated=Value is not created.
-
-
-;ThreadLocal
-ThreadLocal_Value_RecursiveCallsToValue=ValueFactory attempted to access the Value property of this instance.
-ThreadLocal_Disposed=The ThreadLocal object has been disposed.
-ThreadLocal_ValuesNotAvailable=The ThreadLocal object is not tracking values. To use the Values property, use a ThreadLocal constructor that accepts the trackAllValues parameter and set the parameter to true.
-
-; SemaphoreSlim
-SemaphoreSlim_ctor_InitialCountWrong=The initialCount argument must be non-negative and less than or equal to the maximumCount.
-SemaphoreSlim_ctor_MaxCountWrong=The maximumCount argument must be a positive number. If a maximum is not required, use the constructor without a maxCount parameter.
-SemaphoreSlim_Wait_TimeoutWrong=The timeout must represent a value between -1 and Int32.MaxValue, inclusive.
-SemaphoreSlim_Release_CountWrong=The releaseCount argument must be greater than zero.
-SemaphoreSlim_Disposed=The semaphore has been disposed.
-
-; ManualResetEventSlim
-ManualResetEventSlim_ctor_SpinCountOutOfRange=The spinCount argument must be in the range 0 to {0}, inclusive.
-ManualResetEventSlim_ctor_TooManyWaiters=There are too many threads currently waiting on the event. A maximum of {0} waiting threads are supported.
-ManualResetEventSlim_Disposed=The event has been disposed.
-
-; SpinLock
-SpinLock_TryEnter_ArgumentOutOfRange=The timeout must be a value between -1 and Int32.MaxValue, inclusive.
-SpinLock_TryEnter_LockRecursionException=The calling thread already holds the lock.
-SpinLock_TryReliableEnter_ArgumentException=The tookLock argument must be set to false before calling this method.
-SpinLock_Exit_SynchronizationLockException=The calling thread does not hold the lock.
-SpinLock_IsHeldByCurrentThread=Thread tracking is disabled.
-
-; SpinWait
-SpinWait_SpinUntil_TimeoutWrong=The timeout must represent a value between -1 and Int32.MaxValue, inclusive.
-SpinWait_SpinUntil_ArgumentNull=The condition argument is null.
-
-; CdsSyncEtwBCLProvider events
-event_SpinLock_FastPathFailed=SpinLock beginning to spin.
-event_SpinWait_NextSpinWillYield=Next spin will yield.
-event_Barrier_PhaseFinished=Barrier finishing phase {1}.
-
-#if PLATFORM_UNIX
-; Unix threading
-PlatformNotSupported_NamedSynchronizationPrimitives=The named version of this synchronization primitive is not supported on this platform.
-PlatformNotSupported_NamedSyncObjectWaitAnyWaitAll=Wait operations on multiple wait handles including a named synchronization primitive are not supported on this platform.
-#endif
-
-;
-; System.Threading.Tasks
-;
-
-; AsyncMethodBuilder
-AsyncMethodBuilder_InstanceNotInitialized=The builder was not properly initialized.
-
-; TaskAwaiter and YieldAwaitable
-AwaitableAwaiter_InstanceNotInitialized=The awaitable or awaiter was not properly initialized.
-TaskAwaiter_TaskNotCompleted=The awaited task has not yet completed.
-
-; Task<T>
-TaskT_SetException_HasAnInitializer=A task's Exception may only be set directly if the task was created without a function.
-TaskT_TransitionToFinal_AlreadyCompleted=An attempt was made to transition a task to a final state when it had already completed.
-TaskT_ctor_SelfReplicating=It is invalid to specify TaskCreationOptions.SelfReplicating for a Task<TResult>.
-TaskT_DebuggerNoResult={Not yet computed}
-
-; Task
-Task_ctor_LRandSR=(Internal)An attempt was made to create a LongRunning SelfReplicating task.
-Task_ThrowIfDisposed=The task has been disposed.
-Task_Dispose_NotCompleted=A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled).
-Task_Start_Promise=Start may not be called on a promise-style task.
-Task_Start_AlreadyStarted=Start may not be called on a task that was already started.
-Task_Start_TaskCompleted=Start may not be called on a task that has completed.
-Task_Start_ContinuationTask=Start may not be called on a continuation task.
-Task_RunSynchronously_AlreadyStarted=RunSynchronously may not be called on a task that was already started.
-Task_RunSynchronously_TaskCompleted=RunSynchronously may not be called on a task that has already completed.
-Task_RunSynchronously_Promise=RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.
-Task_RunSynchronously_Continuation=RunSynchronously may not be called on a continuation task.
-Task_ContinueWith_NotOnAnything=The specified TaskContinuationOptions excluded all continuation kinds.
-Task_ContinueWith_ESandLR=The specified TaskContinuationOptions combined LongRunning and ExecuteSynchronously. Synchronous continuations should not be long running.
-Task_MultiTaskContinuation_NullTask=The tasks argument included a null value.
-Task_MultiTaskContinuation_FireOptions=It is invalid to exclude specific continuation kinds for continuations off of multiple tasks.
-Task_MultiTaskContinuation_EmptyTaskList=The tasks argument contains no tasks.
-Task_FromAsync_TaskManagerShutDown=FromAsync was called with a TaskManager that had already shut down.
-Task_FromAsync_SelfReplicating=It is invalid to specify TaskCreationOptions.SelfReplicating in calls to FromAsync.
-Task_FromAsync_LongRunning=It is invalid to specify TaskCreationOptions.LongRunning in calls to FromAsync.
-Task_FromAsync_PreferFairness=It is invalid to specify TaskCreationOptions.PreferFairness in calls to FromAsync.
-Task_WaitMulti_NullTask=The tasks array included at least one null element.
-Task_Delay_InvalidMillisecondsDelay=The value needs to be either -1 (signifying an infinite timeout), 0 or a positive integer.
-Task_Delay_InvalidDelay=The value needs to translate in milliseconds to -1 (signifying an infinite timeout), 0 or a positive integer less than or equal to Int32.MaxValue.
-
-; TaskCanceledException
-TaskCanceledException_ctor_DefaultMessage=A task was canceled.
-
-;TaskCompletionSource<T>
-TaskCompletionSourceT_TrySetException_NullException=The exceptions collection included at least one null element.
-TaskCompletionSourceT_TrySetException_NoExceptions=The exceptions collection was empty.
-
-;TaskExceptionHolder
-TaskExceptionHolder_UnknownExceptionType=(Internal)Expected an Exception or an IEnumerable<Exception>
-TaskExceptionHolder_UnhandledException=A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.
-
-; TaskScheduler
-TaskScheduler_ExecuteTask_TaskAlreadyExecuted=ExecuteTask may not be called for a task which was already executed.
-TaskScheduler_ExecuteTask_WrongTaskScheduler=ExecuteTask may not be called for a task which was previously queued to a different TaskScheduler.
-TaskScheduler_InconsistentStateAfterTryExecuteTaskInline=The TryExecuteTaskInline call to the underlying scheduler succeeded, but the task body was not invoked.
-TaskScheduler_FromCurrentSynchronizationContext_NoCurrent=The current SynchronizationContext may not be used as a TaskScheduler.
-
-; TaskSchedulerException
-TaskSchedulerException_ctor_DefaultMessage=An exception was thrown by a TaskScheduler.
-
-;
-; ParallelState ( used in Parallel.For(), Parallel.ForEach() )
-ParallelState_Break_InvalidOperationException_BreakAfterStop=Break was called after Stop was called.
-ParallelState_Stop_InvalidOperationException_StopAfterBreak=Stop was called after Break was called.
-ParallelState_NotSupportedException_UnsupportedMethod=This method is not supported.
-
-;
-; TPLETWProvider events
-event_ParallelLoopBegin=Beginning {3} loop {2} from Task {1}.
-event_ParallelLoopEnd=Ending loop {2} after {3} iterations.
-event_ParallelInvokeBegin=Beginning ParallelInvoke {2} from Task {1} for {4} actions.
-event_ParallelInvokeEnd=Ending ParallelInvoke {2}.
-event_ParallelFork=Task {1} entering fork/join {2}.
-event_ParallelJoin=Task {1} leaving fork/join {2}.
-event_TaskScheduled=Task {2} scheduled to TaskScheduler {0}.
-event_TaskStarted=Task {2} executing.
-event_TaskCompleted=Task {2} completed.
-event_TaskWaitBegin=Beginning wait ({3}) on Task {2}.
-event_TaskWaitEnd=Ending wait on Task {2}.
-
-
-;
-; Weak Reference Exception
-;
-WeakReference_NoLongerValid = The weak reference is no longer valid.
-
-
-;
-; Interop Exceptions
-;
-Interop.COM_TypeMismatch = Type mismatch between source and destination types.
-Interop_Marshal_Unmappable_Char = Cannot marshal: Encountered unmappable character.
-
-#if FEATURE_COMINTEROP_WINRT_DESKTOP_HOST
-WinRTHostDomainName = Windows Runtime Object Host Domain for '{0}'
-#endif
-
-;
-; Loader Exceptions
-;
-Loader_InvalidPath = Relative path must be a string that contains the substring, "..", or does not contain a root directory.
-Loader_Name = Name:
-Loader_NoContextPolicies = There are no context policies.
-Loader_ContextPolicies = Context Policies:
-
-;
-; AppDomain Exceptions
-AppDomain_RequireApplicationName = ApplicationName must be set before the DynamicBase can be set.
-AppDomain_AppBaseNotSet = The ApplicationBase must be set before retrieving this property.
-
-#if FEATURE_HOST_ASSEMBLY_RESOLVER
-AppDomain_BindingModelIsLocked = Binding model is already locked for the AppDomain and cannot be reset.
-Argument_CustomAssemblyLoadContextRequestedNameMismatch = Resolved assembly's simple name should be the same as of the requested assembly.
-#endif // FEATURE_HOST_ASSEMBLY_RESOLVER
-;
-; XMLSyntaxExceptions
-XMLSyntax_UnexpectedEndOfFile = Unexpected end of file.
-XMLSyntax_ExpectedCloseBracket = Expected > character.
-XMLSyntax_ExpectedSlashOrString = Expected / character or string.
-XMLSyntax_UnexpectedCloseBracket = Unexpected > character.
-XMLSyntax_SyntaxError = Invalid syntax on line {0}.
-XMLSyntax_SyntaxErrorEx = Invalid syntax on line {0} - '{1}'.
-XMLSyntax_InvalidSyntax = Invalid syntax.
-XML_Syntax_InvalidSyntaxInFile = Invalid XML in file '{0}' near element '{1}'.
-XMLSyntax_InvalidSyntaxSatAssemTag = Invalid XML in file "{0}" near element "{1}". The <satelliteassemblies> section only supports <assembly> tags.
-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}
-StrongName_Version = version = {0}
-Site_ToString = Site
-Publisher_ToString = Publisher
-Hash_ToString = Hash - {0} = {1}
-ApplicationDirectory_ToString = ApplicationDirectory
-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}'.
-
-;
-; begin System.TimeZoneInfo ArgumentException's
-;
-Argument_AdjustmentRulesNoNulls = The AdjustmentRule array cannot contain null elements.
-Argument_AdjustmentRulesOutOfOrder = The elements of the AdjustmentRule array must be in chronological order and must not overlap.
-Argument_AdjustmentRulesAmbiguousOverlap = The elements of the AdjustmentRule array must not contain ambiguous time periods that extend beyond the DateStart or DateEnd properties of the element.
-Argument_AdjustmentRulesrDaylightSavingTimeOverlap = The elements of the AdjustmentRule array must not contain Daylight Saving Time periods that overlap adjacent elements in such a way as to cause invalid or ambiguous time periods.
-Argument_AdjustmentRulesrDaylightSavingTimeOverlapNonRuleRange = The elements of the AdjustmentRule array must not contain Daylight Saving Time periods that overlap the DateStart or DateEnd properties in such a way as to cause invalid or ambiguous time periods.
-Argument_AdjustmentRulesInvalidOverlap = The elements of the AdjustmentRule array must not contain invalid time periods that extend beyond the DateStart or DateEnd properties of the element.
-Argument_ConvertMismatch = The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local.
-Argument_DateTimeHasTimeOfDay = The supplied DateTime includes a TimeOfDay setting. This is not supported.
-Argument_DateTimeIsInvalid = The supplied DateTime represents an invalid time. For example, when the clock is adjusted forward, any time in the period that is skipped is invalid.
-Argument_DateTimeIsNotAmbiguous = The supplied DateTime is not in an ambiguous time range.
-Argument_DateTimeOffsetIsNotAmbiguous = The supplied DateTimeOffset is not in an ambiguous time range.
-Argument_DateTimeKindMustBeUnspecifiedOrUtc = The supplied DateTime must have the Kind property set to DateTimeKind.Unspecified or DateTimeKind.Utc.
-Argument_DateTimeHasTicks = The supplied DateTime must have the Year, Month, and Day properties set to 1. The time cannot be specified more precisely than whole milliseconds.
-Argument_InvalidId = The specified ID parameter '{0}' is not supported.
-Argument_InvalidSerializedString = The specified serialized string '{0}' is not supported.
-Argument_InvalidREG_TZI_FORMAT = The REG_TZI_FORMAT structure is corrupt.
-Argument_OutOfOrderDateTimes = The DateStart property must come before the DateEnd property.
-Argument_TimeSpanHasSeconds = The TimeSpan parameter cannot be specified more precisely than whole minutes.
-Argument_TimeZoneInfoBadTZif = The tzfile does not begin with the magic characters 'TZif'. Please verify that the file is not corrupt.
-Argument_TimeZoneInfoInvalidTZif = The TZif data structure is corrupt.
-Argument_TransitionTimesAreIdentical = The DaylightTransitionStart property must not equal the DaylightTransitionEnd property.
-;
-; begin System.TimeZoneInfo ArgumentOutOfRangeException's
-;
-ArgumentOutOfRange_DayParam = The Day parameter must be in the range 1 through 31.
-ArgumentOutOfRange_DayOfWeek = The DayOfWeek enumeration must be in the range 0 through 6.
-ArgumentOutOfRange_MonthParam = The Month parameter must be in the range 1 through 12.
-ArgumentOutOfRange_UtcOffset = The TimeSpan parameter must be within plus or minus 14.0 hours.
-ArgumentOutOfRange_UtcOffsetAndDaylightDelta = The sum of the BaseUtcOffset and DaylightDelta properties must within plus or minus 14.0 hours.
-ArgumentOutOfRange_Week = The Week parameter must be in the range 1 through 5.
-;
-; begin System.TimeZoneInfo InvalidTimeZoneException's
-;
-InvalidTimeZone_InvalidRegistryData = The time zone ID '{0}' was found on the local computer, but the registry information was corrupt.
-InvalidTimeZone_InvalidFileData = The time zone ID '{0}' was found on the local computer, but the file at '{1}' was corrupt.
-InvalidTimeZone_InvalidWin32APIData = The Local time zone was found on the local computer, but the data was corrupt.
-InvalidTimeZone_NoTTInfoStructures = There are no ttinfo structures in the tzfile. At least one ttinfo structure is required in order to construct a TimeZoneInfo object.
-InvalidTimeZone_UnparseablePosixMDateString = '{0}' is not a valid POSIX-TZ-environment-variable MDate rule. A valid rule has the format 'Mm.w.d'.
-InvalidTimeZone_JulianDayNotSupported = Julian dates in POSIX strings are unsupported.
-;
-; begin System.TimeZoneInfo SecurityException's
-;
-Security_CannotReadRegistryData = The time zone ID '{0}' was found on the local computer, but the application does not have permission to read the registry information.
-Security_CannotReadFileData = The time zone ID '{0}' was found on the local computer, but the application does not have permission to read the file.
-;
-; begin System.TimeZoneInfo SerializationException's
-;
-Serialization_CorruptField = The value of the field '{0}' is invalid. The serialized data is corrupt.
-Serialization_InvalidEscapeSequence = The serialized data contained an invalid escape sequence '\\{0}'.
-;
-; begin System.TimeZoneInfo TimeZoneNotFoundException's
-;
-TimeZoneNotFound_MissingData = The time zone ID '{0}' was not found on the local computer.
-;
-; end System.TimeZoneInfo
-;
-
-
-; Tuple
-ArgumentException_TupleIncorrectType=Argument must be of type {0}.
-ArgumentException_TupleNonIComparableElement=The tuple contains an element of type {0} which does not implement the IComparable interface.
-ArgumentException_TupleLastArgumentNotATuple=The last element of an eight element tuple must be a Tuple.
-ArgumentException_OtherNotArrayOfCorrectLength=Object is not a array with the same number of elements as the array to compare it to.
-
-; WinRT collection adapters
-Argument_IndexOutOfArrayBounds=The specified index is out of bounds of the specified array.
-Argument_InsufficientSpaceToCopyCollection=The specified space is not sufficient to copy the elements from this Collection.
-ArgumentOutOfRange_IndexLargerThanMaxValue=This collection cannot work with indices larger than Int32.MaxValue - 1 (0x7FFFFFFF - 1).
-ArgumentOutOfRange_IndexOutOfRange=The specified index is outside the current index range of this collection.
-InvalidOperation_CollectionBackingListTooLarge=The collection backing this List contains too many elements.
-InvalidOperation_CollectionBackingDictionaryTooLarge=The collection backing this Dictionary contains too many elements.
-InvalidOperation_CannotRemoveLastFromEmptyCollection=Cannot remove the last element from an empty collection.
-
-; 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:
-;
-;Total items: 147
-;
-Globalization.cp_1200 = Unicode
-Globalization.cp_1201 = Unicode (Big-Endian)
-Globalization.cp_65001 = Unicode (UTF-8)
-Globalization.cp_65000 = Unicode (UTF-7)
-Globalization.cp_12000 = Unicode (UTF-32)
-Globalization.cp_12001 = Unicode (UTF-32 Big-Endian)
-Globalization.cp_20127 = US-ASCII
-Globalization.cp_28591 = Western European (ISO)
-
-#if FEATURE_NON_UNICODE_CODE_PAGES
-Globalization.cp_37 = IBM EBCDIC (US-Canada)
-Globalization.cp_437 = OEM United States
-Globalization.cp_500 = IBM EBCDIC (International)
-Globalization.cp_708 = Arabic (ASMO 708)
-Globalization.cp_720 = Arabic (DOS)
-Globalization.cp_737 = Greek (DOS)
-Globalization.cp_775 = Baltic (DOS)
-Globalization.cp_850 = Western European (DOS)
-Globalization.cp_852 = Central European (DOS)
-Globalization.cp_855 = OEM Cyrillic
-Globalization.cp_857 = Turkish (DOS)
-Globalization.cp_858 = OEM Multilingual Latin I
-Globalization.cp_860 = Portuguese (DOS)
-Globalization.cp_861 = Icelandic (DOS)
-Globalization.cp_862 = Hebrew (DOS)
-Globalization.cp_863 = French Canadian (DOS)
-Globalization.cp_864 = Arabic (864)
-Globalization.cp_865 = Nordic (DOS)
-Globalization.cp_866 = Cyrillic (DOS)
-Globalization.cp_869 = Greek, Modern (DOS)
-Globalization.cp_870 = IBM EBCDIC (Multilingual Latin-2)
-Globalization.cp_874 = Thai (Windows)
-Globalization.cp_875 = IBM EBCDIC (Greek Modern)
-Globalization.cp_932 = Japanese (Shift-JIS)
-Globalization.cp_936 = Chinese Simplified (GB2312)
-Globalization.cp_949 = Korean
-Globalization.cp_950 = Chinese Traditional (Big5)
-Globalization.cp_1026 = IBM EBCDIC (Turkish Latin-5)
-Globalization.cp_1047 = IBM Latin-1
-Globalization.cp_1140 = IBM EBCDIC (US-Canada-Euro)
-Globalization.cp_1141 = IBM EBCDIC (Germany-Euro)
-Globalization.cp_1142 = IBM EBCDIC (Denmark-Norway-Euro)
-Globalization.cp_1143 = IBM EBCDIC (Finland-Sweden-Euro)
-Globalization.cp_1144 = IBM EBCDIC (Italy-Euro)
-Globalization.cp_1145 = IBM EBCDIC (Spain-Euro)
-Globalization.cp_1146 = IBM EBCDIC (UK-Euro)
-Globalization.cp_1147 = IBM EBCDIC (France-Euro)
-Globalization.cp_1148 = IBM EBCDIC (International-Euro)
-Globalization.cp_1149 = IBM EBCDIC (Icelandic-Euro)
-Globalization.cp_1250 = Central European (Windows)
-Globalization.cp_1251 = Cyrillic (Windows)
-Globalization.cp_1252 = Western European (Windows)
-Globalization.cp_1253 = Greek (Windows)
-Globalization.cp_1254 = Turkish (Windows)
-Globalization.cp_1255 = Hebrew (Windows)
-Globalization.cp_1256 = Arabic (Windows)
-Globalization.cp_1257 = Baltic (Windows)
-Globalization.cp_1258 = Vietnamese (Windows)
-Globalization.cp_1361 = Korean (Johab)
-Globalization.cp_10000 = Western European (Mac)
-Globalization.cp_10001 = Japanese (Mac)
-Globalization.cp_10002 = Chinese Traditional (Mac)
-Globalization.cp_10003 = Korean (Mac)
-Globalization.cp_10004 = Arabic (Mac)
-Globalization.cp_10005 = Hebrew (Mac)
-Globalization.cp_10006 = Greek (Mac)
-Globalization.cp_10007 = Cyrillic (Mac)
-Globalization.cp_10008 = Chinese Simplified (Mac)
-Globalization.cp_10010 = Romanian (Mac)
-Globalization.cp_10017 = Ukrainian (Mac)
-Globalization.cp_10021 = Thai (Mac)
-Globalization.cp_10029 = Central European (Mac)
-Globalization.cp_10079 = Icelandic (Mac)
-Globalization.cp_10081 = Turkish (Mac)
-Globalization.cp_10082 = Croatian (Mac)
-Globalization.cp_20000 = Chinese Traditional (CNS)
-Globalization.cp_20001 = TCA Taiwan
-Globalization.cp_20002 = Chinese Traditional (Eten)
-Globalization.cp_20003 = IBM5550 Taiwan
-Globalization.cp_20004 = TeleText Taiwan
-Globalization.cp_20005 = Wang Taiwan
-Globalization.cp_20105 = Western European (IA5)
-Globalization.cp_20106 = German (IA5)
-Globalization.cp_20107 = Swedish (IA5)
-Globalization.cp_20108 = Norwegian (IA5)
-Globalization.cp_20261 = T.61
-Globalization.cp_20269 = ISO-6937
-Globalization.cp_20273 = IBM EBCDIC (Germany)
-Globalization.cp_20277 = IBM EBCDIC (Denmark-Norway)
-Globalization.cp_20278 = IBM EBCDIC (Finland-Sweden)
-Globalization.cp_20280 = IBM EBCDIC (Italy)
-Globalization.cp_20284 = IBM EBCDIC (Spain)
-Globalization.cp_20285 = IBM EBCDIC (UK)
-Globalization.cp_20290 = IBM EBCDIC (Japanese katakana)
-Globalization.cp_20297 = IBM EBCDIC (France)
-Globalization.cp_20420 = IBM EBCDIC (Arabic)
-Globalization.cp_20423 = IBM EBCDIC (Greek)
-Globalization.cp_20424 = IBM EBCDIC (Hebrew)
-Globalization.cp_20833 = IBM EBCDIC (Korean Extended)
-Globalization.cp_20838 = IBM EBCDIC (Thai)
-Globalization.cp_20866 = Cyrillic (KOI8-R)
-Globalization.cp_20871 = IBM EBCDIC (Icelandic)
-Globalization.cp_20880 = IBM EBCDIC (Cyrillic Russian)
-Globalization.cp_20905 = IBM EBCDIC (Turkish)
-Globalization.cp_20924 = IBM Latin-1
-Globalization.cp_20932 = Japanese (JIS 0208-1990 and 0212-1990)
-Globalization.cp_20936 = Chinese Simplified (GB2312-80)
-Globalization.cp_20949 = Korean Wansung
-Globalization.cp_21025 = IBM EBCDIC (Cyrillic Serbian-Bulgarian)
-Globalization.cp_21027 = Ext Alpha Lowercase
-Globalization.cp_21866 = Cyrillic (KOI8-U)
-Globalization.cp_28592 = Central European (ISO)
-Globalization.cp_28593 = Latin 3 (ISO)
-Globalization.cp_28594 = Baltic (ISO)
-Globalization.cp_28595 = Cyrillic (ISO)
-Globalization.cp_28596 = Arabic (ISO)
-Globalization.cp_28597 = Greek (ISO)
-Globalization.cp_28598 = Hebrew (ISO-Visual)
-Globalization.cp_28599 = Turkish (ISO)
-Globalization.cp_28603 = Estonian (ISO)
-Globalization.cp_28605 = Latin 9 (ISO)
-Globalization.cp_29001 = Europa
-Globalization.cp_38598 = Hebrew (ISO-Logical)
-Globalization.cp_50000 = User Defined
-Globalization.cp_50220 = Japanese (JIS)
-Globalization.cp_50221 = Japanese (JIS-Allow 1 byte Kana)
-Globalization.cp_50222 = Japanese (JIS-Allow 1 byte Kana - SO/SI)
-Globalization.cp_50225 = Korean (ISO)
-Globalization.cp_50227 = Chinese Simplified (ISO-2022)
-Globalization.cp_50229 = Chinese Traditional (ISO-2022)
-Globalization.cp_50930 = IBM EBCDIC (Japanese and Japanese Katakana)
-Globalization.cp_50931 = IBM EBCDIC (Japanese and US-Canada)
-Globalization.cp_50933 = IBM EBCDIC (Korean and Korean Extended)
-Globalization.cp_50935 = IBM EBCDIC (Simplified Chinese)
-Globalization.cp_50937 = IBM EBCDIC (Traditional Chinese)
-Globalization.cp_50939 = IBM EBCDIC (Japanese and Japanese-Latin)
-Globalization.cp_51932 = Japanese (EUC)
-Globalization.cp_51936 = Chinese Simplified (EUC)
-Globalization.cp_51949 = Korean (EUC)
-Globalization.cp_52936 = Chinese Simplified (HZ)
-Globalization.cp_54936 = Chinese Simplified (GB18030)
-Globalization.cp_57002 = ISCII Devanagari
-Globalization.cp_57003 = ISCII Bengali
-Globalization.cp_57004 = ISCII Tamil
-Globalization.cp_57005 = ISCII Telugu
-Globalization.cp_57006 = ISCII Assamese
-Globalization.cp_57007 = ISCII Oriya
-Globalization.cp_57008 = ISCII Kannada
-Globalization.cp_57009 = ISCII Malayalam
-Globalization.cp_57010 = ISCII Gujarati
-Globalization.cp_57011 = ISCII Punjabi
-#endif // FEATURE_NON_UNICODE_CODE_PAGES
-#endif // INCLUDE_DEBUG
-
-;------------------
-